Greasy Fork is available in English.

HeroWarsDungeon

Automation of actions for the game Hero Wars

  1. // ==UserScript==
  2. // @name HeroWarsDungeon
  3. // @name:en HeroWarsDungeon
  4. // @name:ru HeroWarsDungeon
  5. // @namespace HeroWarsDungeon
  6. // @version 2.312
  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, ApuoH, Gudwin
  11. // @license Copyright ZingerY
  12. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  13. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  14. // @match https://www.hero-wars.com/*
  15. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. // сделал ApuoH
  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. let repleyBattle = {
  68. defenders: {},
  69. attackers: {},
  70. effects: {},
  71. state: {},
  72. seed: undefined
  73. }
  74. /**
  75. * User data
  76. *
  77. * Данные пользователя
  78. */
  79. let userInfo;
  80. this.isTimeBetweenNewDays = function () {
  81. if (userInfo.timeZone <= 3) {
  82. return false;
  83. }
  84. const nextDayTs = new Date(userInfo.nextDayTs * 1e3);
  85. const nextServerDayTs = new Date(userInfo.nextServerDayTs * 1e3);
  86. if (nextDayTs > nextServerDayTs) {
  87. nextDayTs.setDate(nextDayTs.getDate() - 1);
  88. }
  89. const now = Date.now();
  90. if (now > nextDayTs && now < nextServerDayTs) {
  91. return true;
  92. }
  93. return false;
  94. };
  95. /**
  96. * Original methods for working with AJAX
  97. *
  98. * Оригинальные методы для работы с AJAX
  99. */
  100. const original = {
  101. open: XMLHttpRequest.prototype.open,
  102. send: XMLHttpRequest.prototype.send,
  103. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  104. SendWebSocket: WebSocket.prototype.send,
  105. fetch: fetch,
  106. };
  107.  
  108. // Sentry blocking
  109. // Блокировка наблюдателя
  110. this.fetch = function (url, options) {
  111. /**
  112. * Checking URL for blocking
  113. * Проверяем URL на блокировку
  114. */
  115. if (url.includes('sentry.io')) {
  116. console.log('%cFetch blocked', 'color: red');
  117. console.log(url, options);
  118. const body = {
  119. id: md5(Date.now()),
  120. };
  121. let info = {};
  122. try {
  123. info = JSON.parse(options.body);
  124. } catch (e) {}
  125. if (info.event_id) {
  126. body.id = info.event_id;
  127. }
  128. /**
  129. * Mock response for blocked URL
  130. *
  131. * Мокаем ответ для заблокированного URL
  132. */
  133. const mockResponse = new Response('Custom blocked response', {
  134. status: 200,
  135. headers: { 'Content-Type': 'application/json' },
  136. body,
  137. });
  138. return Promise.resolve(mockResponse);
  139. } else {
  140. /**
  141. * Call the original fetch function for all other URLs
  142. * Вызываем оригинальную функцию fetch для всех других URL
  143. */
  144. return original.fetch.apply(this, arguments);
  145. }
  146. };
  147.  
  148. /**
  149. * Decoder for converting byte data to JSON string
  150. *
  151. * Декодер для перобразования байтовых данных в JSON строку
  152. */
  153. const decoder = new TextDecoder("utf-8");
  154. /**
  155. * Stores a history of requests
  156. *
  157. * Хранит историю запросов
  158. */
  159. let requestHistory = {};
  160. /**
  161. * URL for API requests
  162. *
  163. * URL для запросов к API
  164. */
  165. let apiUrl = '';
  166.  
  167. /**
  168. * Connecting to the game code
  169. *
  170. * Подключение к коду игры
  171. */
  172. this.cheats = new hackGame();
  173. /**
  174. * The function of calculating the results of the battle
  175. *
  176. * Функция расчета результатов боя
  177. */
  178. this.BattleCalc = cheats.BattleCalc;
  179. /**
  180. * Sending a request available through the console
  181. *
  182. * Отправка запроса доступная через консоль
  183. */
  184. this.SendRequest = send;
  185. /**
  186. * Simple combat calculation available through the console
  187. *
  188. * Простой расчет боя доступный через консоль
  189. */
  190. this.Calc = function (data) {
  191. const type = getBattleType(data?.type);
  192. return new Promise((resolve, reject) => {
  193. try {
  194. BattleCalc(data, type, resolve);
  195. } catch (e) {
  196. reject(e);
  197. }
  198. })
  199. }
  200. //тест остановка подземки
  201. let stopDung = false;
  202. /**
  203. * Short asynchronous request
  204. * Usage example (returns information about a character):
  205. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  206. *
  207. * Короткий асинхронный запрос
  208. * Пример использования (возвращает информацию о персонаже):
  209. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  210. */
  211. this.Send = function (json, pr) {
  212. return new Promise((resolve, reject) => {
  213. try {
  214. send(json, resolve, pr);
  215. } catch (e) {
  216. reject(e);
  217. }
  218. })
  219. }
  220.  
  221. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  222. const i18nLangData = {
  223. /* English translation by BaBa */
  224. en: {
  225. /* Checkboxes */
  226. SKIP_FIGHTS: 'Skip battle',
  227. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  228. ENDLESS_CARDS: 'Infinite cards',
  229. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  230. AUTO_EXPEDITION: 'Auto Expedition',
  231. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  232. CANCEL_FIGHT: 'Cancel battle',
  233. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  234. GIFTS: 'Gifts',
  235. GIFTS_TITLE: 'Collect gifts automatically',
  236. BATTLE_RECALCULATION: 'Battle recalculation',
  237. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  238. BATTLE_FISHING: 'Finishing',
  239. BATTLE_FISHING_TITLE: 'Finishing off the team from the last replay in the chat',
  240. BATTLE_TRENING: 'Workout',
  241. BATTLE_TRENING_TITLE: 'A training battle in the chat against the team from the last replay',
  242. QUANTITY_CONTROL: 'Quantity control',
  243. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  244. REPEAT_CAMPAIGN: 'Repeat missions',
  245. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  246. DISABLE_DONAT: 'Disable donation',
  247. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  248. DAILY_QUESTS: 'Quests',
  249. DAILY_QUESTS_TITLE: 'Complete daily quests',
  250. AUTO_QUIZ: 'AutoQuiz',
  251. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  252. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  253. HIDE_SERVERS: 'Collapse servers',
  254. HIDE_SERVERS_TITLE: 'Hide unused servers',
  255. /* Input fields */
  256. HOW_MUCH_TITANITE: 'How much titanite to farm',
  257. COMBAT_SPEED: 'Combat Speed Multiplier',
  258. HOW_REPEAT_CAMPAIGN: 'how many mission replays', //тест добавил
  259. NUMBER_OF_TEST: 'Number of test fights',
  260. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  261. USER_ID_TITLE: 'Enter the player ID',
  262. AMOUNT: 'Gift number, 1 - hero development, 2 - pets, 3 - light, 4 - darkness, 5 - ascension, 6 - appearance',
  263. GIFT_NUM: 'Number of gifts to be sent',
  264. /* Buttons */
  265. RUN_SCRIPT: 'Run the',
  266. STOP_SCRIPT: 'Stop the',
  267. TO_DO_EVERYTHING: 'Do All',
  268. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  269. OUTLAND: 'Outland',
  270. OUTLAND_TITLE: 'Collect Outland',
  271. TITAN_ARENA: 'ToE',
  272. TITAN_ARENA_TITLE: 'Complete the titan arena',
  273. DUNGEON: 'Dungeon',
  274. DUNGEON_TITLE: 'Go through the dungeon',
  275. DUNGEON2: 'Dungeon full',
  276. DUNGEON_FULL_TITLE: 'Dungeon for Full Titans',
  277. STOP_DUNGEON: 'Stop Dungeon',
  278. STOP_DUNGEON_TITLE: 'Stop digging the dungeon',
  279. SEER: 'Seer',
  280. SEER_TITLE: 'Roll the Seer',
  281. TOWER: 'Tower',
  282. TOWER_TITLE: 'Pass the tower',
  283. EXPEDITIONS: 'Expeditions',
  284. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  285. SYNC: 'Sync',
  286. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  287. ARCHDEMON: 'Archdemon',
  288. FURNACE_OF_SOULS: 'Furnace of souls',
  289. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  290. ESTER_EGGS: 'Easter eggs',
  291. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  292. REWARDS: 'Rewards',
  293. REWARDS_TITLE: 'Collect all quest rewards',
  294. MAIL: 'Mail',
  295. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  296. MINIONS: 'Minions',
  297. MINIONS_TITLE: 'Attack minions with saved packs',
  298. ADVENTURE: 'Adventure',
  299. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  300. STORM: 'Storm',
  301. STORM_TITLE: 'Passes the Storm along the specified route',
  302. SANCTUARY: 'Sanctuary',
  303. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  304. GUILD_WAR: 'Guild War',
  305. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  306. SECRET_WEALTH: 'Secret Wealth',
  307. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  308. /* Misc */
  309. BOTTOM_URLS: '<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>',
  310. GIFTS_SENT: 'Gifts sent!',
  311. DO_YOU_WANT: 'Do you really want to do this?',
  312. BTN_RUN: 'Run',
  313. BTN_CANCEL: 'Cancel',
  314. BTN_OK: 'OK',
  315. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  316. BTN_AUTO: 'Auto',
  317. MSG_YOU_APPLIED: 'You applied',
  318. MSG_DAMAGE: 'damage',
  319. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  320. MSG_REPEAT_MISSION: 'Repeat the mission?',
  321. BTN_REPEAT: 'Repeat',
  322. BTN_NO: 'No',
  323. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  324. BTN_OPEN: 'Open',
  325. QUESTION_COPY: 'Question copied to clipboard',
  326. ANSWER_KNOWN: 'The answer is known',
  327. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  328. BEING_RECALC: 'The battle is being recalculated',
  329. THIS_TIME: 'This time',
  330. VICTORY: '<span style="color:green;">VICTORY</span>',
  331. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  332. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  333. OPEN_DOLLS: 'nesting dolls recursively',
  334. SENT_QUESTION: 'Question sent',
  335. SETTINGS: 'Settings',
  336. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  337. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  338. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  339. VALUES: 'Values',
  340. SAVING: 'Saving',
  341. USER_ID: 'User Id',
  342. SEND_GIFT: 'The gift has been sent',
  343. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  344. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  345. TITANIT: 'Titanit',
  346. COMPLETED: 'completed',
  347. FLOOR: 'Floor',
  348. LEVEL: 'Level',
  349. BATTLES: 'battles',
  350. EVENT: 'Event',
  351. NOT_AVAILABLE: 'not available',
  352. NO_HEROES: 'No heroes',
  353. DAMAGE_AMOUNT: 'Damage amount',
  354. NOTHING_TO_COLLECT: 'Nothing to collect',
  355. COLLECTED: 'Collected',
  356. REWARD: 'rewards',
  357. REMAINING_ATTEMPTS: 'Remaining attempts',
  358. BATTLES_CANCELED: 'Battles canceled',
  359. MINION_RAID: 'Minion Raid',
  360. STOPPED: 'Stopped',
  361. REPETITIONS: 'Repetitions',
  362. MISSIONS_PASSED: 'Missions passed',
  363. STOP: 'stop',
  364. TOTAL_OPEN: 'Total open',
  365. OPEN: 'Open',
  366. ROUND_STAT: 'Damage statistics for ',
  367. BATTLE: 'battles',
  368. MINIMUM: 'Minimum',
  369. MAXIMUM: 'Maximum',
  370. AVERAGE: 'Average',
  371. NOT_THIS_TIME: 'Not this time',
  372. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  373. SUCCESS: 'Success',
  374. RECEIVED: 'Received',
  375. LETTERS: 'letters',
  376. PORTALS: 'portals',
  377. ATTEMPTS: 'attempts',
  378. /* Quests */
  379. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  380. QUEST_10002: 'Complete 10 missions',
  381. QUEST_10003: 'Complete 3 heroic missions',
  382. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  383. QUEST_10006: 'Use the exchange of emeralds 1 time',
  384. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  385. QUEST_10016: 'Send gifts to guildmates',
  386. QUEST_10018: 'Use an experience potion',
  387. QUEST_10019: 'Open 1 chest in the Tower',
  388. QUEST_10020: 'Open 3 chests in Outland',
  389. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  390. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  391. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  392. QUEST_10024: 'Level up any artifact once',
  393. QUEST_10025: 'Start Expedition 1',
  394. QUEST_10026: 'Start 4 Expeditions',
  395. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  396. QUEST_10028: 'Level up any titan artifact',
  397. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  398. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  399. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  400. QUEST_10043: 'Start or Join an Adventure',
  401. QUEST_10044: 'Use Summon Pets 1 time',
  402. QUEST_10046: 'Open 3 chests in Adventure',
  403. QUEST_10047: 'Get 150 Guild Activity Points',
  404. NOTHING_TO_DO: 'Nothing to do',
  405. YOU_CAN_COMPLETE: 'You can complete quests',
  406. BTN_DO_IT: 'Do it',
  407. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  408. COMPLETED_QUESTS: 'Completed quests',
  409. /* everything button */
  410. ASSEMBLE_OUTLAND: 'Assemble Outland',
  411. PASS_THE_TOWER: 'Pass the tower',
  412. CHECK_EXPEDITIONS: 'Check Expeditions',
  413. COMPLETE_TOE: 'Complete ToE',
  414. COMPLETE_DUNGEON: 'Complete the dungeon',
  415. COMPLETE_DUNGEON_FULL: 'Complete the dungeon for Full Titans',
  416. COLLECT_MAIL: 'Collect mail',
  417. COLLECT_MISC: 'Collect some bullshit',
  418. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  419. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  420. MAKE_A_SYNC: 'Make a sync',
  421.  
  422. RUN_FUNCTION: 'Run the following functions?',
  423. BTN_GO: 'Go!',
  424. PERFORMED: 'Performed',
  425. DONE: 'Done',
  426. ERRORS_OCCURRES: 'Errors occurred while executing',
  427. COPY_ERROR: 'Copy error information to clipboard',
  428. BTN_YES: 'Yes',
  429. ALL_TASK_COMPLETED: 'All tasks completed',
  430.  
  431. UNKNOWN: 'unknown',
  432. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  433. START_ADVENTURE: 'Start your adventure along this path!',
  434. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  435. BTN_CANCELED: 'Canceled',
  436. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  437. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  438. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  439. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  440. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  441. YES_CONTINUE: 'Yes, continue!',
  442. NOT_ENOUGH_AP: 'Not enough action points',
  443. ATTEMPTS_ARE_OVER: 'The attempts are over',
  444. MOVES: 'Moves',
  445. BUFF_GET_ERROR: 'Buff getting error',
  446. BATTLE_END_ERROR: 'Battle end error',
  447. AUTOBOT: 'Autobot',
  448. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  449. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  450. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  451. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  452. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  453. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  454. FIND_COEFF: 'Find the coefficient greater than',
  455. BTN_PASS: 'PASS',
  456. BRAWLS: 'Brawls',
  457. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  458. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  459. LOSSES: 'Losses',
  460. WINS: 'Wins',
  461. FIGHTS: 'Fights',
  462. STAGE: 'Stage',
  463. DONT_HAVE_LIVES: "You don't have lives",
  464. LIVES: 'Lives',
  465. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  466. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  467. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  468. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  469. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  470. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  471. DAILY_BONUS: 'Daily bonus',
  472. DO_DAILY_QUESTS: 'Do daily quests',
  473. ACTIONS: 'Actions',
  474. ACTIONS_TITLE: 'Dialog box with various actions',
  475. OTHERS: 'Others',
  476. OTHERS_TITLE: 'Others',
  477. CHOOSE_ACTION: 'Choose an action',
  478. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  479. STAMINA: 'Energy',
  480. BOXES_OVER: 'The boxes are over',
  481. NO_BOXES: 'No boxes',
  482. NO_MORE_ACTIVITY: 'No more activity for items today',
  483. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  484. GET_ACTIVITY: 'Get Activity',
  485. NOT_ENOUGH_ITEMS: 'Not enough items',
  486. ACTIVITY_RECEIVED: 'Activity received',
  487. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  488. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  489. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need {imgEmerald}540 you have {imgEmerald}{currentStarMoney}',
  490. BUY_OUTLAND_BTN: 'Buy {count} chests {imgEmerald}{countEmerald}',
  491. CHESTS_NOT_AVAILABLE: 'Chests not available',
  492. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  493. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  494. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  495. SOMETHING_WENT_WRONG: 'Something went wrong',
  496. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  497. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  498. GET_ENERGY: 'Get Energy',
  499. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  500. ITEM_EXCHANGE: 'Item Exchange',
  501. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  502. BUY_SOULS: 'Buy souls',
  503. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  504. BUY_OUTLAND: 'Buy Outland',
  505. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  506. RAID: 'Raid',
  507. AUTO_RAID_ADVENTURE: 'Raid adventure',
  508. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  509. CLAN_STAT: 'Clan statistics',
  510. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  511. BTN_AUTO_F5: 'Auto (F5)',
  512. BOSS_DAMAGE: 'Boss Damage: ',
  513. NOTHING_BUY: 'Nothing to buy',
  514. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  515. BUY_FOR_GOLD: 'Buy for gold',
  516. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  517. REWARDS_AND_MAIL: 'Rewards and Mail',
  518. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  519. New_Year_Clan: 'a gift for a friend',
  520. New_Year_Clan_TITLE: 'New Year gifts to friends',
  521. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  522. TIMER_ALREADY: 'Timer already started {time}',
  523. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  524. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  525. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  526. EPIC_BRAWL: 'Cosmic Battle',
  527. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  528. RELOAD_GAME: 'Reload game',
  529. TIMER: 'Timer:',
  530. SHOW_ERRORS: 'Show errors',
  531. SHOW_ERRORS_TITLE: 'Show server request errors',
  532. ERROR_MSG: 'Error: {name}<br>{description}',
  533. EVENT_AUTO_BOSS: '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?',
  534. BEST_SLOW: 'Best (slower)',
  535. FIRST_FAST: 'First (faster)',
  536. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  537. ERROR_F12: 'Error, details in the console (F12)',
  538. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  539. BEST_PACK: 'Best pack:',
  540. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  541. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  542. BOSS_VICTORY_IMPOSSIBLE: '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?',
  543. BOSS_HAS_BEEN_DEF_TEXT: 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts{winTimer}<br>(Please synchronize or restart the game to update the data)',
  544. MAP: 'Map: ',
  545. PLAYER_POS: 'Player positions:',
  546. NY_GIFTS: 'Gifts',
  547. NY_GIFTS_TITLE: "Open all New Year's gifts",
  548. NY_NO_GIFTS: 'No gifts not received',
  549. NY_GIFTS_COLLECTED: '{count} gifts collected',
  550. CHANGE_MAP: 'Island map',
  551. CHANGE_MAP_TITLE: 'Change island map',
  552. SELECT_ISLAND_MAP: 'Select an island map:',
  553. MAP_NUM: 'Map {num}',
  554. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  555. SHOPS: 'Shops',
  556. SHOPS_DEFAULT: 'Default',
  557. SHOPS_DEFAULT_TITLE: 'Default stores',
  558. SHOPS_LIST: 'Shops {number}',
  559. SHOPS_LIST_TITLE: 'List of shops {number}',
  560. SHOPS_WARNING: '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>',
  561. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  562. FAST_SEASON: 'Fast season',
  563. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  564. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  565. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  566. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  567. IMPROVED_LEVELS: 'Improved levels: {count}',
  568. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  569. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  570. SKINS_UPGRADE: 'Skins Upgrade',
  571. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  572. HINT: '<br>Hint: ',
  573. PICTURE: '<br>Picture: ',
  574. ANSWER: '<br>Answer: ',
  575. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  576. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  577. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  578. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  579. CALC_STAT: 'Calculate statistics',
  580. ELEMENT_TOURNAMENT_REWARD: 'Unclaimed bonus for Elemental Tournament',
  581. BTN_TRY_FIX_IT: 'Fix it',
  582. BTN_TRY_FIX_IT_TITLE: 'Enable auto attack combat correction',
  583. DAMAGE_FIXED: 'Damage fixed from {lastDamage} to {maxDamage}!',
  584. DAMAGE_NO_FIXED: 'Failed to fix damage: {lastDamage}',
  585. LETS_FIX: "Let's fix",
  586. COUNT_FIXED: 'For {count} attempts',
  587. DEFEAT_TURN_TIMER: 'Defeat! Turn on the timer to complete the mission?',
  588. SEASON_REWARD: 'Season Rewards',
  589. SEASON_REWARD_TITLE: 'Collects available free rewards from all current seasons',
  590. SEASON_REWARD_COLLECTED: 'Collected {count} season rewards',
  591. SELL_HERO_SOULS: 'Sell ​​souls',
  592. SELL_HERO_SOULS_TITLE: 'Exchanges all absolute star hero souls for gold',
  593. GOLD_RECEIVED: 'Gold received: {gold}',
  594. OPEN_ALL_EQUIP_BOXES: 'Open all Equipment Fragment Box?',
  595. SERVER_NOT_ACCEPT: 'The server did not accept the result',
  596. INVASION_BOSS_BUFF: 'For {bossLvl} boss need buff {needBuff} you have {haveBuff}}',
  597. },
  598. ru: {
  599. /* Чекбоксы */
  600. SKIP_FIGHTS: 'Пропуск боев',
  601. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  602. ENDLESS_CARDS: 'Бесконечные карты',
  603. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  604. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  605. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  606. CANCEL_FIGHT: 'Отмена боя',
  607. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  608. GIFTS: 'Подарки',
  609. GIFTS_TITLE: 'Собирать подарки автоматически',
  610. BATTLE_RECALCULATION: 'Прерасчет боя',
  611. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  612. BATTLE_FISHING: 'Добивание',
  613. BATTLE_FISHING_TITLE: 'Добивание в чате команды из последнего реплея',
  614. BATTLE_TRENING: 'Тренировка',
  615. BATTLE_TRENING_TITLE: 'Тренировочный бой в чате против команды из последнего реплея',
  616. QUANTITY_CONTROL: 'Контроль кол-ва',
  617. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  618. REPEAT_CAMPAIGN: 'Повтор в компании',
  619. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  620. DISABLE_DONAT: 'Отключить донат',
  621. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  622. DAILY_QUESTS: 'Квесты',
  623. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  624. AUTO_QUIZ: 'АвтоВикторина',
  625. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  626. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  627. HIDE_SERVERS: 'Свернуть сервера',
  628. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  629. /* Поля ввода */
  630. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  631. COMBAT_SPEED: 'Множитель ускорения боя',
  632. HOW_REPEAT_CAMPAIGN: 'Сколько повторов миссий', //тест добавил
  633. NUMBER_OF_TEST: 'Количество тестовых боев',
  634. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  635. USER_ID_TITLE: 'Введите айди игрока',
  636. AMOUNT: 'Количество отправляемых подарков',
  637. GIFT_NUM: 'Номер подарка, 1 - развитие героев, 2 - питомцы, 3 - света, 4 - тьмы, 5 - вознесения, 6 - облик',
  638. /* Кнопки */
  639. RUN_SCRIPT: 'Запустить скрипт',
  640. STOP_SCRIPT: 'Остановить скрипт',
  641. TO_DO_EVERYTHING: 'Сделать все',
  642. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  643. OUTLAND: 'Запределье',
  644. OUTLAND_TITLE: 'Собрать Запределье',
  645. TITAN_ARENA: 'Турнир Стихий',
  646. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  647. DUNGEON: 'Подземелье',
  648. DUNGEON_TITLE: 'Автопрохождение подземелья',
  649. DUNGEON2: 'Подземелье фулл',
  650. DUNGEON_FULL_TITLE: 'Подземелье для фуловых титанов',
  651. STOP_DUNGEON: 'Стоп подземка',
  652. STOP_DUNGEON_TITLE: 'Остановить копание подземелья',
  653. SEER: 'Провидец',
  654. SEER_TITLE: 'Покрутить Провидца',
  655. TOWER: 'Башня',
  656. TOWER_TITLE: 'Автопрохождение башни',
  657. EXPEDITIONS: 'Экспедиции',
  658. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  659. SYNC: 'Синхронизация',
  660. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  661. ARCHDEMON: 'Архидемон',
  662. FURNACE_OF_SOULS: 'Горнило душ',
  663. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  664. ESTER_EGGS: 'Пасхалки',
  665. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  666. REWARDS: 'Награды',
  667. REWARDS_TITLE: 'Собрать все награды за задания',
  668. MAIL: 'Почта',
  669. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  670. MINIONS: 'Прислужники',
  671. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  672. ADVENTURE: 'Приключение',
  673. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  674. STORM: 'Буря',
  675. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  676. SANCTUARY: 'Святилище',
  677. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  678. GUILD_WAR: 'Война гильдий',
  679. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  680. SECRET_WEALTH: 'Тайное богатство',
  681. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  682. /* Разное */
  683. BOTTOM_URLS: '<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>',
  684. GIFTS_SENT: 'Подарки отправлены!',
  685. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  686. BTN_RUN: 'Запускай',
  687. BTN_CANCEL: 'Отмена',
  688. BTN_OK: 'Ок',
  689. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  690. BTN_AUTO: 'Авто',
  691. MSG_YOU_APPLIED: 'Вы нанесли',
  692. MSG_DAMAGE: 'урона',
  693. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  694. MSG_REPEAT_MISSION: 'Повторить миссию?',
  695. BTN_REPEAT: 'Повторить',
  696. BTN_NO: 'Нет',
  697. MSG_SPECIFY_QUANT: 'Указать количество:',
  698. BTN_OPEN: 'Открыть',
  699. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  700. ANSWER_KNOWN: 'Ответ известен',
  701. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  702. BEING_RECALC: 'Идет прерасчет боя',
  703. THIS_TIME: 'На этот раз',
  704. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  705. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  706. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  707. OPEN_DOLLS: 'матрешек рекурсивно',
  708. SENT_QUESTION: 'Вопрос отправлен',
  709. SETTINGS: 'Настройки',
  710. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  711. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  712. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  713. VALUES: 'Значения',
  714. SAVING: 'Сохранка',
  715. USER_ID: 'айди пользователя',
  716. SEND_GIFT: 'Подарок отправлен',
  717. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  718. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  719. TITANIT: 'Титанит',
  720. COMPLETED: 'завершено',
  721. FLOOR: 'Этаж',
  722. LEVEL: 'Уровень',
  723. BATTLES: 'бои',
  724. EVENT: 'Эвент',
  725. NOT_AVAILABLE: 'недоступен',
  726. NO_HEROES: 'Нет героев',
  727. DAMAGE_AMOUNT: 'Количество урона',
  728. NOTHING_TO_COLLECT: 'Нечего собирать',
  729. COLLECTED: 'Собрано',
  730. REWARD: 'наград',
  731. REMAINING_ATTEMPTS: 'Осталось попыток',
  732. BATTLES_CANCELED: 'Битв отменено',
  733. MINION_RAID: 'Рейд прислужников',
  734. STOPPED: 'Остановлено',
  735. REPETITIONS: 'Повторений',
  736. MISSIONS_PASSED: 'Миссий пройдено',
  737. STOP: 'остановить',
  738. TOTAL_OPEN: 'Всего открыто',
  739. OPEN: 'Открыто',
  740. ROUND_STAT: 'Статистика урона за',
  741. BATTLE: 'боев',
  742. MINIMUM: 'Минимальный',
  743. MAXIMUM: 'Максимальный',
  744. AVERAGE: 'Средний',
  745. NOT_THIS_TIME: 'Не в этот раз',
  746. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  747. SUCCESS: 'Успех',
  748. RECEIVED: 'Получено',
  749. LETTERS: 'писем',
  750. PORTALS: 'порталов',
  751. ATTEMPTS: 'попыток',
  752. QUEST_10001: 'Улучши умения героев 3 раза',
  753. QUEST_10002: 'Пройди 10 миссий',
  754. QUEST_10003: 'Пройди 3 героические миссии',
  755. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  756. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  757. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  758. QUEST_10016: 'Отправь подарки согильдийцам',
  759. QUEST_10018: 'Используй зелье опыта',
  760. QUEST_10019: 'Открой 1 сундук в Башне',
  761. QUEST_10020: 'Открой 3 сундука в Запределье',
  762. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  763. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  764. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  765. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  766. QUEST_10025: 'Начни 1 Экспедицию',
  767. QUEST_10026: 'Начни 4 Экспедиции',
  768. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  769. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  770. QUEST_10029: 'Открой сферу артефактов титанов',
  771. QUEST_10030: 'Улучши облик любого героя 1 раз',
  772. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  773. QUEST_10043: 'Начни или присоеденись к Приключению',
  774. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  775. QUEST_10046: 'Открой 3 сундука в Приключениях',
  776. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  777. NOTHING_TO_DO: 'Нечего выполнять',
  778. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  779. BTN_DO_IT: 'Выполняй',
  780. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  781. COMPLETED_QUESTS: 'Выполнено квестов',
  782. /* everything button */
  783. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  784. PASS_THE_TOWER: 'Пройти башню',
  785. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  786. COMPLETE_TOE: 'Пройти Турнир Стихий',
  787. COMPLETE_DUNGEON: 'Пройти подземелье',
  788. COMPLETE_DUNGEON_FULL: 'Пройти подземелье фулл',
  789. COLLECT_MAIL: 'Собрать почту',
  790. COLLECT_MISC: 'Собрать всякую херню',
  791. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  792. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  793. MAKE_A_SYNC: 'Сделать синхронизацию',
  794.  
  795. RUN_FUNCTION: 'Выполнить следующие функции?',
  796. BTN_GO: 'Погнали!',
  797. PERFORMED: 'Выполняется',
  798. DONE: 'Выполнено',
  799. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  800. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  801. BTN_YES: 'Да',
  802. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  803.  
  804. UNKNOWN: 'Неизвестно',
  805. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  806. START_ADVENTURE: 'Начать приключение по этому пути!',
  807. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  808. BTN_CANCELED: 'Отменено',
  809. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  810. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  811. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  812. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  813. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  814. YES_CONTINUE: 'Да, продолжай!',
  815. NOT_ENOUGH_AP: 'Попыток не достаточно',
  816. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  817. MOVES: 'Ходы',
  818. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  819. BATTLE_END_ERROR: 'Ошибка завершения боя',
  820. AUTOBOT: 'АвтоБой',
  821. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  822. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  823. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  824. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  825. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  826. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  827. FIND_COEFF: 'Поиск коэффициента больше чем',
  828. BTN_PASS: 'ПРОПУСК',
  829. BRAWLS: 'Потасовки',
  830. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  831. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  832. LOSSES: 'Поражений',
  833. WINS: 'Побед',
  834. FIGHTS: 'Боев',
  835. STAGE: 'Стадия',
  836. DONT_HAVE_LIVES: 'У Вас нет жизней',
  837. LIVES: 'Жизни',
  838. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  839. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  840. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  841. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  842. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  843. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  844. DAILY_BONUS: 'Ежедневная награда',
  845. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  846. ACTIONS: 'Действия',
  847. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  848. OTHERS: 'Разное',
  849. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  850. CHOOSE_ACTION: 'Выберите действие',
  851. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  852. STAMINA: 'Энергия',
  853. BOXES_OVER: 'Ящики закончились',
  854. NO_BOXES: 'Нет ящиков',
  855. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  856. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  857. GET_ACTIVITY: 'Получить активность',
  858. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  859. ACTIVITY_RECEIVED: 'Получено активности',
  860. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  861. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  862. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  863. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  864. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  865. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  866. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  867. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  868. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  869. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  870. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  871. GET_ENERGY: 'Получить энергию',
  872. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  873. ITEM_EXCHANGE: 'Обмен предметов',
  874. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  875. BUY_SOULS: 'Купить души',
  876. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  877. BUY_OUTLAND: 'Купить Запределье',
  878. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  879. RAID: 'Рейд',
  880. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  881. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  882. CLAN_STAT: 'Клановая статистика',
  883. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  884. BTN_AUTO_F5: 'Авто (F5)',
  885. BOSS_DAMAGE: 'Урон по боссу: ',
  886. NOTHING_BUY: 'Нечего покупать',
  887. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  888. BUY_FOR_GOLD: 'Скупить за золото',
  889. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  890. REWARDS_AND_MAIL: 'Награды и почта',
  891. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  892. New_Year_Clan: 'подарок другу',
  893. New_Year_Clan_TITLE: 'Новогодние подарки друзьям',
  894. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  895. TIMER_ALREADY: 'Таймер уже запущен {time}',
  896. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  897. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  898. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  899. EPIC_BRAWL: 'Вселенская битва',
  900. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  901. RELOAD_GAME: 'Перезагрузить игру',
  902. TIMER: 'Таймер:',
  903. SHOW_ERRORS: 'Отображать ошибки',
  904. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  905. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  906. EVENT_AUTO_BOSS: 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  907. BEST_SLOW: 'Лучший (медленее)',
  908. FIRST_FAST: 'Первый (быстрее)',
  909. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  910. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  911. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  912. BEST_PACK: 'Наилучший пак: ',
  913. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  914. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  915. BOSS_VICTORY_IMPOSSIBLE: 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  916. BOSS_HAS_BEEN_DEF_TEXT: 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток{winTimer}<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  917. MAP: 'Карта: ',
  918. PLAYER_POS: 'Позиции игроков:',
  919. NY_GIFTS: 'Подарки',
  920. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  921. NY_NO_GIFTS: 'Нет не полученных подарков',
  922. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  923. CHANGE_MAP: 'Карта острова',
  924. CHANGE_MAP_TITLE: 'Сменить карту острова',
  925. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  926. MAP_NUM: 'Карта {num}',
  927. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  928. SHOPS: 'Магазины',
  929. SHOPS_DEFAULT: 'Стандартные',
  930. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  931. SHOPS_LIST: 'Магазины {number}',
  932. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  933. SHOPS_WARNING: 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  934. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  935. FAST_SEASON: 'Быстрый сезон',
  936. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  937. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  938. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  939. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  940. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  941. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  942. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  943. SKINS_UPGRADE: 'Улучшение обликов',
  944. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  945. HINT: '<br>Подсказка: ',
  946. PICTURE: '<br>На картинке: ',
  947. ANSWER: '<br>Ответ: ',
  948. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  949. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  950. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  951. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  952. CALC_STAT: 'Посчитать статистику',
  953. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  954. BTN_TRY_FIX_IT: 'Исправить',
  955. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  956. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  957. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  958. LETS_FIX: 'Исправляем',
  959. COUNT_FIXED: 'За {count} попыток',
  960. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  961. SEASON_REWARD: 'Награды сезонов',
  962. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  963. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  964. SELL_HERO_SOULS: 'Продать души',
  965. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  966. GOLD_RECEIVED: 'Получено золота: {gold}',
  967. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  968. SERVER_NOT_ACCEPT: 'Сервер не принял результат',
  969. INVASION_BOSS_BUFF: 'Для {bossLvl} босса нужен баф {needBuff} у вас {haveBuff}',
  970. },
  971. };
  972.  
  973. function getLang() {
  974. let lang = '';
  975. if (typeof NXFlashVars !== 'undefined') {
  976. lang = NXFlashVars.interface_lang
  977. }
  978. if (!lang) {
  979. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  980. }
  981. if (lang == 'ru') {
  982. return lang;
  983. }
  984. return 'en';
  985. }
  986.  
  987. this.I18N = function (constant, replace) {
  988. const selectLang = getLang();
  989. if (constant && constant in i18nLangData[selectLang]) {
  990. const result = i18nLangData[selectLang][constant];
  991. if (replace) {
  992. return result.sprintf(replace);
  993. }
  994. return result;
  995. }
  996. return `% ${constant} %`;
  997. };
  998.  
  999. String.prototype.sprintf = String.prototype.sprintf ||
  1000. function () {
  1001. "use strict";
  1002. var str = this.toString();
  1003. if (arguments.length) {
  1004. var t = typeof arguments[0];
  1005. var key;
  1006. var args = ("string" === t || "number" === t) ?
  1007. Array.prototype.slice.call(arguments)
  1008. : arguments[0];
  1009.  
  1010. for (key in args) {
  1011. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  1012. }
  1013. }
  1014.  
  1015. return str;
  1016. };
  1017.  
  1018. /**
  1019. * Checkboxes
  1020. *
  1021. * Чекбоксы
  1022. */
  1023. const checkboxes = {
  1024. passBattle: {
  1025. label: I18N('SKIP_FIGHTS'),
  1026. cbox: null,
  1027. title: I18N('SKIP_FIGHTS_TITLE'),
  1028. default: false,
  1029. },
  1030. /*sendExpedition: {
  1031. label: I18N('AUTO_EXPEDITION'),
  1032. cbox: null,
  1033. title: I18N('AUTO_EXPEDITION_TITLE'),
  1034. default: false,
  1035. },*/ //тест сдедал экспедиции на авто в сделать все
  1036. cancelBattle: {
  1037. label: I18N('CANCEL_FIGHT'),
  1038. cbox: null,
  1039. title: I18N('CANCEL_FIGHT_TITLE'),
  1040. default: false,
  1041. },
  1042. preCalcBattle: {
  1043. label: I18N('BATTLE_RECALCULATION'),
  1044. cbox: null,
  1045. title: I18N('BATTLE_RECALCULATION_TITLE'),
  1046. default: false,
  1047. },
  1048. finishingBattle: {
  1049. label: I18N('BATTLE_FISHING'),
  1050. cbox: null,
  1051. title: I18N('BATTLE_FISHING_TITLE'),
  1052. default: false,
  1053. },
  1054. treningBattle: {
  1055. label: I18N('BATTLE_TRENING'),
  1056. cbox: null,
  1057. title: I18N('BATTLE_TRENING_TITLE'),
  1058. default: false,
  1059. },
  1060. countControl: {
  1061. label: I18N('QUANTITY_CONTROL'),
  1062. cbox: null,
  1063. title: I18N('QUANTITY_CONTROL_TITLE'),
  1064. default: true,
  1065. },
  1066. repeatMission: {
  1067. label: I18N('REPEAT_CAMPAIGN'),
  1068. cbox: null,
  1069. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1070. default: false,
  1071. },
  1072. noOfferDonat: {
  1073. label: I18N('DISABLE_DONAT'),
  1074. cbox: null,
  1075. title: I18N('DISABLE_DONAT_TITLE'),
  1076. /**
  1077. * A crutch to get the field before getting the character id
  1078. *
  1079. * Костыль чтоб получать поле до получения id персонажа
  1080. */
  1081. default: (() => {
  1082. $result = false;
  1083. try {
  1084. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1085. } catch (e) {
  1086. $result = false;
  1087. }
  1088. return $result || false;
  1089. })(),
  1090. },
  1091. dailyQuests: {
  1092. label: I18N('DAILY_QUESTS'),
  1093. cbox: null,
  1094. title: I18N('DAILY_QUESTS_TITLE'),
  1095. default: false,
  1096. },
  1097. // Потасовки
  1098. /*
  1099. autoBrawls: {
  1100. label: I18N('BRAWLS'),
  1101. cbox: null,
  1102. title: I18N('BRAWLS_TITLE'),
  1103. default: (() => {
  1104. $result = false;
  1105. try {
  1106. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1107. } catch (e) {
  1108. $result = false;
  1109. }
  1110. return $result || false;
  1111. })(),
  1112. hide: false,
  1113. },
  1114. getAnswer: {
  1115. label: I18N('AUTO_QUIZ'),
  1116. cbox: null,
  1117. title: I18N('AUTO_QUIZ_TITLE'),
  1118. default: false,
  1119. hide: true,
  1120. },*/
  1121. tryFixIt_v2: {
  1122. label: I18N('BTN_TRY_FIX_IT'),
  1123. cbox: null,
  1124. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1125. default: false,
  1126. hide: false,
  1127. },
  1128. showErrors: {
  1129. label: I18N('SHOW_ERRORS'),
  1130. cbox: null,
  1131. title: I18N('SHOW_ERRORS_TITLE'),
  1132. default: true,
  1133. },
  1134. buyForGold: {
  1135. label: I18N('BUY_FOR_GOLD'),
  1136. cbox: null,
  1137. title: I18N('BUY_FOR_GOLD_TITLE'),
  1138. default: false,
  1139. },
  1140. hideServers: {
  1141. label: I18N('HIDE_SERVERS'),
  1142. cbox: null,
  1143. title: I18N('HIDE_SERVERS_TITLE'),
  1144. default: false,
  1145. },
  1146. fastSeason: {
  1147. label: I18N('FAST_SEASON'),
  1148. cbox: null,
  1149. title: I18N('FAST_SEASON_TITLE'),
  1150. default: false,
  1151. },
  1152. };
  1153. /**
  1154. * Get checkbox state
  1155. *
  1156. * Получить состояние чекбокса
  1157. */
  1158. function isChecked(checkBox) {
  1159. if (!(checkBox in checkboxes)) {
  1160. return false;
  1161. }
  1162. return checkboxes[checkBox].cbox?.checked;
  1163. }
  1164. /**
  1165. * Input fields
  1166. *
  1167. * Поля ввода
  1168. */
  1169. const inputs = {
  1170. countTitanit: {
  1171. input: null,
  1172. title: I18N('HOW_MUCH_TITANITE'),
  1173. default: 150,
  1174. },
  1175. speedBattle: {
  1176. input: null,
  1177. title: I18N('COMBAT_SPEED'),
  1178. default: 5,
  1179. },
  1180. //тест повтор компании
  1181. countRaid: {
  1182. input: null,
  1183. title: I18N('HOW_REPEAT_CAMPAIGN'),
  1184. default: 5,
  1185. },
  1186. countTestBattle: {
  1187. input: null,
  1188. title: I18N('NUMBER_OF_TEST'),
  1189. default: 10,
  1190. },
  1191. countAutoBattle: {
  1192. input: null,
  1193. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1194. default: 10,
  1195. },
  1196. /*FPS: {
  1197. input: null,
  1198. title: 'FPS',
  1199. default: 60,
  1200. }*/
  1201. }
  1202. //сохранка тест
  1203. const inputs2 = {
  1204. countBattle: {
  1205. input: null,
  1206. title: '-1 сохраняет защиту, -2 атаку противника с Replay',
  1207. default: 1,
  1208. },
  1209. needResource: {
  1210. input: null,
  1211. title: 'Мощь противника мин.(тыс.)/урона(млн.)',
  1212. default: 300,
  1213. },
  1214. needResource2: {
  1215. input: null,
  1216. title: 'Мощь противника макс./тип бафа',
  1217. default: 1500,
  1218. },
  1219. }
  1220. //новогодние подарки игрокам других гильдий
  1221. const inputs3 = {
  1222. userID: { // айди игрока посмотреть открыв его инфо
  1223. input: null,
  1224. title: I18N('USER_ID_TITLE'),
  1225. default: 111111,
  1226. },
  1227. GiftNum: { // номер подарка считаем слева направо от 1 до 6, под 1 это за 750 новогодних игрушек
  1228. input: null,
  1229. title: I18N('GIFT_NUM'),
  1230. default: 10,
  1231. },
  1232. AmontID: { // количество ресурсов от 1 до бесконечности
  1233. input: null,
  1234. title: I18N('AMOUNT'),
  1235. default: 1,
  1236. },
  1237. }
  1238. /**
  1239. * Checks the checkbox
  1240. *
  1241. * Поплучить данные поля ввода
  1242. */
  1243. /*function getInput(inputName) {
  1244. return inputs[inputName]?.input?.value;
  1245. }*/
  1246. function getInput(inputName) {
  1247. if (inputName in inputs){return inputs[inputName]?.input?.value;}
  1248. else if (inputName in inputs2){return inputs2[inputName]?.input?.value;}
  1249. //else if (inputName in inputs3){return inputs3[inputName]?.input?.value;}
  1250. else return null
  1251. }
  1252.  
  1253. //тест рейд
  1254. /** Автоповтор миссии */
  1255. let isRepeatMission = false;
  1256. /** Вкл/Выкл автоповтор миссии */
  1257. this.switchRepeatMission = function() {
  1258. isRepeatMission = !isRepeatMission;
  1259. console.log(isRepeatMission);
  1260. }
  1261.  
  1262. /**
  1263. * Control FPS
  1264. *
  1265. * Контроль FPS
  1266. */
  1267. let nextAnimationFrame = Date.now();
  1268. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1269. this.requestAnimationFrame = async function (e) {
  1270. const FPS = Number(getInput('FPS')) || -1;
  1271. const now = Date.now();
  1272. const delay = nextAnimationFrame - now;
  1273. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1274. if (delay > 0) {
  1275. await new Promise((e) => setTimeout(e, delay));
  1276. }
  1277. oldRequestAnimationFrame(e);
  1278. };
  1279.  
  1280. /**
  1281. * Button List
  1282. *
  1283. * Список кнопочек
  1284. */
  1285. const buttons = {
  1286. getOutland: {
  1287. name: I18N('TO_DO_EVERYTHING'),
  1288. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1289. func: testDoYourBest,
  1290. },
  1291. /*
  1292. doActions: {
  1293. name: I18N('ACTIONS'),
  1294. title: I18N('ACTIONS_TITLE'),
  1295. func: async function () {
  1296. const popupButtons = [
  1297. {
  1298. msg: I18N('OUTLAND'),
  1299. result: function () {
  1300. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1301. },
  1302. title: I18N('OUTLAND_TITLE'),
  1303. },
  1304. {
  1305. msg: I18N('TOWER'),
  1306. result: function () {
  1307. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1308. },
  1309. title: I18N('TOWER_TITLE'),
  1310. },
  1311. {
  1312. msg: I18N('EXPEDITIONS'),
  1313. result: function () {
  1314. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1315. },
  1316. title: I18N('EXPEDITIONS_TITLE'),
  1317. },
  1318. {
  1319. msg: I18N('MINIONS'),
  1320. result: function () {
  1321. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1322. },
  1323. title: I18N('MINIONS_TITLE'),
  1324. },
  1325. {
  1326. msg: I18N('ESTER_EGGS'),
  1327. result: function () {
  1328. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1329. },
  1330. title: I18N('ESTER_EGGS_TITLE'),
  1331. },
  1332. {
  1333. msg: I18N('STORM'),
  1334. result: function () {
  1335. testAdventure('solo');
  1336. },
  1337. title: I18N('STORM_TITLE'),
  1338. },
  1339. {
  1340. msg: I18N('REWARDS'),
  1341. result: function () {
  1342. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1343. },
  1344. title: I18N('REWARDS_TITLE'),
  1345. },
  1346. {
  1347. msg: I18N('MAIL'),
  1348. result: function () {
  1349. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1350. },
  1351. title: I18N('MAIL_TITLE'),
  1352. },
  1353. {
  1354. msg: I18N('SEER'),
  1355. result: function () {
  1356. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1357. },
  1358. title: I18N('SEER_TITLE'),
  1359. },
  1360. {
  1361. msg: I18N('NY_GIFTS'),
  1362. result: getGiftNewYear,
  1363. title: I18N('NY_GIFTS_TITLE'),
  1364. },
  1365. ];
  1366. popupButtons.push({ result: false, isClose: true });
  1367. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1368. if (typeof answer === 'function') {
  1369. answer();
  1370. },
  1371. }
  1372. },*/
  1373. doOthers: {
  1374. name: I18N('OTHERS'),
  1375. title: I18N('OTHERS_TITLE'),
  1376. func: async function () {
  1377. const popupButtons = [
  1378. /*
  1379. {
  1380. msg: I18N('GET_ENERGY'),
  1381. result: farmStamina,
  1382. title: I18N('GET_ENERGY_TITLE'),
  1383. },
  1384. {
  1385. msg: I18N('ITEM_EXCHANGE'),
  1386. result: fillActive,
  1387. title: I18N('ITEM_EXCHANGE_TITLE'),
  1388. },
  1389. {
  1390. msg: I18N('BUY_SOULS'),
  1391. result: function () {
  1392. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1393. },
  1394. title: I18N('BUY_SOULS_TITLE'),
  1395. },
  1396. {
  1397. msg: I18N('BUY_FOR_GOLD'),
  1398. result: function () {
  1399. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1400. },
  1401. title: I18N('BUY_FOR_GOLD_TITLE'),
  1402. },
  1403. {
  1404. msg: I18N('BUY_OUTLAND'),
  1405. result: bossOpenChestPay,
  1406. title: I18N('BUY_OUTLAND_TITLE'),
  1407. },
  1408. {
  1409. msg: I18N('AUTO_RAID_ADVENTURE'),
  1410. result: autoRaidAdventure,
  1411. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1412. },
  1413. {
  1414. msg: I18N('CLAN_STAT'),
  1415. result: clanStatistic,
  1416. title: I18N('CLAN_STAT_TITLE'),
  1417. },
  1418. {
  1419. msg: I18N('EPIC_BRAWL'),
  1420. result: async function () {
  1421. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1422. const brawl = new epicBrawl();
  1423. brawl.start();
  1424. });
  1425. },
  1426. title: I18N('EPIC_BRAWL_TITLE'),
  1427. },*/
  1428. {
  1429. msg: I18N('ARTIFACTS_UPGRADE'),
  1430. result: updateArtifacts,
  1431. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1432. },
  1433. {
  1434. msg: I18N('SKINS_UPGRADE'),
  1435. result: updateSkins,
  1436. title: I18N('SKINS_UPGRADE_TITLE'),
  1437. },
  1438. {
  1439. msg: I18N('SEASON_REWARD'),
  1440. result: farmBattlePass,
  1441. title: I18N('SEASON_REWARD_TITLE'),
  1442. },
  1443. {
  1444. msg: I18N('SELL_HERO_SOULS'),
  1445. result: sellHeroSoulsForGold,
  1446. title: I18N('SELL_HERO_SOULS_TITLE'),
  1447. },
  1448. {
  1449. msg: I18N('CHANGE_MAP'),
  1450. result: async function () {
  1451. const maps = Object.values(lib.data.seasonAdventure.list)
  1452. .filter((e) => e.map.cells.length > 2)
  1453. .map((i) => ({
  1454. msg: I18N('MAP_NUM', { num: i.id }),
  1455. result: i.id,
  1456. }));
  1457.  
  1458. /*const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1459. ...maps,
  1460. { result: false, isClose: true },
  1461. ]);*/
  1462. //тест карта острова
  1463. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1464. if (result) {
  1465. cheats.changeIslandMap(result);
  1466. }
  1467. },
  1468. title: I18N('CHANGE_MAP_TITLE'),
  1469. },
  1470. {
  1471. msg: I18N('SHOPS'),
  1472. result: async function () {
  1473. const shopButtons = [{
  1474. msg: I18N('SHOPS_DEFAULT'),
  1475. result: function () {
  1476. cheats.goDefaultShops();
  1477. },
  1478. title: I18N('SHOPS_DEFAULT_TITLE'),
  1479. }, {
  1480. msg: I18N('SECRET_WEALTH'),
  1481. result: function () {
  1482. cheats.goSecretWealthShops();
  1483. },
  1484. title: I18N('SECRET_WEALTH'),
  1485. }];
  1486. for (let i = 0; i < 4; i++) {
  1487. const number = i + 1;
  1488. shopButtons.push({
  1489. msg: I18N('SHOPS_LIST', { number }),
  1490. result: function () {
  1491. cheats.goCustomShops(i);
  1492. },
  1493. title: I18N('SHOPS_LIST_TITLE', { number }),
  1494. })
  1495. }
  1496. shopButtons.push({ result: false, isClose: true })
  1497. const answer = await popup.confirm(I18N('SHOPS_WARNING'), shopButtons);
  1498. if (typeof answer === 'function') {
  1499. answer();
  1500. }
  1501. },
  1502. title: I18N('SHOPS'),
  1503. },
  1504. ];
  1505.  
  1506. popupButtons.push({ result: false, isClose: true });
  1507. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1508. if (typeof answer === 'function') {
  1509. answer();
  1510. }
  1511. },
  1512. },
  1513. testTitanArena: {
  1514. name: I18N('TITAN_ARENA'),
  1515. title: I18N('TITAN_ARENA_TITLE'),
  1516. func: function () {
  1517. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1518. },
  1519. },
  1520. /* тест подземка есть в сделать все
  1521. testDungeon: {
  1522. name: I18N('DUNGEON'),
  1523. title: I18N('DUNGEON_TITLE'),
  1524. func: function () {
  1525. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1526. },
  1527. hide: true,
  1528. },*/
  1529. //тест подземка 2
  1530. DungeonFull: {
  1531. name: I18N('DUNGEON2'),
  1532. title: I18N('DUNGEON_FULL_TITLE'),
  1533. func: function () {
  1534. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON_FULL_TITLE')}?`, DungeonFull);
  1535. },
  1536. },
  1537. //остановить подземелье
  1538. stopDungeon: {
  1539. name: I18N('STOP_DUNGEON'),
  1540. title: I18N('STOP_DUNGEON_TITLE'),
  1541. func: function () {
  1542. confShow(`${I18N('STOP_SCRIPT')} ${I18N('STOP_DUNGEON_TITLE')}?`, stopDungeon);
  1543. },
  1544. },
  1545. // Архидемон
  1546. bossRatingEvent: {
  1547. name: I18N('ARCHDEMON'),
  1548. title: I18N('ARCHDEMON_TITLE'),
  1549. func: function () {
  1550. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1551. },
  1552. hide: true,
  1553. },
  1554. // Горнило душ
  1555. bossRatingEvent: {
  1556. name: I18N('FURNACE_OF_SOULS'),
  1557. title: I18N('ARCHDEMON_TITLE'),
  1558. func: function () {
  1559. confShow(`${I18N('RUN_SCRIPT')} ${I18N('FURNACE_OF_SOULS')}?`, bossRatingEventSouls);
  1560. },
  1561. hide: true,
  1562. },
  1563. // Буря
  1564. /*testAdventure2: {
  1565. name: I18N('STORM'),
  1566. title: I18N('STORM_TITLE'),
  1567. func: () => {
  1568. testAdventure2('solo');
  1569. },
  1570. },*/
  1571. rewardsAndMailFarm: {
  1572. name: I18N('REWARDS_AND_MAIL'),
  1573. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1574. func: function () {
  1575. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1576. },
  1577. },
  1578. //тест прислужники
  1579. testRaidNodes: {
  1580. name: I18N('MINIONS'),
  1581. title: I18N('MINIONS_TITLE'),
  1582. func: function () {
  1583. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1584. },
  1585. },
  1586. testAdventure: {
  1587. name: I18N('ADVENTURE'),
  1588. title: I18N('ADVENTURE_TITLE'),
  1589. func: () => {
  1590. testAdventure();
  1591. },
  1592. },
  1593. goToSanctuary: {
  1594. name: I18N('SANCTUARY'),
  1595. title: I18N('SANCTUARY_TITLE'),
  1596. func: cheats.goSanctuary,
  1597. },
  1598. goToClanWar: {
  1599. name: I18N('GUILD_WAR'),
  1600. title: I18N('GUILD_WAR_TITLE'),
  1601. func: cheats.goClanWar,
  1602. },
  1603. dailyQuests: {
  1604. name: I18N('DAILY_QUESTS'),
  1605. title: I18N('DAILY_QUESTS_TITLE'),
  1606. func: async function () {
  1607. const quests = new dailyQuests(
  1608. () => {},
  1609. () => {}
  1610. );
  1611. await quests.autoInit();
  1612. quests.start();
  1613. },
  1614. },
  1615. //подарок др
  1616. /*NewYearGift_Clan: {
  1617. name: I18N('New_Year_Clan'),
  1618. title: I18N('New_Year_Clan_TITLE'),
  1619. func: function () {
  1620. confShow(`${I18N('RUN_SCRIPT')} ${I18N('New_Year_Clan_TITLE')}?`, NewYearGift_Clan);
  1621. },
  1622. },*/
  1623. newDay: {
  1624. name: I18N('SYNC'),
  1625. title: I18N('SYNC_TITLE'),
  1626. func: function () {
  1627. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1628. },
  1629. },
  1630. };
  1631. /**
  1632. * Display buttons
  1633. *
  1634. * Вывести кнопочки
  1635. */
  1636. function addControlButtons() {
  1637. for (let name in buttons) {
  1638. button = buttons[name];
  1639. if (button.hide) {
  1640. continue;
  1641. }
  1642. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1643. }
  1644. }
  1645. /**
  1646. * Adds links
  1647. *
  1648. * Добавляет ссылки
  1649. */
  1650. function addBottomUrls() {
  1651. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1652. }
  1653. /**
  1654. * Stop repetition of the mission
  1655. *
  1656. * Остановить повтор миссии
  1657. */
  1658. let isStopSendMission = false;
  1659. /**
  1660. * There is a repetition of the mission
  1661. *
  1662. * Идет повтор миссии
  1663. */
  1664. let isSendsMission = false;
  1665. /**
  1666. * Data on the past mission
  1667. *
  1668. * Данные о прошедшей мисии
  1669. */
  1670. let lastMissionStart = {}
  1671. /**
  1672. * Start time of the last battle in the company
  1673. *
  1674. * Время начала последнего боя в кампании
  1675. */
  1676. let lastMissionBattleStart = 0;
  1677. /**
  1678. * Data for calculating the last battle with the boss
  1679. *
  1680. * Данные для расчете последнего боя с боссом
  1681. */
  1682. let lastBossBattle = null;
  1683. /**
  1684. * Information about the last battle
  1685. *
  1686. * Данные о прошедшей битве
  1687. */
  1688. let lastBattleArg = {}
  1689. let lastBossBattleStart = null;
  1690. this.addBattleTimer = 4;
  1691. this.invasionTimer = 2500;
  1692. const invasionInfo = {
  1693. buff: 0,
  1694. bossLvl: 130,
  1695. };
  1696. const invasionDataPacks = {
  1697. 130: { buff: 0, pet: 6004, heroes: [58, 48, 16, 65, 59], favor: { 16: 6004, 48: 6001, 58: 6002, 59: 6005, 65: 6000 } },
  1698. 140: { buff: 0, pet: 6006, heroes: [1, 4, 13, 58, 65], favor: { 1: 6001, 4: 6006, 13: 6002, 58: 6005, 65: 6000 } },
  1699. 150: { buff: 0, pet: 6006, heroes: [1, 12, 17, 21, 65], favor: { 1: 6001, 12: 6003, 17: 6006, 21: 6002, 65: 6000 } },
  1700. 160: { buff: 0, pet: 6008, heroes: [12, 21, 34, 58, 65], favor: { 12: 6003, 21: 6006, 34: 6008, 58: 6002, 65: 6001 } },
  1701. 170: { buff: 0, pet: 6005, heroes: [33, 12, 65, 21, 4], favor: { 4: 6001, 12: 6003, 21: 6006, 33: 6008, 65: 6000 } },
  1702. 180: { buff: 20, pet: 6009, heroes: [58, 13, 5, 17, 65], favor: { 5: 6006, 13: 6003, 58: 6005 } },
  1703. 190: { buff: 0, pet: 6006, heroes: [1, 12, 21, 36, 65], favor: { 1: 6004, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1704. 200: { buff: 0, pet: 6006, heroes: [12, 1, 13, 2, 65], favor: { 2: 6001, 12: 6003, 13: 6006, 65: 6000 } },
  1705. 210: { buff: 15, pet: 6005, heroes: [12, 21, 33, 58, 65], favor: { 12: 6003, 21: 6006, 33: 6008, 58: 6005, 65: 6001 } },
  1706. 220: { buff: 5, pet: 6006, heroes: [58, 13, 7, 34, 65], favor: { 7: 6002, 13: 6008, 34: 6006, 58: 6005, 65: 6001 } },
  1707. 230: { buff: 35, pet: 6005, heroes: [5, 7, 13, 58, 65], favor: { 5: 6006, 7: 6003, 13: 6002, 58: 6005, 65: 6000 } },
  1708. 240: { buff: 0, pet: 6005, heroes: [12, 58, 1, 36, 65], favor: { 1: 6006, 12: 6003, 36: 6005, 65: 6001 } },
  1709. 250: { buff: 15, pet: 6005, heroes: [12, 36, 4, 16, 65], favor: { 12: 6003, 16: 6004, 36: 6005, 65: 6001 } },
  1710. 260: { buff: 15, pet: 6005, heroes: [48, 12, 36, 65, 4], favor: { 4: 6006, 12: 6003, 36: 6005, 48: 6000, 65: 6007 } },
  1711. 270: { buff: 35, pet: 6005, heroes: [12, 58, 36, 4, 65], favor: { 4: 6006, 12: 6003, 36: 6005 } },
  1712. 280: { buff: 80, pet: 6005, heroes: [21, 36, 48, 7, 65], favor: { 7: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6000 } },
  1713. 290: { buff: 95, pet: 6008, heroes: [12, 21, 36, 35, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 65: 6007 } },
  1714. 300: { buff: 25, pet: 6005, heroes: [12, 13, 4, 34, 65], favor: { 4: 6006, 12: 6003, 13: 6007, 34: 6002 } },
  1715. 310: { buff: 45, pet: 6005, heroes: [12, 21, 58, 33, 65], favor: { 12: 6003, 21: 6006, 33: 6002, 58: 6005, 65: 6007 } },
  1716. 320: { buff: 70, pet: 6005, heroes: [12, 48, 2, 6, 65], favor: { 6: 6005, 12: 6003 } },
  1717. 330: { buff: 70, pet: 6005, heroes: [12, 21, 36, 5, 65], favor: { 5: 6002, 12: 6003, 21: 6006, 36: 6005, 65: 6000 } },
  1718. 340: { buff: 55, pet: 6009, heroes: [12, 36, 13, 6, 65], favor: { 6: 6005, 12: 6003, 13: 6002, 36: 6006, 65: 6000 } },
  1719. 350: { buff: 100, pet: 6005, heroes: [12, 21, 58, 34, 65], favor: { 12: 6003, 21: 6006, 58: 6005 } },
  1720. 360: { buff: 85, pet: 6007, heroes: [12, 21, 36, 4, 65], favor: { 4: 6006, 12: 6003, 21: 6002, 36: 6005 } },
  1721. 370: { buff: 90, pet: 6008, heroes: [12, 21, 36, 13, 65], favor: { 12: 6003, 13: 6007, 21: 6006, 36: 6005, 65: 6001 } },
  1722. 380: { buff: 165, pet: 6005, heroes: [12, 33, 36, 4, 65], favor: { 4: 6001, 12: 6003, 33: 6006 } },
  1723. 390: { buff: 235, pet: 6005, heroes: [21, 58, 48, 2, 65], favor: { 2: 6005, 21: 6002 } },
  1724. 400: { buff: 125, pet: 6006, heroes: [12, 21, 36, 48, 65], favor: { 12: 6003, 21: 6006, 36: 6005, 48: 6001, 65: 6007 } },
  1725. };
  1726. /**
  1727. * The name of the function of the beginning of the battle
  1728. *
  1729. * Имя функции начала боя
  1730. */
  1731. let nameFuncStartBattle = '';
  1732. /**
  1733. * The name of the function of the end of the battle
  1734. *
  1735. * Имя функции конца боя
  1736. */
  1737. let nameFuncEndBattle = '';
  1738. /**
  1739. * Data for calculating the last battle
  1740. *
  1741. * Данные для расчета последнего боя
  1742. */
  1743. let lastBattleInfo = null;
  1744. /**
  1745. * The ability to cancel the battle
  1746. *
  1747. * Возможность отменить бой
  1748. */
  1749. let isCancalBattle = true;
  1750.  
  1751. /**
  1752. * Certificator of the last open nesting doll
  1753. *
  1754. * Идетификатор последней открытой матрешки
  1755. */
  1756. let lastRussianDollId = null;
  1757. /**
  1758. * Cancel the training guide
  1759. *
  1760. * Отменить обучающее руководство
  1761. */
  1762. this.isCanceledTutorial = false;
  1763.  
  1764. /**
  1765. * Data from the last question of the quiz
  1766. *
  1767. * Данные последнего вопроса викторины
  1768. */
  1769. let lastQuestion = null;
  1770. /**
  1771. * Answer to the last question of the quiz
  1772. *
  1773. * Ответ на последний вопрос викторины
  1774. */
  1775. let lastAnswer = null;
  1776. /**
  1777. * Flag for opening keys or titan artifact spheres
  1778. *
  1779. * Флаг открытия ключей или сфер артефактов титанов
  1780. */
  1781. let artifactChestOpen = false;
  1782. /**
  1783. * The name of the function to open keys or orbs of titan artifacts
  1784. *
  1785. * Имя функции открытия ключей или сфер артефактов титанов
  1786. */
  1787. let artifactChestOpenCallName = '';
  1788. let correctShowOpenArtifact = 0;
  1789. /**
  1790. * Data for the last battle in the dungeon
  1791. * (Fix endless cards)
  1792. *
  1793. * Данные для последнего боя в подземке
  1794. * (Исправление бесконечных карт)
  1795. */
  1796. let lastDungeonBattleData = null;
  1797. /**
  1798. * Start time of the last battle in the dungeon
  1799. *
  1800. * Время начала последнего боя в подземелье
  1801. */
  1802. let lastDungeonBattleStart = 0;
  1803. /**
  1804. * Subscription end time
  1805. *
  1806. * Время окончания подписки
  1807. */
  1808. let subEndTime = 0;
  1809. /**
  1810. * Number of prediction cards
  1811. *
  1812. * Количество карт предсказаний
  1813. */
  1814. let countPredictionCard = 0;
  1815.  
  1816. /**
  1817. * Brawl pack
  1818. *
  1819. * Пачка для потасовок
  1820. */
  1821. let brawlsPack = null;
  1822. /**
  1823. * Autobrawl started
  1824. *
  1825. * Автопотасовка запущена
  1826. */
  1827. let isBrawlsAutoStart = false;
  1828. let clanDominationGetInfo = null;
  1829. /**
  1830. * Copies the text to the clipboard
  1831. *
  1832. * Копирует тест в буфер обмена
  1833. * @param {*} text copied text // копируемый текст
  1834. */
  1835. function copyText(text) {
  1836. let copyTextarea = document.createElement("textarea");
  1837. copyTextarea.style.opacity = "0";
  1838. copyTextarea.textContent = text;
  1839. document.body.appendChild(copyTextarea);
  1840. copyTextarea.select();
  1841. document.execCommand("copy");
  1842. document.body.removeChild(copyTextarea);
  1843. delete copyTextarea;
  1844. }
  1845. /**
  1846. * Returns the history of requests
  1847. *
  1848. * Возвращает историю запросов
  1849. */
  1850. this.getRequestHistory = function() {
  1851. return requestHistory;
  1852. }
  1853. /**
  1854. * Generates a random integer from min to max
  1855. *
  1856. * Гененирует случайное целое число от min до max
  1857. */
  1858. const random = function (min, max) {
  1859. return Math.floor(Math.random() * (max - min + 1) + min);
  1860. }
  1861. const randf = function (min, max) {
  1862. return Math.random() * (max - min + 1) + min;
  1863. };
  1864. /**
  1865. * Clearing the request history
  1866. *
  1867. * Очистка истоии запросов
  1868. */
  1869. setInterval(function () {
  1870. let now = Date.now();
  1871. for (let i in requestHistory) {
  1872. const time = +i.split('_')[0];
  1873. if (now - time > 300000) {
  1874. delete requestHistory[i];
  1875. }
  1876. }
  1877. }, 300000);
  1878. /**
  1879. * Displays the dialog box
  1880. *
  1881. * Отображает диалоговое окно
  1882. */
  1883. function confShow(message, yesCallback, noCallback) {
  1884. let buts = [];
  1885. message = message || I18N('DO_YOU_WANT');
  1886. noCallback = noCallback || (() => {});
  1887. if (yesCallback) {
  1888. buts = [
  1889. { msg: I18N('BTN_RUN'), result: true},
  1890. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1891. ]
  1892. } else {
  1893. yesCallback = () => {};
  1894. buts = [
  1895. { msg: I18N('BTN_OK'), result: true},
  1896. ];
  1897. }
  1898. popup.confirm(message, buts).then((e) => {
  1899. // dialogPromice = null;
  1900. if (e) {
  1901. yesCallback();
  1902. } else {
  1903. noCallback();
  1904. }
  1905. });
  1906. }
  1907. /**
  1908. * Override/proxy the method for creating a WS package send
  1909. *
  1910. * Переопределяем/проксируем метод создания отправки WS пакета
  1911. */
  1912. WebSocket.prototype.send = function (data) {
  1913. if (!this.isSetOnMessage) {
  1914. const oldOnmessage = this.onmessage;
  1915. this.onmessage = function (event) {
  1916. try {
  1917. const data = JSON.parse(event.data);
  1918. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1919. this.isWebSocketLogin = true;
  1920. } else if (data.result.type == "iframeEvent.login") {
  1921. return;
  1922. }
  1923. } catch (e) { }
  1924. return oldOnmessage.apply(this, arguments);
  1925. }
  1926. this.isSetOnMessage = true;
  1927. }
  1928. original.SendWebSocket.call(this, data);
  1929. }
  1930. /**
  1931. * Overriding/Proxying the Ajax Request Creation Method
  1932. *
  1933. * Переопределяем/проксируем метод создания Ajax запроса
  1934. */
  1935. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1936. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1937. this.errorRequest = false;
  1938. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1939. if (!apiUrl) {
  1940. apiUrl = url;
  1941. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1942. console.log(socialInfo);
  1943. }
  1944. requestHistory[this.uniqid] = {
  1945. method,
  1946. url,
  1947. error: [],
  1948. headers: {},
  1949. request: null,
  1950. response: null,
  1951. signature: [],
  1952. calls: {},
  1953. };
  1954. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1955. this.errorRequest = true;
  1956. }
  1957. return original.open.call(this, method, url, async, user, password);
  1958. };
  1959. /**
  1960. * Overriding/Proxying the header setting method for the AJAX request
  1961. *
  1962. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1963. */
  1964. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1965. if (this.uniqid in requestHistory) {
  1966. requestHistory[this.uniqid].headers[name] = value;
  1967. } else {
  1968. check = true;
  1969. }
  1970.  
  1971. if (name == 'X-Auth-Signature') {
  1972. requestHistory[this.uniqid].signature.push(value);
  1973. if (!check) {
  1974. return;
  1975. }
  1976. }
  1977.  
  1978. return original.setRequestHeader.call(this, name, value);
  1979. };
  1980. /**
  1981. * Overriding/Proxying the AJAX Request Sending Method
  1982. *
  1983. * Переопределяем/проксируем метод отправки AJAX запроса
  1984. */
  1985. XMLHttpRequest.prototype.send = async function (sourceData) {
  1986. if (this.uniqid in requestHistory) {
  1987. let tempData = null;
  1988. if (getClass(sourceData) == "ArrayBuffer") {
  1989. tempData = decoder.decode(sourceData);
  1990. } else {
  1991. tempData = sourceData;
  1992. }
  1993. requestHistory[this.uniqid].request = tempData;
  1994. let headers = requestHistory[this.uniqid].headers;
  1995. lastHeaders = Object.assign({}, headers);
  1996. /**
  1997. * Game loading event
  1998. *
  1999. * Событие загрузки игры
  2000. */
  2001. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  2002. isLoadGame = true;
  2003. if (cheats.libGame) {
  2004. lib.setData(cheats.libGame);
  2005. } else {
  2006. lib.setData(await cheats.LibLoad());
  2007. }
  2008. addControls();
  2009. addControlButtons();
  2010. addBottomUrls();
  2011.  
  2012. //if (isChecked('sendExpedition')) {
  2013. // checkExpedition(); //экспедиции на авто при входе в игру
  2014. //}
  2015. //if (isChecked('sendExpedition')) {
  2016. const isTimeBetweenDays = isTimeBetweenNewDays();
  2017. if (!isTimeBetweenDays) {
  2018. checkExpedition(); //экспедиции на авто при входе в игру
  2019. } else {
  2020. setProgress(I18N('EXPEDITIONS_NOTTIME'), true);
  2021. }
  2022. //}
  2023. getAutoGifts(); // автосбор подарков
  2024.  
  2025. cheats.activateHacks();
  2026.  
  2027. justInfo();
  2028. if (isChecked('dailyQuests')) {
  2029. testDailyQuests();
  2030. }
  2031.  
  2032. if (isChecked('buyForGold')) {
  2033. buyInStoreForGold();
  2034. }
  2035. }
  2036. /**
  2037. * Outgoing request data processing
  2038. *
  2039. * Обработка данных исходящего запроса
  2040. */
  2041. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  2042. /**
  2043. * Handling incoming request data
  2044. *
  2045. * Обработка данных входящего запроса
  2046. */
  2047. const oldReady = this.onreadystatechange;
  2048. this.onreadystatechange = async function (e) {
  2049. if (this.errorRequest) {
  2050. return oldReady.apply(this, arguments);
  2051. }
  2052. if(this.readyState == 4 && this.status == 200) {
  2053. isTextResponse = this.responseType === "text" || this.responseType === "";
  2054. let response = isTextResponse ? this.responseText : this.response;
  2055. requestHistory[this.uniqid].response = response;
  2056. /**
  2057. * Replacing incoming request data
  2058. *
  2059. * Заменна данных входящего запроса
  2060. */
  2061. if (isTextResponse) {
  2062. await checkChangeResponse.call(this, response);
  2063. }
  2064. /**
  2065. * A function to run after the request is executed
  2066. *
  2067. * Функция запускаемая после выполения запроса
  2068. */
  2069. if (typeof this.onReadySuccess == 'function') {
  2070. setTimeout(this.onReadySuccess, 500);
  2071. }
  2072. /** Удаляем из истории запросов битвы с боссом */
  2073. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  2074. }
  2075. if (oldReady) {
  2076. return oldReady.apply(this, arguments);
  2077. }
  2078. }
  2079. }
  2080. if (this.errorRequest) {
  2081. const oldReady = this.onreadystatechange;
  2082. this.onreadystatechange = function () {
  2083. Object.defineProperty(this, 'status', {
  2084. writable: true
  2085. });
  2086. this.status = 200;
  2087. Object.defineProperty(this, 'readyState', {
  2088. writable: true
  2089. });
  2090. this.readyState = 4;
  2091. Object.defineProperty(this, 'responseText', {
  2092. writable: true
  2093. });
  2094. this.responseText = JSON.stringify({
  2095. "result": true
  2096. });
  2097. if (typeof this.onReadySuccess == 'function') {
  2098. setTimeout(this.onReadySuccess, 200);
  2099. }
  2100. return oldReady.apply(this, arguments);
  2101. }
  2102. this.onreadystatechange();
  2103. } else {
  2104. try {
  2105. return original.send.call(this, sourceData);
  2106. } catch(e) {
  2107. debugger;
  2108. }
  2109.  
  2110. }
  2111. };
  2112. /**
  2113. * Processing and substitution of outgoing data
  2114. *
  2115. * Обработка и подмена исходящих данных
  2116. */
  2117. async function checkChangeSend(sourceData, tempData) {
  2118. try {
  2119. /**
  2120. * A function that replaces battle data with incorrect ones to cancel combatя
  2121. *
  2122. * Функция заменяющая данные боя на неверные для отмены боя
  2123. */
  2124. const fixBattle = function (heroes) {
  2125. for (const ids in heroes) {
  2126. hero = heroes[ids];
  2127. hero.energy = random(1, 999);
  2128. if (hero.hp > 0) {
  2129. hero.hp = random(1, hero.hp);
  2130. }
  2131. }
  2132. }
  2133. /**
  2134. * Dialog window 2
  2135. *
  2136. * Диалоговое окно 2
  2137. */
  2138. const showMsg = async function (msg, ansF, ansS) {
  2139. if (typeof popup == 'object') {
  2140. return await popup.confirm(msg, [
  2141. {msg: ansF, result: false},
  2142. {msg: ansS, result: true},
  2143. ]);
  2144. } else {
  2145. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2146. }
  2147. }
  2148. /**
  2149. * Dialog window 3
  2150. *
  2151. * Диалоговое окно 3
  2152. */
  2153. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2154. return await popup.confirm(msg, [
  2155. {msg: ansF, result: 0},
  2156. {msg: ansS, result: 1},
  2157. {msg: ansT, result: 2},
  2158. ]);
  2159. }
  2160.  
  2161. let changeRequest = false;
  2162. testData = JSON.parse(tempData);
  2163. for (const call of testData.calls) {
  2164. if (!artifactChestOpen) {
  2165. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2166. }
  2167. /**
  2168. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2169. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2170. */
  2171. if ((call.name == 'adventure_endBattle' ||
  2172. call.name == 'adventureSolo_endBattle' ||
  2173. call.name == 'clanWarEndBattle' &&
  2174. isChecked('cancelBattle') ||
  2175. call.name == 'crossClanWar_endBattle' &&
  2176. isChecked('cancelBattle') ||
  2177. call.name == 'brawl_endBattle' ||
  2178. call.name == 'towerEndBattle' ||
  2179. call.name == 'invasion_bossEnd' ||
  2180. call.name == 'titanArenaEndBattle' ||
  2181. call.name == 'bossEndBattle' ||
  2182. call.name == 'clanRaid_endNodeBattle') &&
  2183. isCancalBattle) {
  2184. nameFuncEndBattle = call.name;
  2185. if (isChecked('tryFixIt_v2') &&
  2186. !call.args.result.win &&
  2187. (call.name == 'brawl_endBattle' ||
  2188. //call.name == 'crossClanWar_endBattle' ||
  2189. call.name == 'epicBrawl_endBattle' ||
  2190. //call.name == 'clanWarEndBattle' ||
  2191. call.name == 'adventure_endBattle' ||
  2192. call.name == 'titanArenaEndBattle' ||
  2193. call.name == 'bossEndBattle' ||
  2194. call.name == 'adventureSolo_endBattle') &&
  2195. lastBattleInfo) {
  2196. const noFixWin = call.name == 'clanWarEndBattle' || call.name == 'crossClanWar_endBattle';
  2197. const cloneBattle = structuredClone(lastBattleInfo);
  2198. lastBattleInfo = null;
  2199. try {
  2200. const bFix = new BestOrWinFixBattle(cloneBattle);
  2201. bFix.setNoMakeWin(noFixWin);
  2202. let endTime = Date.now() + 3e4;
  2203. if (endTime < cloneBattle.endTime) {
  2204. endTime = cloneBattle.endTime;
  2205. }
  2206. const result = await bFix.start(cloneBattle.endTime, 150);
  2207. if (result.result.win) {
  2208. call.args.result = result.result;
  2209. call.args.progress = result.progress;
  2210. changeRequest = true;
  2211. } else if (result.value) {
  2212. if (
  2213. await popup.confirm('Поражение<br>Лучший результат: ' + result.value + '%', [
  2214. { msg: 'Отмена', result: 0 },
  2215. { msg: 'Принять', result: 1 },
  2216. ])
  2217. ) {
  2218. call.args.result = result.result;
  2219. call.args.progress = result.progress;
  2220. changeRequest = true;
  2221. }
  2222. }
  2223. } catch (error) {
  2224. console.error(error);
  2225. }
  2226. }
  2227. if (!call.args.result.win) {
  2228. let resultPopup = false;
  2229. if (call.name == 'adventure_endBattle' ||
  2230. //call.name == 'invasion_bossEnd' ||
  2231. call.name == 'bossEndBattle' ||
  2232. call.name == 'adventureSolo_endBattle') {
  2233. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2234. } else if (call.name == 'clanWarEndBattle' ||
  2235. call.name == 'crossClanWar_endBattle') {
  2236. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2237. } else if (call.name !== 'epicBrawl_endBattle' && call.name !== 'titanArenaEndBattle') {
  2238. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2239. }
  2240. if (resultPopup) {
  2241. if (call.name == 'invasion_bossEnd') {
  2242. this.errorRequest = true;
  2243. }
  2244. fixBattle(call.args.progress[0].attackers.heroes);
  2245. fixBattle(call.args.progress[0].defenders.heroes);
  2246. changeRequest = true;
  2247. if (resultPopup > 1) {
  2248. this.onReadySuccess = testAutoBattle;
  2249. // setTimeout(bossBattle, 1000);
  2250. }
  2251. }
  2252. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2253. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2254. if (resultPopup) {
  2255. fixBattle(call.args.progress[0].attackers.heroes);
  2256. fixBattle(call.args.progress[0].defenders.heroes);
  2257. changeRequest = true;
  2258. if (resultPopup > 1) {
  2259. this.onReadySuccess = testAutoBattle;
  2260. }
  2261. }
  2262. }
  2263. // Потасовки
  2264. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2265. }
  2266. /**
  2267. * Save pack for Brawls
  2268. *
  2269. * Сохраняем пачку для потасовок
  2270. */
  2271. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2272. console.log(JSON.stringify(call.args));
  2273. brawlsPack = call.args;
  2274. if (
  2275. await popup.confirm(
  2276. I18N('START_AUTO_BRAWLS'),
  2277. [
  2278. { msg: I18N('BTN_NO'), result: false },
  2279. { msg: I18N('BTN_YES'), result: true },
  2280. ],
  2281. [
  2282. {
  2283. name: 'isAuto',
  2284. label: I18N('BRAWL_AUTO_PACK'),
  2285. checked: false,
  2286. },
  2287. ]
  2288. )
  2289. ) {
  2290. isBrawlsAutoStart = true;
  2291. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2292. this.errorRequest = true;
  2293. testBrawls(isAuto.checked);
  2294. }
  2295. }
  2296. /**
  2297. * Canceled fight in Asgard
  2298. * Отмена боя в Асгарде
  2299. */
  2300. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2301. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2302. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2303. const lastDamage = maxDamage;
  2304. const testFunc = [];
  2305. if (testFuntions.masterFix) {
  2306. testFunc.push({ msg: 'masterFix', isInput: true, default: 100 });
  2307. }
  2308. const resultPopup = await popup.confirm(
  2309. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2310. [
  2311. { msg: I18N('BTN_OK'), result: false },
  2312. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2313. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2314. ...testFunc,
  2315. ],
  2316. [
  2317. {
  2318. name: 'isStat',
  2319. label: I18N('CALC_STAT'),
  2320. checked: false,
  2321. },
  2322. ]
  2323. );
  2324. if (resultPopup) {
  2325. if (resultPopup == 2) {
  2326. setProgress(I18N('LETS_FIX'), false);
  2327. await new Promise((e) => setTimeout(e, 0));
  2328. const cloneBattle = structuredClone(lastBossBattle);
  2329. const endTime = cloneBattle.endTime - 1e4;
  2330. console.log('fixBossBattleStart');
  2331. const bFix = new BossFixBattle(cloneBattle);
  2332. const result = await bFix.start(endTime, 300);
  2333. console.log(result);
  2334. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2335. lastDamage: lastDamage.toLocaleString()
  2336. });
  2337. if (result.value > lastDamage) {
  2338. call.args.result = result.result;
  2339. call.args.progress = result.progress;
  2340. msgResult = I18N('DAMAGE_FIXED', {
  2341. lastDamage: lastDamage.toLocaleString(),
  2342. maxDamage: result.value.toLocaleString(),
  2343. });
  2344. }
  2345. console.log(lastDamage, '>', result.value);
  2346. setProgress(
  2347. msgResult +
  2348. '<br/>' +
  2349. I18N('COUNT_FIXED', {
  2350. count: result.maxCount,
  2351. }),
  2352. false,
  2353. hideProgress
  2354. );
  2355. } else if (resultPopup > 3) {
  2356. const cloneBattle = structuredClone(lastBossBattle);
  2357. const mFix = new masterFixBattle(cloneBattle);
  2358. const result = await mFix.start(cloneBattle.endTime, resultPopup);
  2359. console.log(result);
  2360. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2361. lastDamage: lastDamage.toLocaleString(),
  2362. });
  2363. if (result.value > lastDamage) {
  2364. maxDamage = result.value;
  2365. call.args.result = result.result;
  2366. call.args.progress = result.progress;
  2367. msgResult = I18N('DAMAGE_FIXED', {
  2368. lastDamage: lastDamage.toLocaleString(),
  2369. maxDamage: maxDamage.toLocaleString(),
  2370. });
  2371. }
  2372. console.log('Урон:', lastDamage, maxDamage);
  2373. setProgress(msgResult, false, hideProgress);
  2374. } else {
  2375. fixBattle(call.args.progress[0].attackers.heroes);
  2376. fixBattle(call.args.progress[0].defenders.heroes);
  2377. }
  2378. changeRequest = true;
  2379. }
  2380. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2381. if (isStat.checked) {
  2382. this.onReadySuccess = testBossBattle;
  2383. }
  2384. }
  2385. /**
  2386. * Save the Asgard Boss Attack Pack
  2387. * Сохраняем пачку для атаки босса Асгарда
  2388. */
  2389. if (call.name == 'clanRaid_startBossBattle') {
  2390. console.log(JSON.stringify(call.args));
  2391. }
  2392. /**
  2393. * Saving the request to start the last battle
  2394. * Сохранение запроса начала последнего боя
  2395. */
  2396. if (
  2397. call.name == 'clanWarAttack' ||
  2398. call.name == 'crossClanWar_startBattle' ||
  2399. call.name == 'adventure_turnStartBattle' ||
  2400. call.name == 'adventureSolo_turnStartBattle' ||
  2401. call.name == 'bossAttack' ||
  2402. call.name == 'invasion_bossStart' ||
  2403. call.name == 'towerStartBattle'
  2404. ) {
  2405. nameFuncStartBattle = call.name;
  2406. lastBattleArg = call.args;
  2407.  
  2408. if (call.name == 'invasion_bossStart') {
  2409. const timePassed = Date.now() - lastBossBattleStart;
  2410. if (timePassed < invasionTimer) {
  2411. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2412. }
  2413. invasionTimer -= 1;
  2414. }
  2415. lastBossBattleStart = Date.now();
  2416. }
  2417. if (call.name == 'invasion_bossEnd') {
  2418. const lastBattle = lastBattleInfo;
  2419. if (lastBattle && call.args.result.win) {
  2420. lastBattle.progress = call.args.progress;
  2421. const result = await Calc(lastBattle);
  2422. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2423. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2424. console.log(timer, period);
  2425. if (period < timer) {
  2426. timer = timer - period;
  2427. await countdownTimer(timer);
  2428. }
  2429. }
  2430. }
  2431. /**
  2432. * Disable spending divination cards
  2433. * Отключить трату карт предсказаний
  2434. */
  2435. if (call.name == 'dungeonEndBattle') {
  2436. if (call.args.isRaid) {
  2437. if (countPredictionCard <= 0) {
  2438. delete call.args.isRaid;
  2439. changeRequest = true;
  2440. } else if (countPredictionCard > 0) {
  2441. countPredictionCard--;
  2442. }
  2443. }
  2444. console.log(`Cards: ${countPredictionCard}`);
  2445. /**
  2446. * Fix endless cards
  2447. * Исправление бесконечных карт
  2448. */
  2449. const lastBattle = lastDungeonBattleData;
  2450. if (lastBattle && !call.args.isRaid) {
  2451. if (changeRequest) {
  2452. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2453. } else {
  2454. lastBattle.progress = call.args.progress;
  2455. }
  2456. const result = await Calc(lastBattle);
  2457.  
  2458. if (changeRequest) {
  2459. call.args.progress = result.progress;
  2460. call.args.result = result.result;
  2461. }
  2462.  
  2463. let timer = result.battleTimer + addBattleTimer;
  2464. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2465. console.log(timer, period);
  2466. if (period < timer) {
  2467. timer = timer - period;
  2468. await countdownTimer(timer);
  2469. }
  2470. }
  2471. }
  2472. /**
  2473. * Quiz Answer
  2474. * Ответ на викторину
  2475. */
  2476. if (call.name == 'quizAnswer') {
  2477. /**
  2478. * Automatically changes the answer to the correct one if there is one.
  2479. * Автоматически меняет ответ на правильный если он есть
  2480. */
  2481. if (lastAnswer && isChecked('getAnswer')) {
  2482. call.args.answerId = lastAnswer;
  2483. lastAnswer = null;
  2484. changeRequest = true;
  2485. }
  2486. }
  2487. /**
  2488. * Present
  2489. * Подарки
  2490. */
  2491. if (call.name == 'freebieCheck') {
  2492. freebieCheckInfo = call;
  2493. }
  2494. /** missionTimer */
  2495. if (call.name == 'missionEnd' && missionBattle) {
  2496. let startTimer = false;
  2497. if (!call.args.result.win) {
  2498. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2499. { msg: I18N('BTN_NO'), result: false },
  2500. { msg: I18N('BTN_YES'), result: true },
  2501. ]);
  2502. }
  2503. if (call.args.result.win || startTimer) {
  2504. missionBattle.progress = call.args.progress;
  2505. missionBattle.result = call.args.result;
  2506. const result = await Calc(missionBattle);
  2507. let timer = result.battleTimer + addBattleTimer;
  2508. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2509. if (period < timer) {
  2510. timer = timer - period;
  2511. await countdownTimer(timer);
  2512. }
  2513. missionBattle = null;
  2514. } else {
  2515. this.errorRequest = true;
  2516. }
  2517. }
  2518. /**
  2519. * Getting mission data for auto-repeat
  2520. * Получение данных миссии для автоповтора
  2521. */
  2522. if (isChecked('repeatMission') &&
  2523. call.name == 'missionEnd') {
  2524. let missionInfo = {
  2525. id: call.args.id,
  2526. result: call.args.result,
  2527. heroes: call.args.progress[0].attackers.heroes,
  2528. count: 0,
  2529. }
  2530. setTimeout(async () => {
  2531. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2532. { msg: I18N('BTN_REPEAT'), result: true},
  2533. { msg: I18N('BTN_NO'), result: false},
  2534. ])) {
  2535. isStopSendMission = false;
  2536. isSendsMission = true;
  2537. sendsMission(missionInfo);
  2538. }
  2539. }, 0);
  2540. }
  2541. /**
  2542. * Getting mission data
  2543. * Получение данных миссии
  2544. * missionTimer
  2545. */
  2546. if (call.name == 'missionStart') {
  2547. lastMissionStart = call.args;
  2548. lastMissionBattleStart = Date.now();
  2549. }
  2550.  
  2551. /**
  2552. * Specify the quantity for Titan Orbs and Pet Eggs
  2553. * Указать количество для сфер титанов и яиц петов
  2554. */
  2555. if (isChecked('countControl') &&
  2556. (call.name == 'pet_chestOpen' ||
  2557. call.name == 'titanUseSummonCircle') &&
  2558. call.args.amount > 1) {
  2559. const startAmount = call.args.amount;
  2560. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2561. { msg: I18N('BTN_OPEN'), isInput: true, default: 1},
  2562. ]);
  2563. if (result) {
  2564. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2565. cheats.updateInventory({
  2566. [item.type]: {
  2567. [item.id]: -(result - startAmount),
  2568. },
  2569. });
  2570. call.args.amount = result;
  2571. changeRequest = true;
  2572. }
  2573. }
  2574. /**
  2575. * Specify the amount for keys and spheres of titan artifacts
  2576. * Указать колличество для ключей и сфер артефактов титанов
  2577. */
  2578. if (isChecked('countControl') &&
  2579. (call.name == 'artifactChestOpen' ||
  2580. call.name == 'titanArtifactChestOpen') &&
  2581. call.args.amount > 1 &&
  2582. call.args.free &&
  2583. !changeRequest) {
  2584. artifactChestOpenCallName = call.name;
  2585. const startAmount = call.args.amount;
  2586. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2587. { msg: I18N('BTN_OPEN'), isInput: true, default: 1 },
  2588. ]);
  2589. if (result) {
  2590. const openChests = result;
  2591. let sphere = result < 10 ? 1 : 10;
  2592.  
  2593. call.args.amount = sphere;
  2594. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2595. if (count < 10) sphere = 1;
  2596. const ident = artifactChestOpenCallName + "_" + count;
  2597. testData.calls.push({
  2598. name: artifactChestOpenCallName,
  2599. args: {
  2600. amount: sphere,
  2601. free: true,
  2602. },
  2603. ident: ident
  2604. });
  2605. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2606. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2607. }
  2608. requestHistory[this.uniqid].calls[call.name].push(ident);
  2609. }
  2610. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2611. cheats.updateInventory({
  2612. consumable: {
  2613. [consumableId]: -(openChests - startAmount),
  2614. },
  2615. });
  2616.  
  2617. artifactChestOpen = true;
  2618. changeRequest = true;
  2619. }
  2620. }
  2621. if (call.name == 'consumableUseLootBox') {
  2622. lastRussianDollId = call.args.libId;
  2623. /**
  2624. * Specify quantity for gold caskets
  2625. * Указать количество для золотых шкатулок
  2626. */
  2627. if (isChecked('countControl') &&
  2628. call.args.libId == 148 &&
  2629. call.args.amount > 1) {
  2630. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2631. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2632. ]);
  2633. call.args.amount = result;
  2634. changeRequest = true;
  2635. }
  2636. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2637. this.massOpen = call.args.libId;
  2638. }
  2639. }
  2640. if (call.name == 'invasion_bossStart' && isChecked('tryFixIt_v2') && call.args.id == 217) {
  2641. const pack = invasionDataPacks[invasionInfo.bossLvl];
  2642. if (pack.buff != invasionInfo.buff) {
  2643. setProgress(
  2644. I18N('INVASION_BOSS_BUFF', {
  2645. bossLvl: invasionInfo.bossLvl,
  2646. needBuff: pack.buff,
  2647. haveBuff: invasionInfo.buff,
  2648. }),
  2649. false
  2650. );
  2651. } else {
  2652. call.args.pet = pack.pet;
  2653. call.args.heroes = pack.heroes;
  2654. call.args.favor = pack.favor;
  2655. changeRequest = true;
  2656. }
  2657. }
  2658. /**
  2659. * Changing the maximum number of raids in the campaign
  2660. * Изменение максимального количества рейдов в кампании
  2661. */
  2662. // if (call.name == 'missionRaid') {
  2663. // if (isChecked('countControl') && call.args.times > 1) {
  2664. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2665. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2666. // ]));
  2667. // call.args.times = result > call.args.times ? call.args.times : result;
  2668. // changeRequest = true;
  2669. // }
  2670. // }
  2671. }
  2672.  
  2673. let headers = requestHistory[this.uniqid].headers;
  2674. if (changeRequest) {
  2675. sourceData = JSON.stringify(testData);
  2676. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2677. }
  2678.  
  2679. let signature = headers['X-Auth-Signature'];
  2680. if (signature) {
  2681. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2682. }
  2683. } catch (err) {
  2684. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2685. }
  2686. return sourceData;
  2687. }
  2688. /**
  2689. * Processing and substitution of incoming data
  2690. *
  2691. * Обработка и подмена входящих данных
  2692. */
  2693. async function checkChangeResponse(response) {
  2694. try {
  2695. isChange = false;
  2696. let nowTime = Math.round(Date.now() / 1000);
  2697. callsIdent = requestHistory[this.uniqid].calls;
  2698. respond = JSON.parse(response);
  2699. /**
  2700. * If the request returned an error removes the error (removes synchronization errors)
  2701. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2702. */
  2703. if (respond.error) {
  2704. isChange = true;
  2705. console.error(respond.error);
  2706. if (isChecked('showErrors')) {
  2707. popup.confirm(I18N('ERROR_MSG', {
  2708. name: respond.error.name,
  2709. description: respond.error.description,
  2710. }));
  2711. }
  2712. if (respond.error.name != 'AccountBan') {
  2713. delete respond.error;
  2714. respond.results = [];
  2715. }
  2716. }
  2717. let mainReward = null;
  2718. const allReward = {};
  2719. let countTypeReward = 0;
  2720. let readQuestInfo = false;
  2721. for (const call of respond.results) {
  2722. /**
  2723. * Obtaining initial data for completing quests
  2724. * Получение исходных данных для выполнения квестов
  2725. */
  2726. if (readQuestInfo) {
  2727. questsInfo[call.ident] = call.result.response;
  2728. }
  2729. /**
  2730. * Getting a user ID
  2731. * Получение идетификатора пользователя
  2732. */
  2733. if (call.ident == callsIdent['registration']) {
  2734. userId = call.result.response.userId;
  2735. if (localStorage['userId'] != userId) {
  2736. localStorage['newGiftSendIds'] = '';
  2737. localStorage['userId'] = userId;
  2738. }
  2739. await openOrMigrateDatabase(userId);
  2740. readQuestInfo = true;
  2741. }
  2742. /**
  2743. * Hiding donation offers 1
  2744. * Скрываем предложения доната 1
  2745. */
  2746. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2747. const billings = call.result.response?.billings;
  2748. const bundle = call.result.response?.bundle;
  2749. if (billings && bundle) {
  2750. call.result.response.billings = call.result.response.billings.filter((e) => ['repeatableOffer'].includes(e.type));
  2751. call.result.response.bundle = [];
  2752. isChange = true;
  2753. }
  2754. }
  2755. /**
  2756. * Hiding donation offers 2
  2757. * Скрываем предложения доната 2
  2758. */
  2759. if (getSaveVal('noOfferDonat') &&
  2760. (call.ident == callsIdent['offerGetAll'] ||
  2761. call.ident == callsIdent['specialOffer_getAll'])) {
  2762. let offers = call.result.response;
  2763. if (offers) {
  2764. call.result.response = offers.filter(
  2765. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2766. );
  2767. isChange = true;
  2768. }
  2769. }
  2770. /**
  2771. * Hiding donation offers 3
  2772. * Скрываем предложения доната 3
  2773. */
  2774. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2775. delete call.result.bundleUpdate;
  2776. isChange = true;
  2777. }
  2778. /**
  2779. * Hiding donation offers 4
  2780. * Скрываем предложения доната 4
  2781. */
  2782. if (call.result?.specialOffers) {
  2783. const offers = call.result.specialOffers;
  2784. call.result.specialOffers = offers.filter(
  2785. (e) => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource', 'stagesOffer'].includes(e.offerType)
  2786. );
  2787. isChange = true;
  2788. }
  2789. /**
  2790. * Copies a quiz question to the clipboard
  2791. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2792. */
  2793. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2794. let quest = call.result.response;
  2795. console.log(quest.question);
  2796. copyText(quest.question);
  2797. setProgress(I18N('QUESTION_COPY'), true);
  2798. quest.lang = null;
  2799. if (typeof NXFlashVars !== 'undefined') {
  2800. quest.lang = NXFlashVars.interface_lang;
  2801. }
  2802. lastQuestion = quest;
  2803. if (isChecked('getAnswer')) {
  2804. const answer = await getAnswer(lastQuestion);
  2805. let showText = '';
  2806. if (answer) {
  2807. lastAnswer = answer;
  2808. console.log(answer);
  2809. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2810. } else {
  2811. showText = I18N('ANSWER_NOT_KNOWN');
  2812. }
  2813.  
  2814. try {
  2815. const hint = hintQuest(quest);
  2816. if (hint) {
  2817. showText += I18N('HINT') + hint;
  2818. }
  2819. } catch(e) {}
  2820.  
  2821. setProgress(showText, true);
  2822. }
  2823. }
  2824. /**
  2825. * Submits a question with an answer to the database
  2826. * Отправляет вопрос с ответом в базу данных
  2827. */
  2828. if (call.ident == callsIdent['quizAnswer']) {
  2829. const answer = call.result.response;
  2830. if (lastQuestion) {
  2831. const answerInfo = {
  2832. answer,
  2833. question: lastQuestion,
  2834. lang: null,
  2835. }
  2836. if (typeof NXFlashVars !== 'undefined') {
  2837. answerInfo.lang = NXFlashVars.interface_lang;
  2838. }
  2839. lastQuestion = null;
  2840. setTimeout(sendAnswerInfo, 0, answerInfo);
  2841. }
  2842. }
  2843. /**
  2844. * Get user data
  2845. * Получить даныне пользователя
  2846. */
  2847. if (call.ident == callsIdent['userGetInfo']) {
  2848. let user = call.result.response;
  2849. document.title = user.name;
  2850. userInfo = Object.assign({}, user);
  2851. delete userInfo.refillable;
  2852. if (!questsInfo['userGetInfo']) {
  2853. questsInfo['userGetInfo'] = user;
  2854. }
  2855. }
  2856. /**
  2857. * Start of the battle for recalculation
  2858. * Начало боя для прерасчета
  2859. */
  2860. if (call.ident == callsIdent['clanWarAttack'] ||
  2861. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2862. call.ident == callsIdent['bossAttack'] ||
  2863. call.ident == callsIdent['battleGetReplay'] ||
  2864. call.ident == callsIdent['brawl_startBattle'] ||
  2865. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2866. call.ident == callsIdent['invasion_bossStart'] ||
  2867. call.ident == callsIdent['titanArenaStartBattle'] ||
  2868. call.ident == callsIdent['towerStartBattle'] ||
  2869. call.ident == callsIdent['adventure_turnStartBattle']) {
  2870. let battle = call.result.response.battle || call.result.response.replay;
  2871. if (call.ident == callsIdent['brawl_startBattle'] ||
  2872. call.ident == callsIdent['bossAttack'] ||
  2873. call.ident == callsIdent['towerStartBattle'] ||
  2874. call.ident == callsIdent['invasion_bossStart']) {
  2875. battle = call.result.response;
  2876. }
  2877. lastBattleInfo = battle;
  2878. if (call.ident == callsIdent['battleGetReplay'] && call.result.response.replay.type === "clan_raid") {
  2879. if (call?.result?.response?.replay?.result?.damage) {
  2880. const damages = Object.values(call.result.response.replay.result.damage);
  2881. const bossDamage = damages.reduce((a, v) => a + v, 0);
  2882. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2883. continue;
  2884. }
  2885. }
  2886. if (!isChecked('preCalcBattle')) {
  2887. continue;
  2888. }
  2889. setProgress(I18N('BEING_RECALC'));
  2890. let battleDuration = 120;
  2891. try {
  2892. const typeBattle = getBattleType(battle.type);
  2893. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2894. } catch (e) { }
  2895. //console.log(battle.type);
  2896. function getBattleInfo(battle, isRandSeed) {
  2897. return new Promise(function (resolve) {
  2898. if (isRandSeed) {
  2899. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2900. }
  2901. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2902. });
  2903. }
  2904. let actions = [getBattleInfo(battle, false)]
  2905. let countTestBattle = getInput('countTestBattle');
  2906. if (call.ident == callsIdent['invasion_bossStart'] ) {
  2907. countTestBattle = 0;
  2908. }
  2909. if (call.ident == callsIdent['battleGetReplay']) {
  2910. battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, 0] } }];
  2911. }
  2912. for (let i = 0; i < countTestBattle; i++) {
  2913. actions.push(getBattleInfo(battle, true));
  2914. }
  2915. Promise.all(actions)
  2916. .then(e => {
  2917. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2918. let firstBattle = e.shift();
  2919. const timer = Math.floor(battleDuration - firstBattle.time);
  2920. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2921. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2922. let msg = `${I18N('THIS_TIME')} ${firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT')}`;
  2923. if (e.length) {
  2924. const countWin = e.reduce((w, s) => w + s.win, 0);
  2925. msg += ` ${I18N('CHANCE_TO_WIN')}: ${Math.floor((countWin / e.length) * 100)}% (${e.length})`;
  2926. }
  2927. msg += `, ${min}:${sec}`
  2928. setProgress(msg, false, hideProgress)
  2929. });
  2930. }
  2931. //тест сохранки
  2932. /** Запоминаем команды в реплее*/
  2933. if (call.ident == callsIdent['battleGetReplay']) {
  2934. let battle = call.result.response.replay;
  2935. repleyBattle.attackers = battle.attackers;
  2936. repleyBattle.defenders = battle.defenders[0];
  2937. repleyBattle.effects = battle.effects.defenders;
  2938. repleyBattle.state = battle.progress[0].defenders.heroes;
  2939. repleyBattle.seed = battle.seed;
  2940. }
  2941. /** Нападение в турнире*/
  2942. if (call.ident == callsIdent['titanArenaStartBattle']) {
  2943. let bestBattle = getInput('countBattle');
  2944. let unrandom = getInput('needResource');
  2945. let maxPower = getInput('needResource2');
  2946. if (bestBattle * unrandom * maxPower == 0) {
  2947. let battle = call.result.response.battle;
  2948. if (bestBattle == 0) {
  2949. battle.progress = bestLordBattle[battle.typeId]?.progress;
  2950. }
  2951. if (unrandom == 0 && !!repleyBattle.seed) {
  2952. battle.seed = repleyBattle.seed;
  2953. }
  2954. if (maxPower == 0) {
  2955. battle.attackers = getTitansPack(Object.keys(battle.attackers));
  2956. }
  2957. isChange = true;
  2958. }
  2959. }
  2960. /** Тест боев с усилениями команд защиты*/
  2961. if (call.ident == callsIdent['chatAcceptChallenge']) {
  2962. let battle = call.result.response.battle;
  2963. addBuff(battle);
  2964. let testType = getInput('countBattle');
  2965. if (testType.slice(0, 1) == "-") {
  2966. testType = parseInt(testType.slice(1), 10);
  2967. switch (testType) {
  2968. case 1:
  2969. battle.defenders[0] = repleyBattle.defenders;
  2970. break; //наша атака против защиты из реплея
  2971. case 2:
  2972. battle.defenders[0] = repleyBattle.attackers;
  2973. break; //наша атака против атаки из реплея
  2974. case 3:
  2975. battle.attackers = repleyBattle.attackers;
  2976. break; //атака из реплея против защиты в чате
  2977. case 4:
  2978. battle.attackers = repleyBattle.defenders;
  2979. break; //защита из реплея против защиты в чате
  2980. case 5:
  2981. battle.attackers = repleyBattle.attackers;
  2982. battle.defenders[0] = repleyBattle.defenders;
  2983. break; //атака из реплея против защиты из реплея
  2984. case 6:
  2985. battle.attackers = repleyBattle.defenders;
  2986. battle.defenders[0] = repleyBattle.attackers;
  2987. break; //защита из реплея против атаки из реплея
  2988. case 7:
  2989. battle.attackers = repleyBattle.attackers;
  2990. battle.defenders[0] = repleyBattle.attackers;
  2991. break; //атака из реплея против атаки из реплея
  2992. case 8:
  2993. battle.attackers = repleyBattle.defenders;
  2994. battle.defenders[0] = repleyBattle.defenders;
  2995. break; //защита из реплея против защиты из реплея
  2996. case 15:
  2997. battle.attackers = repleyBattle.defenders;
  2998. battle.defenders[0] = repleyBattle.defenders;
  2999. break; //защита из реплея против защиты из реплея
  3000. }
  3001. }
  3002.  
  3003. isChange = true;
  3004. }
  3005. /** Тест боев с усилениями команд защиты тренировках*/
  3006. if (call.ident == callsIdent['demoBattles_startBattle']) {
  3007. let battle = call.result.response.battle;
  3008. addBuff(battle);
  3009. let testType = getInput('countBattle');
  3010. if (testType.slice(0, 1) == "-") {
  3011. testType = parseInt(testType.slice(1), 10);
  3012. switch (testType) {
  3013. case 1:
  3014. battle.defenders[0] = repleyBattle.defenders;
  3015. break; //наша атака против защиты из реплея
  3016. case 2:
  3017. battle.defenders[0] = repleyBattle.attackers;
  3018. break; //наша атака против атаки из реплея
  3019. case 3:
  3020. battle.attackers = repleyBattle.attackers;
  3021. break; //атака из реплея против защиты в чате
  3022. case 4:
  3023. battle.attackers = repleyBattle.defenders;
  3024. break; //защита из реплея против защиты в чате
  3025. case 5:
  3026. battle.attackers = repleyBattle.attackers;
  3027. battle.defenders[0] = repleyBattle.defenders;
  3028. break; //атака из реплея против защиты из реплея
  3029. case 6:
  3030. battle.attackers = repleyBattle.defenders;
  3031. battle.defenders[0] = repleyBattle.attackers;
  3032. break; //защита из реплея против атаки из реплея
  3033. case 7:
  3034. battle.attackers = repleyBattle.attackers;
  3035. battle.defenders[0] = repleyBattle.attackers;
  3036. break; //атака из реплея против атаки из реплея
  3037. case 8:
  3038. battle.attackers = repleyBattle.defenders;
  3039. battle.defenders[0] = repleyBattle.defenders;
  3040. break; //защита из реплея против защиты из реплея
  3041. }
  3042. }
  3043.  
  3044. isChange = true;
  3045. }
  3046. //тест сохранки
  3047. /**
  3048. * Start of the Asgard boss fight
  3049. * Начало боя с боссом Асгарда
  3050. */
  3051. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  3052. lastBossBattle = call.result.response.battle;
  3053. lastBossBattle.endTime = Date.now() + 160 * 1000;
  3054. if (isChecked('preCalcBattle')) {
  3055. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  3056. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  3057. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  3058. }
  3059. }
  3060. /**
  3061. * Cancel tutorial
  3062. * Отмена туториала
  3063. */
  3064. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  3065. let chains = call.result.response.chains;
  3066. for (let n in chains) {
  3067. chains[n] = 9999;
  3068. }
  3069. isChange = true;
  3070. }
  3071. /**
  3072. * Opening keys and spheres of titan artifacts
  3073. * Открытие ключей и сфер артефактов титанов
  3074. */
  3075. if (artifactChestOpen &&
  3076. (call.ident == callsIdent[artifactChestOpenCallName] ||
  3077. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  3078. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  3079.  
  3080. reward.forEach(e => {
  3081. for (let f in e) {
  3082. if (!allReward[f]) {
  3083. allReward[f] = {};
  3084. }
  3085. for (let o in e[f]) {
  3086. if (!allReward[f][o]) {
  3087. allReward[f][o] = e[f][o];
  3088. countTypeReward++;
  3089. } else {
  3090. allReward[f][o] += e[f][o];
  3091. }
  3092. }
  3093. }
  3094. });
  3095.  
  3096. if (!call.ident.includes(artifactChestOpenCallName)) {
  3097. mainReward = call.result.response;
  3098. }
  3099. }
  3100.  
  3101. if (countTypeReward > 20) {
  3102. correctShowOpenArtifact = 3;
  3103. } else {
  3104. correctShowOpenArtifact = 0;
  3105. }
  3106.  
  3107. /**
  3108. * Sum the result of opening Pet Eggs
  3109. * Суммирование результата открытия яиц питомцев
  3110. */
  3111. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  3112. const rewards = call.result.response.rewards;
  3113. if (rewards.length > 10) {
  3114. /**
  3115. * Removing pet cards
  3116. * Убираем карточки петов
  3117. */
  3118. for (const reward of rewards) {
  3119. if (reward.petCard) {
  3120. delete reward.petCard;
  3121. }
  3122. }
  3123. }
  3124. rewards.forEach(e => {
  3125. for (let f in e) {
  3126. if (!allReward[f]) {
  3127. allReward[f] = {};
  3128. }
  3129. for (let o in e[f]) {
  3130. if (!allReward[f][o]) {
  3131. allReward[f][o] = e[f][o];
  3132. } else {
  3133. allReward[f][o] += e[f][o];
  3134. }
  3135. }
  3136. }
  3137. });
  3138. call.result.response.rewards = [allReward];
  3139. isChange = true;
  3140. }
  3141. /**
  3142. * Removing titan cards
  3143. * Убираем карточки титанов
  3144. */
  3145. if (call.ident == callsIdent['titanUseSummonCircle']) {
  3146. if (call.result.response.rewards.length > 10) {
  3147. for (const reward of call.result.response.rewards) {
  3148. if (reward.titanCard) {
  3149. delete reward.titanCard;
  3150. }
  3151. }
  3152. isChange = true;
  3153. }
  3154. }
  3155. /**
  3156. * Auto-repeat opening matryoshkas
  3157. * АвтоПовтор открытия матрешек
  3158. */
  3159. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  3160. let [countLootBox, lootBox] = Object.entries(call.result.response).pop();
  3161. countLootBox = +countLootBox;
  3162. let newCount = 0;
  3163. if (lootBox?.consumable && lootBox.consumable[lastRussianDollId]) {
  3164. newCount += lootBox.consumable[lastRussianDollId];
  3165. delete lootBox.consumable[lastRussianDollId];
  3166. }
  3167. if (
  3168. newCount && (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  3169. { msg: I18N('BTN_OPEN'), result: true },
  3170. { msg: I18N('BTN_NO'), result: false, isClose: true },
  3171. ]))
  3172. ) {
  3173. const [count, recursionResult] = await openRussianDolls(lastRussianDollId, newCount);
  3174. countLootBox += +count;
  3175. mergeItemsObj(lootBox, recursionResult);
  3176. isChange = true;
  3177. }
  3178.  
  3179. if (this.massOpen) {
  3180. if (
  3181. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  3182. { msg: I18N('BTN_OPEN'), result: true },
  3183. { msg: I18N('BTN_NO'), result: false, isClose: true },
  3184. ])
  3185. ) {
  3186. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  3187. Object.entries(e.results[0].result.response.consumable)
  3188. );
  3189. const calls = [];
  3190. const deleteItems = {};
  3191. for (const [libId, amount] of consumable) {
  3192. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  3193. calls.push({
  3194. name: 'consumableUseLootBox',
  3195. args: { libId, amount },
  3196. ident: 'consumableUseLootBox_' + libId,
  3197. });
  3198. deleteItems[libId] = -amount;
  3199. }
  3200. }
  3201. const responses = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3202. for (const loot of responses) {
  3203. const [count, result] = Object.entries(loot).pop();
  3204. countLootBox += +count;
  3205. mergeItemsObj(lootBox, result);
  3206. }
  3207. isChange = true;
  3208. this.onReadySuccess = () => {
  3209. cheats.updateInventory({ consumable: deleteItems });
  3210. cheats.refreshInventory();
  3211. };
  3212. }
  3213. }
  3214.  
  3215. if (isChange) {
  3216. call.result.response = {
  3217. [countLootBox]: lootBox,
  3218. };
  3219. }
  3220.  
  3221. }
  3222. /**
  3223. * Dungeon recalculation (fix endless cards)
  3224. * Прерасчет подземки (исправление бесконечных карт)
  3225. */
  3226. if (call.ident == callsIdent['dungeonStartBattle']) {
  3227. lastDungeonBattleData = call.result.response;
  3228. lastDungeonBattleStart = Date.now();
  3229. }
  3230. /**
  3231. * Getting the number of prediction cards
  3232. * Получение количества карт предсказаний
  3233. */
  3234. if (call.ident == callsIdent['inventoryGet']) {
  3235. countPredictionCard = call.result.response.consumable[81] || 0;
  3236. }
  3237. /**
  3238. * Getting subscription status
  3239. * Получение состояния подписки
  3240. */
  3241. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3242. const subscription = call.result.response.subscription;
  3243. if (subscription) {
  3244. subEndTime = subscription.endTime * 1000;
  3245. }
  3246. }
  3247. /**
  3248. * Getting prediction cards
  3249. * Получение карт предсказаний
  3250. */
  3251. if (call.ident == callsIdent['questFarm']) {
  3252. const consumable = call.result.response?.consumable;
  3253. if (consumable && consumable[81]) {
  3254. countPredictionCard += consumable[81];
  3255. console.log(`Cards: ${countPredictionCard}`);
  3256. }
  3257. }
  3258. /**
  3259. * Hiding extra servers
  3260. * Скрытие лишних серверов
  3261. */
  3262. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3263. let servers = call.result.response.users.map(s => s.serverId)
  3264. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3265. isChange = true;
  3266. }
  3267. /**
  3268. * Displays player positions in the adventure
  3269. * Отображает позиции игроков в приключении
  3270. */
  3271. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3272. const users = Object.values(call.result.response.users);
  3273. const mapIdent = call.result.response.mapIdent;
  3274. const adventureId = call.result.response.adventureId;
  3275. const maps = {
  3276. adv_strongford_3pl_hell: 9,
  3277. adv_valley_3pl_hell: 10,
  3278. adv_ghirwil_3pl_hell: 11,
  3279. adv_angels_3pl_hell: 12,
  3280. }
  3281. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3282. msg += '<br>' + I18N('PLAYER_POS');
  3283. for (const user of users) {
  3284. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3285. }
  3286. setProgress(msg, false, hideProgress);
  3287. }
  3288. /**
  3289. * Automatic launch of a raid at the end of the adventure
  3290. * Автоматический запуск рейда при окончании приключения
  3291. */
  3292. if (call.ident == callsIdent['adventure_end']) {
  3293. autoRaidAdventure()
  3294. }
  3295. /** Удаление лавки редкостей */
  3296. if (call.ident == callsIdent['missionRaid']) {
  3297. if (call.result?.heroesMerchant) {
  3298. delete call.result.heroesMerchant;
  3299. isChange = true;
  3300. }
  3301. }
  3302. /** missionTimer */
  3303. if (call.ident == callsIdent['missionStart']) {
  3304. missionBattle = call.result.response;
  3305. }
  3306. /** Награды турнира стихий */
  3307. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3308. const trophys = call.result.response;
  3309. const calls = [];
  3310. for (const week in trophys) {
  3311. const trophy = trophys[week];
  3312. if (!trophy.championRewardFarmed) {
  3313. calls.push({
  3314. name: 'hallOfFameFarmTrophyReward',
  3315. args: { trophyId: week, rewardType: 'champion' },
  3316. ident: 'body_champion_' + week,
  3317. });
  3318. }
  3319. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3320. calls.push({
  3321. name: 'hallOfFameFarmTrophyReward',
  3322. args: { trophyId: week, rewardType: 'clan' },
  3323. ident: 'body_clan_' + week,
  3324. });
  3325. }
  3326. }
  3327. if (calls.length) {
  3328. Send({ calls })
  3329. .then((e) => e.results.map((e) => e.result.response))
  3330. .then(async results => {
  3331. let coin18 = 0,
  3332. coin19 = 0,
  3333. gold = 0,
  3334. starmoney = 0;
  3335. for (const r of results) {
  3336. coin18 += r?.coin ? +r.coin[18] : 0;
  3337. coin19 += r?.coin ? +r.coin[19] : 0;
  3338. gold += r?.gold ? +r.gold : 0;
  3339. starmoney += r?.starmoney ? +r.starmoney : 0;
  3340. }
  3341. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3342. if (coin18) {
  3343. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3344. }
  3345. if (coin19) {
  3346. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3347. }
  3348. if (gold) {
  3349. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3350. }
  3351. if (starmoney) {
  3352. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3353. }
  3354. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3355. });
  3356. }
  3357. }
  3358. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3359. clanDominationGetInfo = call.result.response;
  3360. }
  3361. if (call.ident == callsIdent['clanRaid_endBossBattle']) {
  3362. console.log(call.result.response);
  3363. const damage = Object.values(call.result.response.damage).reduce((a, e) => a + e);
  3364. if (call.result.response.result.afterInvalid) {
  3365. addProgress('<br>' + I18N('SERVER_NOT_ACCEPT'));
  3366. }
  3367. addProgress('<br>Server > ' + I18N('BOSS_DAMAGE') + damage.toLocaleString());
  3368. }
  3369. if (call.ident == callsIdent['invasion_getInfo']) {
  3370. const r = call.result.response;
  3371. if (r?.actions?.length) {
  3372. const boss = r.actions.find((e) => e.payload.id === 217);
  3373. invasionInfo.buff = r.buffAmount;
  3374. invasionInfo.bossLvl = boss.payload.level;
  3375. if (isChecked('tryFixIt_v2')) {
  3376. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3377. setProgress(
  3378. I18N('INVASION_BOSS_BUFF', {
  3379. bossLvl: invasionInfo.bossLvl,
  3380. needBuff: pack.buff,
  3381. haveBuff: invasionInfo.buff
  3382. }),
  3383. false
  3384. );
  3385. }
  3386. }
  3387. }
  3388. if (call.ident == callsIdent['workshopBuff_create']) {
  3389. const r = call.result.response;
  3390. if (r.id == 1) {
  3391. invasionInfo.buff = r.amount;
  3392. if (isChecked('tryFixIt_v2')) {
  3393. const pack = invasionDataPacks[invasionInfo.bossLvl];
  3394. setProgress(
  3395. I18N('INVASION_BOSS_BUFF', {
  3396. bossLvl: invasionInfo.bossLvl,
  3397. needBuff: pack.buff,
  3398. haveBuff: invasionInfo.buff,
  3399. }),
  3400. false
  3401. );
  3402. }
  3403. }
  3404. }
  3405. /*
  3406. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3407. this.onReadySuccess = async function () {
  3408. const result = await Send({
  3409. calls: [
  3410. {
  3411. name: 'clanDomination_mapState',
  3412. args: {},
  3413. ident: 'clanDomination_mapState',
  3414. },
  3415. ],
  3416. }).then((e) => e.results[0].result.response);
  3417. let townPositions = result.townPositions;
  3418. let positions = {};
  3419. for (let pos in townPositions) {
  3420. let townPosition = townPositions[pos];
  3421. positions[townPosition.position] = townPosition;
  3422. }
  3423. Object.assign(clanDominationGetInfo, {
  3424. townPositions: positions,
  3425. });
  3426. let userPositions = result.userPositions;
  3427. for (let pos in clanDominationGetInfo.townPositions) {
  3428. let townPosition = clanDominationGetInfo.townPositions[pos];
  3429. if (townPosition.status) {
  3430. userPositions[townPosition.userId] = +pos;
  3431. }
  3432. }
  3433. cheats.updateMap(result);
  3434. };
  3435. }
  3436. if (call.ident == callsIdent['clanDomination_mapState']) {
  3437. const townPositions = call.result.response.townPositions;
  3438. const userPositions = call.result.response.userPositions;
  3439. for (let pos in townPositions) {
  3440. let townPos = townPositions[pos];
  3441. if (townPos.status) {
  3442. userPositions[townPos.userId] = townPos.position;
  3443. }
  3444. }
  3445. isChange = true;
  3446. }
  3447. */
  3448. }
  3449. if (mainReward && artifactChestOpen) {
  3450. console.log(allReward);
  3451. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3452. artifactChestOpen = false;
  3453. artifactChestOpenCallName = '';
  3454. isChange = true;
  3455. }
  3456. } catch(err) {
  3457. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3458. }
  3459.  
  3460. if (isChange) {
  3461. Object.defineProperty(this, 'responseText', {
  3462. writable: true
  3463. });
  3464. this.responseText = JSON.stringify(respond);
  3465. }
  3466. }
  3467.  
  3468. /** Добавляет в бой эффекты усиления*/
  3469. function addBuff(battle) {
  3470. let effects = battle.effects;
  3471. let buffType = getInput('needResource2');
  3472. if (-1 < buffType && buffType < 7) {
  3473. let percentBuff = getInput('needResource');
  3474. effects.defenders = {};
  3475. effects.defenders[buffs[buffType]] = percentBuff;
  3476. } else if (buffType.slice(0, 1) == "-" || isChecked('treningBattle')) {
  3477. buffType = parseInt(buffType.slice(1), 10);
  3478. effects.defenders = repleyBattle.effects;
  3479. battle.defenders[0] = repleyBattle.defenders;
  3480. let def = battle.defenders[0];
  3481. if (buffType == 1) {
  3482. for (let i in def) {
  3483. let state = def[i].state;
  3484. state.hp = state.maxHp;
  3485. state.energy = 0;
  3486. state.isDead = false;
  3487. }
  3488. } else if (buffType == 2 || isChecked('finishingBattle')) {
  3489. for (let i in def) {
  3490. let state2 = def[i].state;
  3491. let rState = repleyBattle.state[i];
  3492. if (!!rState) {
  3493. state2.hp = rState.hp;
  3494. state2.energy = rState.energy;
  3495. state2.isDead = rState.isDead;
  3496. } else {
  3497. state2.hp = 0;
  3498. state2.energy = 0;
  3499. state2.isDead = true;
  3500. }
  3501. }
  3502. }
  3503. }
  3504. }
  3505. const buffs = ['percentBuffAll_allAttacks', 'percentBuffAll_armor', 'percentBuffAll_magicResist', 'percentBuffAll_physicalAttack', 'percentBuffAll_magicPower', 'percentDamageBuff_dot', 'percentBuffAll_healing', 'percentBuffAllForFallenAllies', 'percentBuffAll_energyIncrease', 'percentIncomeDamageReduce_any', 'percentIncomeDamageReduce_physical', 'percentIncomeDamageReduce_magic', 'percentIncomeDamageReduce_dot', 'percentBuffHp', 'percentBuffByPerk_energyIncrease_8', 'percentBuffByPerk_energyIncrease_5', 'percentBuffByPerk_energyIncrease_4', 'percentBuffByPerk_allAttacks_5', 'percentBuffByPerk_allAttacks_4', 'percentBuffByPerk_allAttacks_9', 'percentBuffByPerk_castSpeed_7', 'percentBuffByPerk_castSpeed_6', 'percentBuffByPerk_castSpeed_10', 'percentBuffByPerk_armorPenetration_6', 'percentBuffByPerk_physicalAttack_6', 'percentBuffByPerk_armorPenetration_10', 'percentBuffByPerk_physicalAttack_10', 'percentBuffByPerk_magicPower_7', 'percentDamageBuff_any','percentDamageBuff_physical','percentDamageBuff_magic','corruptedBoss_25_80_1_100_10','tutorialPetUlt_1.2','tutorialBossPercentDamage_1','corruptedBoss_50_80_1_100_10','corruptedBoss_75_80_1_100_10','corruptedBoss_80_80_1_100_10','percentBuffByPerk_castSpeed_4','percentBuffByPerk_energyIncrease_7','percentBuffByPerk_castSpeed_9','percentBuffByPerk_castSpeed_8','bossStageBuff_1000000_20000','bossStageBuff_1500000_30000','bossStageBuff_2000000_40000','bossStageBuff_3000000_50000','bossStageBuff_4000000_60000','bossStageBuff_5000000_70000','bossStageBuff_7500000_80000','bossStageBuff_11000000_90000','bossStageBuff_15000000_100000','bossStageBuff_20000000_120000','bossStageBuff_30000000_150000','bossStageBuff_40000000_200000','bossStageBuff_50000000_250000','percentBuffPet_strength','percentBuffPet_castSpeed','percentBuffPet_petEnergyIncrease','stormPowerBuff_100_1000','stormPowerBuff_100','changeStarSphereIncomingDamage_any','changeBlackHoleDamage','buffSpeedWhenStarfall','changeTeamStartEnergy','decreaseStarSphereDamage','avoidAllBlackholeDamageOnce','groveKeeperAvoidBlackholeDamageChance_3','undeadPreventsNightmares_3','engeneerIncreaseStarMachineIncomingDamage_3','overloadHealDamageStarSphere','nightmareDeathGiveLifesteal_100','starfallIncreaseAllyHeal_9_100','decreaseStarSphereDamage_4','increaseNightmaresIncomingDamageByCount','debuffNightmareOnSpawnFrom_7_hp','damageNightmareGiveEnergy','ultEnergyCompensationOnPlanetParade_6','bestDamagerBeforeParadeGetsImprovedBuff_any','starSphereDeathGiveEnergy','bestDamagerOnParadeBecomesImmortal_any','preventNightmare','buffStatWithHealing_physicalAttack_magic_100','buffStatWithHealing_magicPower_physical_100','buffStatWithHealing_hp_dot_100','replaceHealingWithDamage_magic','critWithRetaliation_10_dot','posessionWithBuffStat_25_20_5_10','energyBurnDamageWithEffect_magic_Silence_5_5','percentBuffHp','percentBuffAll_energyIncrease','percentBuffAll_magicResist','percentBuffAll_armor','percentIncomeDamageReduce_any','percentBuffAll_healing','percentIncomeDamageReduce_any','percentBuffHp','percentBuffAll_energyIncrease','percentIncomeDamageReduce_any','percentBuffHp','percentBuffByPerk_castSpeed_All','percentBuffAll_castSpeed'];
  3506.  
  3507. /**
  3508. * Request an answer to a question
  3509. *
  3510. * Запрос ответа на вопрос
  3511. */
  3512. async function getAnswer(question) {
  3513. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3514. /*const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3515. return new Promise((resolve, reject) => {
  3516. quizAPI.request().then((data) => {
  3517. if (data.result) {
  3518. resolve(data.result);
  3519. } else {
  3520. resolve(false);
  3521. }
  3522. }).catch((error) => {
  3523. console.error(error);
  3524. resolve(false);
  3525. });
  3526. })*/
  3527. }
  3528.  
  3529. /**
  3530. * Submitting a question and answer to a database
  3531. *
  3532. * Отправка вопроса и ответа в базу данных
  3533. */
  3534. function sendAnswerInfo(answerInfo) {
  3535. // c29tZSBub25zZW5zZQ==
  3536. /*const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3537. quizAPI.request().then((data) => {
  3538. if (data.result) {
  3539. console.log(I18N('SENT_QUESTION'));
  3540. }
  3541. });*/
  3542. }
  3543.  
  3544. /**
  3545. * Returns the battle type by preset type
  3546. *
  3547. * Возвращает тип боя по типу пресета
  3548. */
  3549. function getBattleType(strBattleType) {
  3550. if (!strBattleType) {
  3551. return null;
  3552. }
  3553. switch (strBattleType) {
  3554. case 'titan_pvp':
  3555. return 'get_titanPvp';
  3556. case 'titan_pvp_manual':
  3557. case 'titan_clan_pvp':
  3558. case 'clan_pvp_titan':
  3559. case 'clan_global_pvp_titan':
  3560. case 'brawl_titan':
  3561. case 'challenge_titan':
  3562. case 'titan_mission':
  3563. return 'get_titanPvpManual';
  3564. case 'clan_raid': // Asgard Boss // Босс асгарда
  3565. case 'adventure': // Adventures // Приключения
  3566. case 'clan_global_pvp':
  3567. case 'epic_brawl':
  3568. case 'clan_pvp':
  3569. return 'get_clanPvp';
  3570. case 'dungeon_titan':
  3571. case 'titan_tower':
  3572. return 'get_titan';
  3573. case 'tower':
  3574. case 'clan_dungeon':
  3575. return 'get_tower';
  3576. case 'pve':
  3577. case 'mission':
  3578. return 'get_pve';
  3579. case 'mission_boss':
  3580. return 'get_missionBoss';
  3581. case 'challenge':
  3582. case 'pvp_manual':
  3583. return 'get_pvpManual';
  3584. case 'grand':
  3585. case 'arena':
  3586. case 'pvp':
  3587. case 'clan_domination':
  3588. return 'get_pvp';
  3589. case 'core':
  3590. return 'get_core';
  3591. default: {
  3592. if (strBattleType.includes('invasion')) {
  3593. return 'get_invasion';
  3594. }
  3595. if (strBattleType.includes('boss')) {
  3596. return 'get_boss';
  3597. }
  3598. if (strBattleType.includes('titan_arena')) {
  3599. return 'get_titanPvpManual';
  3600. }
  3601. return 'get_clanPvp';
  3602. }
  3603. }
  3604. }
  3605. /**
  3606. * Returns the class name of the passed object
  3607. *
  3608. * Возвращает название класса переданного объекта
  3609. */
  3610. function getClass(obj) {
  3611. return {}.toString.call(obj).slice(8, -1);
  3612. }
  3613. /**
  3614. * Calculates the request signature
  3615. *
  3616. * Расчитывает сигнатуру запроса
  3617. */
  3618. this.getSignature = function(headers, data) {
  3619. const sign = {
  3620. signature: '',
  3621. length: 0,
  3622. add: function (text) {
  3623. this.signature += text;
  3624. if (this.length < this.signature.length) {
  3625. this.length = 3 * (this.signature.length + 1) >> 1;
  3626. }
  3627. },
  3628. }
  3629. sign.add(headers["X-Request-Id"]);
  3630. sign.add(':');
  3631. sign.add(headers["X-Auth-Token"]);
  3632. sign.add(':');
  3633. sign.add(headers["X-Auth-Session-Id"]);
  3634. sign.add(':');
  3635. sign.add(data);
  3636. sign.add(':');
  3637. sign.add('LIBRARY-VERSION=1');
  3638. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3639.  
  3640. return md5(sign.signature);
  3641. }
  3642. /**
  3643. * Creates an interface
  3644. *
  3645. * Создает интерфейс
  3646. */
  3647. function createInterface() {
  3648. popup.init();
  3649. scriptMenu.init({
  3650. showMenu: true
  3651. });
  3652. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3653. scriptMenu.addHeader('v' + GM_info.script.version);
  3654. }
  3655.  
  3656. function addControls() {
  3657. createInterface();
  3658. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3659. for (let name in checkboxes) {
  3660. if (checkboxes[name].hide) {
  3661. continue;
  3662. }
  3663. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3664. /**
  3665. * Getting the state of checkboxes from storage
  3666. * Получаем состояние чекбоксов из storage
  3667. */
  3668. let val = storage.get(name, null);
  3669. if (val != null) {
  3670. checkboxes[name].cbox.checked = val;
  3671. } else {
  3672. storage.set(name, checkboxes[name].default);
  3673. checkboxes[name].cbox.checked = checkboxes[name].default;
  3674. }
  3675. /**
  3676. * Tracing the change event of the checkbox for writing to storage
  3677. * Отсеживание события изменения чекбокса для записи в storage
  3678. */
  3679. checkboxes[name].cbox.dataset['name'] = name;
  3680. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3681. const nameCheckbox = this.dataset['name'];
  3682. /*
  3683. if (this.checked && nameCheckbox == 'cancelBattle') {
  3684. this.checked = false;
  3685. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3686. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3687. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3688. ])) {
  3689. return;
  3690. }
  3691. this.checked = true;
  3692. }
  3693. */
  3694. storage.set(nameCheckbox, this.checked);
  3695. })
  3696. }
  3697.  
  3698. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3699. for (let name in inputs) {
  3700. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3701. /**
  3702. * Get inputText state from storage
  3703. * Получаем состояние inputText из storage
  3704. */
  3705. let val = storage.get(name, null);
  3706. if (val != null) {
  3707. inputs[name].input.value = val;
  3708. } else {
  3709. storage.set(name, inputs[name].default);
  3710. inputs[name].input.value = inputs[name].default;
  3711. }
  3712. /**
  3713. * Tracing a field change event for a record in storage
  3714. * Отсеживание события изменения поля для записи в storage
  3715. */
  3716. inputs[name].input.dataset['name'] = name;
  3717. inputs[name].input.addEventListener('input', function () {
  3718. const inputName = this.dataset['name'];
  3719. let value = +this.value;
  3720. if (!value || Number.isNaN(value)) {
  3721. value = storage.get(inputName, inputs[inputName].default);
  3722. inputs[name].input.value = value;
  3723. }
  3724. storage.set(inputName, value);
  3725. })
  3726. }
  3727. const inputDetails2 = scriptMenu.addDetails(I18N('SAVING'));
  3728. for (let name in inputs2) {
  3729. inputs2[name].input = scriptMenu.addInputText(inputs2[name].title, false, inputDetails2);
  3730. /**
  3731. * Get inputText state from storage
  3732. * Получаем состояние inputText из storage
  3733. */
  3734. let val = storage.get(name, null);
  3735. if (val != null) {
  3736. inputs2[name].input.value = val;
  3737. } else {
  3738. storage.set(name, inputs2[name].default);
  3739. inputs2[name].input.value = inputs2[name].default;
  3740. }
  3741. /**
  3742. * Tracing a field change event for a record in storage
  3743. * Отсеживание события изменения поля для записи в storage
  3744. */
  3745. inputs2[name].input.dataset['name'] = name;
  3746. inputs2[name].input.addEventListener('input', function () {
  3747. const inputName = this.dataset['name'];
  3748. let value = +this.value;
  3749. if (!value || Number.isNaN(value)) {
  3750. value = storage.get(inputName, inputs2[inputName].default);
  3751. inputs2[name].input.value = value;
  3752. }
  3753. storage.set(inputName, value);
  3754. })
  3755. }
  3756. /* const inputDetails3 = scriptMenu.addDetails(I18N('USER_ID'));
  3757. for (let name in inputs3) {
  3758. inputs3[name].input = scriptMenu.addInputText(inputs3[name].title, false, inputDetails3);
  3759. /**
  3760. * Get inputText state from storage
  3761. * Получаем состояние inputText из storage
  3762. *
  3763. let val = storage.get(name, null);
  3764. if (val != null) {
  3765. inputs3[name].input.value = val;
  3766. } else {
  3767. storage.set(name, inputs3[name].default);
  3768. inputs3[name].input.value = inputs3[name].default;
  3769. }
  3770. /**
  3771. * Tracing a field change event for a record in storage
  3772. * Отсеживание события изменения поля для записи в storage
  3773. *
  3774. inputs3[name].input.dataset['name'] = name;
  3775. inputs3[name].input.addEventListener('input', function () {
  3776. const inputName = this.dataset['name'];
  3777. let value = +this.value;
  3778. if (!value || Number.isNaN(value)) {
  3779. value = storage.get(inputName, inputs3[inputName].default);
  3780. inputs3[name].input.value = value;
  3781. }
  3782. storage.set(inputName, value);
  3783. })
  3784. }*/
  3785. }
  3786.  
  3787. /**
  3788. * Sending a request
  3789. *
  3790. * Отправка запроса
  3791. */
  3792. function send(json, callback, pr) {
  3793. if (typeof json == 'string') {
  3794. json = JSON.parse(json);
  3795. }
  3796. for (const call of json.calls) {
  3797. if (!call?.context?.actionTs) {
  3798. call.context = {
  3799. actionTs: Math.floor(performance.now())
  3800. }
  3801. }
  3802. }
  3803. json = JSON.stringify(json);
  3804. /**
  3805. * We get the headlines of the previous intercepted request
  3806. * Получаем заголовки предыдущего перехваченого запроса
  3807. */
  3808. let headers = lastHeaders;
  3809. /**
  3810. * We increase the header of the query Certifier by 1
  3811. * Увеличиваем заголовок идетификатора запроса на 1
  3812. */
  3813. headers["X-Request-Id"]++;
  3814. /**
  3815. * We calculate the title with the signature
  3816. * Расчитываем заголовок с сигнатурой
  3817. */
  3818. headers["X-Auth-Signature"] = getSignature(headers, json);
  3819. /**
  3820. * Create a new ajax request
  3821. * Создаем новый AJAX запрос
  3822. */
  3823. let xhr = new XMLHttpRequest;
  3824. /**
  3825. * Indicate the previously saved URL for API queries
  3826. * Указываем ранее сохраненный URL для API запросов
  3827. */
  3828. xhr.open('POST', apiUrl, true);
  3829. /**
  3830. * Add the function to the event change event
  3831. * Добавляем функцию к событию смены статуса запроса
  3832. */
  3833. xhr.onreadystatechange = function() {
  3834. /**
  3835. * If the result of the request is obtained, we call the flask function
  3836. * Если результат запроса получен вызываем колбек функцию
  3837. */
  3838. if(xhr.readyState == 4) {
  3839. callback(xhr.response, pr);
  3840. }
  3841. };
  3842. /**
  3843. * Indicate the type of request
  3844. * Указываем тип запроса
  3845. */
  3846. xhr.responseType = 'json';
  3847. /**
  3848. * We set the request headers
  3849. * Задаем заголовки запроса
  3850. */
  3851. for(let nameHeader in headers) {
  3852. let head = headers[nameHeader];
  3853. xhr.setRequestHeader(nameHeader, head);
  3854. }
  3855. /**
  3856. * Sending a request
  3857. * Отправляем запрос
  3858. */
  3859. xhr.send(json);
  3860. }
  3861.  
  3862. let hideTimeoutProgress = 0;
  3863. /**
  3864. * Hide progress
  3865. *
  3866. * Скрыть прогресс
  3867. */
  3868. function hideProgress(timeout) {
  3869. timeout = timeout || 0;
  3870. clearTimeout(hideTimeoutProgress);
  3871. hideTimeoutProgress = setTimeout(function () {
  3872. scriptMenu.setStatus('');
  3873. }, timeout);
  3874. }
  3875. /**
  3876. * Progress display
  3877. *
  3878. * Отображение прогресса
  3879. */
  3880. function setProgress(text, hide, onclick) {
  3881. scriptMenu.setStatus(text, onclick);
  3882. hide = hide || false;
  3883. if (hide) {
  3884. hideProgress(3000);
  3885. }
  3886. }
  3887.  
  3888. /**
  3889. * Progress added
  3890. *
  3891. * Дополнение прогресса
  3892. */
  3893. function addProgress(text) {
  3894. scriptMenu.addStatus(text);
  3895. }
  3896.  
  3897. /**
  3898. * Returns the timer value depending on the subscription
  3899. *
  3900. * Возвращает значение таймера в зависимости от подписки
  3901. */
  3902. function getTimer(time, div) {
  3903. let speedDiv = 5;
  3904. if (subEndTime < Date.now()) {
  3905. speedDiv = div || 1.5;
  3906. }
  3907. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3908. }
  3909.  
  3910. function startSlave() {
  3911. const sFix = new slaveFixBattle();
  3912. sFix.wsStart();
  3913. }
  3914. this.testFuntions = {
  3915. hideProgress,
  3916. setProgress,
  3917. addProgress,
  3918. masterFix: false,
  3919. startSlave,
  3920. };
  3921.  
  3922. /**
  3923. * Calculates HASH MD5 from string
  3924. *
  3925. * Расчитывает HASH MD5 из строки
  3926. *
  3927. * [js-md5]{@link https://github.com/emn178/js-md5}
  3928. *
  3929. * @namespace md5
  3930. * @version 0.7.3
  3931. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3932. * @copyright Chen, Yi-Cyuan 2014-2017
  3933. * @license MIT
  3934. */
  3935. !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 _}))}();
  3936.  
  3937. /**
  3938. * Script for beautiful dialog boxes
  3939. *
  3940. * Скрипт для красивых диалоговых окошек
  3941. */
  3942. const popup = new (function () {
  3943. this.popUp,
  3944. this.downer,
  3945. this.middle,
  3946. this.msgText,
  3947. this.buttons = [];
  3948. this.checkboxes = [];
  3949. this.dialogPromice = null;
  3950. this.isInit = false;
  3951.  
  3952. this.init = function () {
  3953. if (this.isInit) {
  3954. return;
  3955. }
  3956. addStyle();
  3957. addBlocks();
  3958. addEventListeners();
  3959. this.isInit = true;
  3960. }
  3961.  
  3962. const addEventListeners = () => {
  3963. document.addEventListener('keyup', (e) => {
  3964. if (e.key == 'Escape') {
  3965. if (this.dialogPromice) {
  3966. const { func, result } = this.dialogPromice;
  3967. this.dialogPromice = null;
  3968. popup.hide();
  3969. func(result);
  3970. }
  3971. }
  3972. });
  3973. }
  3974.  
  3975. const addStyle = () => {
  3976. let style = document.createElement('style');
  3977. style.innerText = `
  3978. .PopUp_ {
  3979. position: absolute;
  3980. min-width: 300px;
  3981. max-width: 500px;
  3982. max-height: 600px;
  3983. background-color: #190e08e6;
  3984. z-index: 10001;
  3985. top: 169px;
  3986. left: 345px;
  3987. border: 3px #ce9767 solid;
  3988. border-radius: 10px;
  3989. display: flex;
  3990. flex-direction: column;
  3991. justify-content: space-around;
  3992. padding: 15px 9px;
  3993. box-sizing: border-box;
  3994. }
  3995.  
  3996. .PopUp_back {
  3997. position: absolute;
  3998. background-color: #00000066;
  3999. width: 100%;
  4000. height: 100%;
  4001. z-index: 10000;
  4002. top: 0;
  4003. left: 0;
  4004. }
  4005.  
  4006. .PopUp_close {
  4007. width: 40px;
  4008. height: 40px;
  4009. position: absolute;
  4010. right: -18px;
  4011. top: -18px;
  4012. border: 3px solid #c18550;
  4013. border-radius: 20px;
  4014. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4015. background-position-y: 3px;
  4016. box-shadow: -1px 1px 3px black;
  4017. cursor: pointer;
  4018. box-sizing: border-box;
  4019. }
  4020.  
  4021. .PopUp_close:hover {
  4022. filter: brightness(1.2);
  4023. }
  4024.  
  4025. .PopUp_crossClose {
  4026. width: 100%;
  4027. height: 100%;
  4028. background-size: 65%;
  4029. background-position: center;
  4030. background-repeat: no-repeat;
  4031. 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")
  4032. }
  4033.  
  4034. .PopUp_blocks {
  4035. width: 100%;
  4036. height: 50%;
  4037. display: flex;
  4038. justify-content: space-evenly;
  4039. align-items: center;
  4040. flex-wrap: wrap;
  4041. justify-content: center;
  4042. }
  4043.  
  4044. .PopUp_blocks:last-child {
  4045. margin-top: 25px;
  4046. }
  4047.  
  4048. .PopUp_buttons {
  4049. display: flex;
  4050. margin: 7px 10px;
  4051. flex-direction: column;
  4052. }
  4053.  
  4054. .PopUp_button {
  4055. background-color: #52A81C;
  4056. border-radius: 5px;
  4057. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4058. cursor: pointer;
  4059. padding: 4px 12px 6px;
  4060. }
  4061.  
  4062. .PopUp_input {
  4063. text-align: center;
  4064. font-size: 16px;
  4065. height: 27px;
  4066. border: 1px solid #cf9250;
  4067. border-radius: 9px 9px 0px 0px;
  4068. background: transparent;
  4069. color: #fce1ac;
  4070. padding: 1px 10px;
  4071. box-sizing: border-box;
  4072. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  4073. }
  4074.  
  4075. .PopUp_checkboxes {
  4076. display: flex;
  4077. flex-direction: column;
  4078. margin: 15px 15px -5px 15px;
  4079. align-items: flex-start;
  4080. }
  4081.  
  4082. .PopUp_ContCheckbox {
  4083. margin: 2px 0px;
  4084. }
  4085.  
  4086. .PopUp_checkbox {
  4087. position: absolute;
  4088. z-index: -1;
  4089. opacity: 0;
  4090. }
  4091. .PopUp_checkbox+label {
  4092. display: inline-flex;
  4093. align-items: center;
  4094. user-select: none;
  4095.  
  4096. font-size: 15px;
  4097. font-family: sans-serif;
  4098. font-weight: 600;
  4099. font-stretch: condensed;
  4100. letter-spacing: 1px;
  4101. color: #fce1ac;
  4102. text-shadow: 0px 0px 1px;
  4103. }
  4104. .PopUp_checkbox+label::before {
  4105. content: '';
  4106. display: inline-block;
  4107. width: 20px;
  4108. height: 20px;
  4109. border: 1px solid #cf9250;
  4110. border-radius: 7px;
  4111. margin-right: 7px;
  4112. }
  4113. .PopUp_checkbox:checked+label::before {
  4114. 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");
  4115. }
  4116.  
  4117. .PopUp_input::placeholder {
  4118. color: #fce1ac75;
  4119. }
  4120.  
  4121. .PopUp_input:focus {
  4122. outline: 0;
  4123. }
  4124.  
  4125. .PopUp_input + .PopUp_button {
  4126. border-radius: 0px 0px 5px 5px;
  4127. padding: 2px 18px 5px;
  4128. }
  4129.  
  4130. .PopUp_button:hover {
  4131. filter: brightness(1.2);
  4132. }
  4133.  
  4134. .PopUp_button:active {
  4135. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  4136. }
  4137.  
  4138. .PopUp_text {
  4139. font-size: 22px;
  4140. font-family: sans-serif;
  4141. font-weight: 600;
  4142. font-stretch: condensed;
  4143. white-space: pre-wrap;
  4144. letter-spacing: 1px;
  4145. text-align: center;
  4146. }
  4147.  
  4148. .PopUp_buttonText {
  4149. color: #E4FF4C;
  4150. text-shadow: 0px 1px 2px black;
  4151. }
  4152.  
  4153. .PopUp_msgText {
  4154. color: #FDE5B6;
  4155. text-shadow: 0px 0px 2px;
  4156. }
  4157.  
  4158. .PopUp_hideBlock {
  4159. display: none;
  4160. }
  4161. `;
  4162. document.head.appendChild(style);
  4163. }
  4164.  
  4165. const addBlocks = () => {
  4166. this.back = document.createElement('div');
  4167. this.back.classList.add('PopUp_back');
  4168. this.back.classList.add('PopUp_hideBlock');
  4169. document.body.append(this.back);
  4170.  
  4171. this.popUp = document.createElement('div');
  4172. this.popUp.classList.add('PopUp_');
  4173. this.back.append(this.popUp);
  4174.  
  4175. let upper = document.createElement('div')
  4176. upper.classList.add('PopUp_blocks');
  4177. this.popUp.append(upper);
  4178.  
  4179. this.middle = document.createElement('div')
  4180. this.middle.classList.add('PopUp_blocks');
  4181. this.middle.classList.add('PopUp_checkboxes');
  4182. this.popUp.append(this.middle);
  4183.  
  4184. this.downer = document.createElement('div')
  4185. this.downer.classList.add('PopUp_blocks');
  4186. this.popUp.append(this.downer);
  4187.  
  4188. this.msgText = document.createElement('div');
  4189. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  4190. upper.append(this.msgText);
  4191. }
  4192.  
  4193. this.showBack = function () {
  4194. this.back.classList.remove('PopUp_hideBlock');
  4195. }
  4196.  
  4197. this.hideBack = function () {
  4198. this.back.classList.add('PopUp_hideBlock');
  4199. }
  4200.  
  4201. this.show = function () {
  4202. if (this.checkboxes.length) {
  4203. this.middle.classList.remove('PopUp_hideBlock');
  4204. }
  4205. this.showBack();
  4206. this.popUp.classList.remove('PopUp_hideBlock');
  4207. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  4208. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  4209. }
  4210.  
  4211. this.hide = function () {
  4212. this.hideBack();
  4213. this.popUp.classList.add('PopUp_hideBlock');
  4214. }
  4215.  
  4216. this.addAnyButton = (option) => {
  4217. const contButton = document.createElement('div');
  4218. contButton.classList.add('PopUp_buttons');
  4219. this.downer.append(contButton);
  4220.  
  4221. let inputField = {
  4222. value: option.result || option.default
  4223. }
  4224. if (option.isInput) {
  4225. inputField = document.createElement('input');
  4226. inputField.type = 'text';
  4227. if (option.placeholder) {
  4228. inputField.placeholder = option.placeholder;
  4229. }
  4230. if (option.default) {
  4231. inputField.value = option.default;
  4232. }
  4233. inputField.classList.add('PopUp_input');
  4234. contButton.append(inputField);
  4235. }
  4236.  
  4237. const button = document.createElement('div');
  4238. button.classList.add('PopUp_button');
  4239. button.title = option.title || '';
  4240. contButton.append(button);
  4241.  
  4242. const buttonText = document.createElement('div');
  4243. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4244. buttonText.innerHTML = option.msg;
  4245. button.append(buttonText);
  4246.  
  4247. return { button, contButton, inputField };
  4248. }
  4249.  
  4250. this.addCloseButton = () => {
  4251. let button = document.createElement('div')
  4252. button.classList.add('PopUp_close');
  4253. this.popUp.append(button);
  4254.  
  4255. let crossClose = document.createElement('div')
  4256. crossClose.classList.add('PopUp_crossClose');
  4257. button.append(crossClose);
  4258.  
  4259. return { button, contButton: button };
  4260. }
  4261.  
  4262. this.addButton = (option, buttonClick) => {
  4263.  
  4264. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4265. if (option.isClose) {
  4266. this.dialogPromice = { func: buttonClick, result: option.result };
  4267. }
  4268. button.addEventListener('click', () => {
  4269. let result = '';
  4270. if (option.isInput) {
  4271. result = inputField.value;
  4272. }
  4273. if (option.isClose || option.isCancel) {
  4274. this.dialogPromice = null;
  4275. }
  4276. buttonClick(result);
  4277. });
  4278.  
  4279. this.buttons.push(contButton);
  4280. }
  4281.  
  4282. this.clearButtons = () => {
  4283. while (this.buttons.length) {
  4284. this.buttons.pop().remove();
  4285. }
  4286. }
  4287.  
  4288. this.addCheckBox = (checkBox) => {
  4289. const contCheckbox = document.createElement('div');
  4290. contCheckbox.classList.add('PopUp_ContCheckbox');
  4291. this.middle.append(contCheckbox);
  4292.  
  4293. const checkbox = document.createElement('input');
  4294. checkbox.type = 'checkbox';
  4295. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4296. checkbox.dataset.name = checkBox.name;
  4297. checkbox.checked = checkBox.checked;
  4298. checkbox.label = checkBox.label;
  4299. checkbox.title = checkBox.title || '';
  4300. checkbox.classList.add('PopUp_checkbox');
  4301. contCheckbox.appendChild(checkbox)
  4302.  
  4303. const checkboxLabel = document.createElement('label');
  4304. checkboxLabel.innerText = checkBox.label;
  4305. checkboxLabel.title = checkBox.title || '';
  4306. checkboxLabel.setAttribute('for', checkbox.id);
  4307. contCheckbox.appendChild(checkboxLabel);
  4308.  
  4309. this.checkboxes.push(checkbox);
  4310. }
  4311.  
  4312. this.clearCheckBox = () => {
  4313. this.middle.classList.add('PopUp_hideBlock');
  4314. while (this.checkboxes.length) {
  4315. this.checkboxes.pop().parentNode.remove();
  4316. }
  4317. }
  4318.  
  4319. this.setMsgText = (text) => {
  4320. this.msgText.innerHTML = text;
  4321. }
  4322.  
  4323. this.getCheckBoxes = () => {
  4324. const checkBoxes = [];
  4325.  
  4326. for (const checkBox of this.checkboxes) {
  4327. checkBoxes.push({
  4328. name: checkBox.dataset.name,
  4329. label: checkBox.label,
  4330. checked: checkBox.checked
  4331. });
  4332. }
  4333.  
  4334. return checkBoxes;
  4335. }
  4336.  
  4337. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4338. if (!this.isInit) {
  4339. this.init();
  4340. }
  4341. this.clearButtons();
  4342. this.clearCheckBox();
  4343. return new Promise((complete, failed) => {
  4344. this.setMsgText(msg);
  4345. if (!buttOpt) {
  4346. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4347. }
  4348. for (const checkBox of checkBoxes) {
  4349. this.addCheckBox(checkBox);
  4350. }
  4351. for (let butt of buttOpt) {
  4352. this.addButton(butt, (result) => {
  4353. result = result || butt.result;
  4354. complete(result);
  4355. popup.hide();
  4356. });
  4357. if (butt.isCancel) {
  4358. this.dialogPromice = { func: complete, result: butt.result };
  4359. }
  4360. }
  4361. this.show();
  4362. });
  4363. }
  4364.  
  4365. });
  4366.  
  4367. /**
  4368. * Script control panel
  4369. *
  4370. * Панель управления скриптом
  4371. */
  4372. const scriptMenu = new (function () {
  4373.  
  4374. this.mainMenu,
  4375. this.buttons = [],
  4376. this.checkboxes = [];
  4377. this.option = {
  4378. showMenu: false,
  4379. showDetails: {}
  4380. };
  4381.  
  4382. this.init = function (option = {}) {
  4383. this.option = Object.assign(this.option, option);
  4384. this.option.showDetails = this.loadShowDetails();
  4385. addStyle();
  4386. addBlocks();
  4387. }
  4388.  
  4389. const addStyle = () => {
  4390. style = document.createElement('style');
  4391. style.innerText = `
  4392. .scriptMenu_status {
  4393. position: absolute;
  4394. z-index: 10001;
  4395. white-space: pre-wrap; //тест для выравнивания кнопок
  4396. /* max-height: 30px; */
  4397. top: -1px;
  4398. left: 30%;
  4399. cursor: pointer;
  4400. border-radius: 0px 0px 10px 10px;
  4401. background: #190e08e6;
  4402. border: 1px #ce9767 solid;
  4403. font-size: 18px;
  4404. font-family: sans-serif;
  4405. font-weight: 600;
  4406. font-stretch: condensed;
  4407. letter-spacing: 1px;
  4408. color: #fce1ac;
  4409. text-shadow: 0px 0px 1px;
  4410. transition: 0.5s;
  4411. padding: 2px 10px 3px;
  4412. }
  4413. .scriptMenu_statusHide {
  4414. top: -35px;
  4415. height: 30px;
  4416. overflow: hidden;
  4417. }
  4418. .scriptMenu_label {
  4419. position: absolute;
  4420. top: 30%;
  4421. left: -4px;
  4422. z-index: 9999;
  4423. cursor: pointer;
  4424. width: 30px;
  4425. height: 30px;
  4426. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4427. border: 1px solid #1a2f04;
  4428. border-radius: 5px;
  4429. box-shadow:
  4430. inset 0px 2px 4px #83ce26,
  4431. inset 0px -4px 6px #1a2f04,
  4432. 0px 0px 2px black,
  4433. 0px 0px 0px 2px #ce9767;
  4434. }
  4435. .scriptMenu_label:hover {
  4436. filter: brightness(1.2);
  4437. }
  4438. .scriptMenu_arrowLabel {
  4439. width: 100%;
  4440. height: 100%;
  4441. background-size: 75%;
  4442. background-position: center;
  4443. background-repeat: no-repeat;
  4444. 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");
  4445. box-shadow: 0px 1px 2px #000;
  4446. border-radius: 5px;
  4447. filter: drop-shadow(0px 1px 2px #000D);
  4448. }
  4449. .scriptMenu_main {
  4450. position: absolute;
  4451. max-width: 285px;
  4452. z-index: 9999;
  4453. top: 50%;
  4454. transform: translateY(-40%);
  4455. background: #190e08e6;
  4456. border: 1px #ce9767 solid;
  4457. border-radius: 0px 10px 10px 0px;
  4458. border-left: none;
  4459. padding: 5px 10px 5px 5px;
  4460. box-sizing: border-box;
  4461. font-size: 15px;
  4462. font-family: sans-serif;
  4463. font-weight: 600;
  4464. font-stretch: condensed;
  4465. letter-spacing: 1px;
  4466. color: #fce1ac;
  4467. text-shadow: 0px 0px 1px;
  4468. transition: 1s;
  4469. display: flex;
  4470. flex-direction: column;
  4471. flex-wrap: nowrap;
  4472. }
  4473. .scriptMenu_showMenu {
  4474. display: none;
  4475. }
  4476. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4477. left: 0px;
  4478. }
  4479. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4480. left: -300px;
  4481. }
  4482. .scriptMenu_divInput {
  4483. margin: 2px;
  4484. }
  4485. .scriptMenu_divInputText {
  4486. margin: 2px;
  4487. align-self: center;
  4488. display: flex;
  4489. }
  4490. .scriptMenu_checkbox {
  4491. position: absolute;
  4492. z-index: -1;
  4493. opacity: 0;
  4494. }
  4495. .scriptMenu_checkbox+label {
  4496. display: inline-flex;
  4497. align-items: center;
  4498. user-select: none;
  4499. }
  4500. .scriptMenu_checkbox+label::before {
  4501. content: '';
  4502. display: inline-block;
  4503. width: 20px;
  4504. height: 20px;
  4505. border: 1px solid #cf9250;
  4506. border-radius: 7px;
  4507. margin-right: 7px;
  4508. }
  4509. .scriptMenu_checkbox:checked+label::before {
  4510. 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");
  4511. }
  4512. .scriptMenu_close {
  4513. width: 40px;
  4514. height: 40px;
  4515. position: absolute;
  4516. right: -18px;
  4517. top: -18px;
  4518. border: 3px solid #c18550;
  4519. border-radius: 20px;
  4520. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4521. background-position-y: 3px;
  4522. box-shadow: -1px 1px 3px black;
  4523. cursor: pointer;
  4524. box-sizing: border-box;
  4525. }
  4526. .scriptMenu_close:hover {
  4527. filter: brightness(1.2);
  4528. }
  4529. .scriptMenu_crossClose {
  4530. width: 100%;
  4531. height: 100%;
  4532. background-size: 65%;
  4533. background-position: center;
  4534. background-repeat: no-repeat;
  4535. 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")
  4536. }
  4537. .scriptMenu_button {
  4538. user-select: none;
  4539. border-radius: 5px;
  4540. cursor: pointer;
  4541. padding: 5px 14px 8px;
  4542. margin: 4px;
  4543. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4544. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4545. }
  4546. .scriptMenu_button:hover {
  4547. filter: brightness(1.2);
  4548. }
  4549. .scriptMenu_button:active {
  4550. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4551. }
  4552. .scriptMenu_buttonText {
  4553. color: #fce5b7;
  4554. text-shadow: 0px 1px 2px black;
  4555. text-align: center;
  4556. }
  4557. .scriptMenu_header {
  4558. text-align: center;
  4559. align-self: center;
  4560. font-size: 15px;
  4561. margin: 0px 15px;
  4562. }
  4563. .scriptMenu_header a {
  4564. color: #fce5b7;
  4565. text-decoration: none;
  4566. }
  4567. .scriptMenu_InputText {
  4568. text-align: center;
  4569. width: 130px;
  4570. height: 24px;
  4571. border: 1px solid #cf9250;
  4572. border-radius: 9px;
  4573. background: transparent;
  4574. color: #fce1ac;
  4575. padding: 0px 10px;
  4576. box-sizing: border-box;
  4577. }
  4578. .scriptMenu_InputText:focus {
  4579. filter: brightness(1.2);
  4580. outline: 0;
  4581. }
  4582. .scriptMenu_InputText::placeholder {
  4583. color: #fce1ac75;
  4584. }
  4585. .scriptMenu_Summary {
  4586. cursor: pointer;
  4587. margin-left: 7px;
  4588. }
  4589. .scriptMenu_Details {
  4590. align-self: center;
  4591. }
  4592. `;
  4593. document.head.appendChild(style);
  4594. }
  4595.  
  4596. const addBlocks = () => {
  4597. const main = document.createElement('div');
  4598. document.body.appendChild(main);
  4599.  
  4600. this.status = document.createElement('div');
  4601. this.status.classList.add('scriptMenu_status');
  4602. this.setStatus('');
  4603. main.appendChild(this.status);
  4604.  
  4605. const label = document.createElement('label');
  4606. label.classList.add('scriptMenu_label');
  4607. label.setAttribute('for', 'checkbox_showMenu');
  4608. main.appendChild(label);
  4609.  
  4610. const arrowLabel = document.createElement('div');
  4611. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4612. label.appendChild(arrowLabel);
  4613.  
  4614. const checkbox = document.createElement('input');
  4615. checkbox.type = 'checkbox';
  4616. checkbox.id = 'checkbox_showMenu';
  4617. checkbox.checked = this.option.showMenu;
  4618. checkbox.classList.add('scriptMenu_showMenu');
  4619. main.appendChild(checkbox);
  4620.  
  4621. this.mainMenu = document.createElement('div');
  4622. this.mainMenu.classList.add('scriptMenu_main');
  4623. main.appendChild(this.mainMenu);
  4624.  
  4625. const closeButton = document.createElement('label');
  4626. closeButton.classList.add('scriptMenu_close');
  4627. closeButton.setAttribute('for', 'checkbox_showMenu');
  4628. this.mainMenu.appendChild(closeButton);
  4629.  
  4630. const crossClose = document.createElement('div');
  4631. crossClose.classList.add('scriptMenu_crossClose');
  4632. closeButton.appendChild(crossClose);
  4633. }
  4634.  
  4635. this.setStatus = (text, onclick) => {
  4636. if (!text) {
  4637. this.status.classList.add('scriptMenu_statusHide');
  4638. this.status.innerHTML = '';
  4639. } else {
  4640. this.status.classList.remove('scriptMenu_statusHide');
  4641. this.status.innerHTML = text;
  4642. }
  4643.  
  4644. if (typeof onclick == 'function') {
  4645. this.status.addEventListener("click", onclick, {
  4646. once: true
  4647. });
  4648. }
  4649. }
  4650.  
  4651. this.addStatus = (text) => {
  4652. if (!this.status.innerHTML) {
  4653. this.status.classList.remove('scriptMenu_statusHide');
  4654. }
  4655. this.status.innerHTML += text;
  4656. }
  4657. /**
  4658. * Adding a text element
  4659. *
  4660. * Добавление текстового элемента
  4661. * @param {String} text text // текст
  4662. * @param {Function} func Click function // функция по клику
  4663. * @param {HTMLDivElement} main parent // родитель
  4664. */
  4665. this.addHeader = (text, func, main) => {
  4666. main = main || this.mainMenu;
  4667. const header = document.createElement('div');
  4668. header.classList.add('scriptMenu_header');
  4669. header.innerHTML = text;
  4670. if (typeof func == 'function') {
  4671. header.addEventListener('click', func);
  4672. }
  4673. main.appendChild(header);
  4674. }
  4675.  
  4676. /**
  4677. * Adding a button
  4678. *
  4679. * Добавление кнопки
  4680. * @param {String} text
  4681. * @param {Function} func
  4682. * @param {String} title
  4683. * @param {HTMLDivElement} main parent // родитель
  4684. */
  4685. this.addButton = (text, func, title, main) => {
  4686. main = main || this.mainMenu;
  4687. const button = document.createElement('div');
  4688. button.classList.add('scriptMenu_button');
  4689. button.title = title;
  4690. button.addEventListener('click', func);
  4691. main.appendChild(button);
  4692.  
  4693. const buttonText = document.createElement('div');
  4694. buttonText.classList.add('scriptMenu_buttonText');
  4695. buttonText.innerText = text;
  4696. button.appendChild(buttonText);
  4697. this.buttons.push(button);
  4698.  
  4699. return button;
  4700. }
  4701.  
  4702. /**
  4703. * Adding checkbox
  4704. *
  4705. * Добавление чекбокса
  4706. * @param {String} label
  4707. * @param {String} title
  4708. * @param {HTMLDivElement} main parent // родитель
  4709. * @returns
  4710. */
  4711. this.addCheckbox = (label, title, main) => {
  4712. main = main || this.mainMenu;
  4713. const divCheckbox = document.createElement('div');
  4714. divCheckbox.classList.add('scriptMenu_divInput');
  4715. divCheckbox.title = title;
  4716. main.appendChild(divCheckbox);
  4717.  
  4718. const checkbox = document.createElement('input');
  4719. checkbox.type = 'checkbox';
  4720. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4721. checkbox.classList.add('scriptMenu_checkbox');
  4722. divCheckbox.appendChild(checkbox)
  4723.  
  4724. const checkboxLabel = document.createElement('label');
  4725. checkboxLabel.innerText = label;
  4726. checkboxLabel.setAttribute('for', checkbox.id);
  4727. divCheckbox.appendChild(checkboxLabel);
  4728.  
  4729. this.checkboxes.push(checkbox);
  4730. return checkbox;
  4731. }
  4732.  
  4733. /**
  4734. * Adding input field
  4735. *
  4736. * Добавление поля ввода
  4737. * @param {String} title
  4738. * @param {String} placeholder
  4739. * @param {HTMLDivElement} main parent // родитель
  4740. * @returns
  4741. */
  4742. this.addInputText = (title, placeholder, main) => {
  4743. main = main || this.mainMenu;
  4744. const divInputText = document.createElement('div');
  4745. divInputText.classList.add('scriptMenu_divInputText');
  4746. divInputText.title = title;
  4747. main.appendChild(divInputText);
  4748.  
  4749. const newInputText = document.createElement('input');
  4750. newInputText.type = 'text';
  4751. if (placeholder) {
  4752. newInputText.placeholder = placeholder;
  4753. }
  4754. newInputText.classList.add('scriptMenu_InputText');
  4755. divInputText.appendChild(newInputText)
  4756. return newInputText;
  4757. }
  4758.  
  4759. /**
  4760. * Adds a dropdown block
  4761. *
  4762. * Добавляет раскрывающийся блок
  4763. * @param {String} summary
  4764. * @param {String} name
  4765. * @returns
  4766. */
  4767. this.addDetails = (summaryText, name = null) => {
  4768. const details = document.createElement('details');
  4769. details.classList.add('scriptMenu_Details');
  4770. this.mainMenu.appendChild(details);
  4771.  
  4772. const summary = document.createElement('summary');
  4773. summary.classList.add('scriptMenu_Summary');
  4774. summary.innerText = summaryText;
  4775. if (name) {
  4776. const self = this;
  4777. details.open = this.option.showDetails[name];
  4778. details.dataset.name = name;
  4779. summary.addEventListener('click', () => {
  4780. self.option.showDetails[details.dataset.name] = !details.open;
  4781. self.saveShowDetails(self.option.showDetails);
  4782. });
  4783. }
  4784. details.appendChild(summary);
  4785.  
  4786. return details;
  4787. }
  4788.  
  4789. /**
  4790. * Saving the expanded state of the details blocks
  4791. *
  4792. * Сохранение состояния развенутости блоков details
  4793. * @param {*} value
  4794. */
  4795. this.saveShowDetails = (value) => {
  4796. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4797. }
  4798.  
  4799. /**
  4800. * Loading the state of expanded blocks details
  4801. *
  4802. * Загрузка состояния развенутости блоков details
  4803. * @returns
  4804. */
  4805. this.loadShowDetails = () => {
  4806. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4807.  
  4808. if (!showDetails) {
  4809. return {};
  4810. }
  4811.  
  4812. try {
  4813. showDetails = JSON.parse(showDetails);
  4814. } catch (e) {
  4815. return {};
  4816. }
  4817.  
  4818. return showDetails;
  4819. }
  4820. });
  4821.  
  4822. /**
  4823. * Пример использования
  4824. scriptMenu.init();
  4825. scriptMenu.addHeader('v1.508');
  4826. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4827. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4828. scriptMenu.addInputText('input подсказака');
  4829. */
  4830. /**
  4831. * Game Library
  4832. *
  4833. * Игровая библиотека
  4834. */
  4835. class Library {
  4836. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4837.  
  4838. constructor() {
  4839. if (!Library.instance) {
  4840. Library.instance = this;
  4841. }
  4842.  
  4843. return Library.instance;
  4844. }
  4845.  
  4846. async load() {
  4847. try {
  4848. await this.getUrlLib();
  4849. console.log(this.defaultLibUrl);
  4850. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4851. } catch (error) {
  4852. console.error('Не удалось загрузить библиотеку', error)
  4853. }
  4854. }
  4855.  
  4856. async getUrlLib() {
  4857. try {
  4858. const db = new Database('hw_cache', 'cache');
  4859. await db.open();
  4860. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4861. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4862. } catch(e) {}
  4863. }
  4864.  
  4865. getData(id) {
  4866. return this.data[id];
  4867. }
  4868. setData(data) {
  4869. this.data = data;
  4870. }
  4871. }
  4872.  
  4873. this.lib = new Library();
  4874. /**
  4875. * Database
  4876. *
  4877. * База данных
  4878. */
  4879. class Database {
  4880. constructor(dbName, storeName) {
  4881. this.dbName = dbName;
  4882. this.storeName = storeName;
  4883. this.db = null;
  4884. }
  4885.  
  4886. async open() {
  4887. return new Promise((resolve, reject) => {
  4888. const request = indexedDB.open(this.dbName);
  4889.  
  4890. request.onerror = () => {
  4891. reject(new Error(`Failed to open database ${this.dbName}`));
  4892. };
  4893.  
  4894. request.onsuccess = () => {
  4895. this.db = request.result;
  4896. resolve();
  4897. };
  4898.  
  4899. request.onupgradeneeded = (event) => {
  4900. const db = event.target.result;
  4901. if (!db.objectStoreNames.contains(this.storeName)) {
  4902. db.createObjectStore(this.storeName);
  4903. }
  4904. };
  4905. });
  4906. }
  4907.  
  4908. async set(key, value) {
  4909. return new Promise((resolve, reject) => {
  4910. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4911. const store = transaction.objectStore(this.storeName);
  4912. const request = store.put(value, key);
  4913.  
  4914. request.onerror = () => {
  4915. reject(new Error(`Failed to save value with key ${key}`));
  4916. };
  4917.  
  4918. request.onsuccess = () => {
  4919. resolve();
  4920. };
  4921. });
  4922. }
  4923.  
  4924. async get(key, def) {
  4925. return new Promise((resolve, reject) => {
  4926. const transaction = this.db.transaction([this.storeName], 'readonly');
  4927. const store = transaction.objectStore(this.storeName);
  4928. const request = store.get(key);
  4929.  
  4930. request.onerror = () => {
  4931. resolve(def);
  4932. };
  4933.  
  4934. request.onsuccess = () => {
  4935. resolve(request.result);
  4936. };
  4937. });
  4938. }
  4939.  
  4940. async delete(key) {
  4941. return new Promise((resolve, reject) => {
  4942. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4943. const store = transaction.objectStore(this.storeName);
  4944. const request = store.delete(key);
  4945.  
  4946. request.onerror = () => {
  4947. reject(new Error(`Failed to delete value with key ${key}`));
  4948. };
  4949.  
  4950. request.onsuccess = () => {
  4951. resolve();
  4952. };
  4953. });
  4954. }
  4955. }
  4956.  
  4957. /**
  4958. * Returns the stored value
  4959. *
  4960. * Возвращает сохраненное значение
  4961. */
  4962. function getSaveVal(saveName, def) {
  4963. const result = storage.get(saveName, def);
  4964. return result;
  4965. }
  4966.  
  4967. /**
  4968. * Stores value
  4969. *
  4970. * Сохраняет значение
  4971. */
  4972. function setSaveVal(saveName, value) {
  4973. storage.set(saveName, value);
  4974. }
  4975.  
  4976. /**
  4977. * Database initialization
  4978. *
  4979. * Инициализация базы данных
  4980. */
  4981. const db = new Database(GM_info.script.name, 'settings');
  4982.  
  4983. /**
  4984. * Data store
  4985. *
  4986. * Хранилище данных
  4987. */
  4988. const storage = {
  4989. userId: 0,
  4990. /**
  4991. * Default values
  4992. *
  4993. * Значения по умолчанию
  4994. */
  4995. values: [
  4996. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4997. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4998. ...Object.entries(inputs2).map(e => ({ [e[0]]: e[1].default })),
  4999. //...Object.entries(inputs3).map(e => ({ [e[0]]: e[1].default })),
  5000. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  5001. name: GM_info.script.name,
  5002. get: function (key, def) {
  5003. if (key in this.values) {
  5004. return this.values[key];
  5005. }
  5006. return def;
  5007. },
  5008. set: function (key, value) {
  5009. this.values[key] = value;
  5010. db.set(this.userId, this.values).catch(
  5011. e => null
  5012. );
  5013. localStorage[this.name + ':' + key] = value;
  5014. },
  5015. delete: function (key) {
  5016. delete this.values[key];
  5017. db.set(this.userId, this.values);
  5018. delete localStorage[this.name + ':' + key];
  5019. }
  5020. }
  5021.  
  5022. /**
  5023. * Returns all keys from localStorage that start with prefix (for migration)
  5024. *
  5025. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  5026. */
  5027. function getAllValuesStartingWith(prefix) {
  5028. const values = [];
  5029. for (let i = 0; i < localStorage.length; i++) {
  5030. const key = localStorage.key(i);
  5031. if (key.startsWith(prefix)) {
  5032. const val = localStorage.getItem(key);
  5033. const keyValue = key.split(':')[1];
  5034. values.push({ key: keyValue, val });
  5035. }
  5036. }
  5037. return values;
  5038. }
  5039.  
  5040. /**
  5041. * Opens or migrates to a database
  5042. *
  5043. * Открывает или мигрирует в базу данных
  5044. */
  5045. async function openOrMigrateDatabase(userId) {
  5046. storage.userId = userId;
  5047. try {
  5048. await db.open();
  5049. } catch(e) {
  5050. return;
  5051. }
  5052. let settings = await db.get(userId, false);
  5053.  
  5054. if (settings) {
  5055. storage.values = settings;
  5056. return;
  5057. }
  5058.  
  5059. const values = getAllValuesStartingWith(GM_info.script.name);
  5060. for (const value of values) {
  5061. let val = null;
  5062. try {
  5063. val = JSON.parse(value.val);
  5064. } catch {
  5065. break;
  5066. }
  5067. storage.values[value.key] = val;
  5068. }
  5069. await db.set(userId, storage.values);
  5070. }
  5071.  
  5072. class ZingerYWebsiteAPI {
  5073.  
  5074. }
  5075.  
  5076. //тест парсер подарков
  5077. class GiftCodeCollector {
  5078. constructor(filterCodes = []) {
  5079. /** Массив кодов которые возвращать не нужно */
  5080. this.collectedGiftCodes = filterCodes;
  5081. this.codes = [];
  5082. }
  5083.  
  5084. async fetchData() {
  5085. const response = await fetch('https://community-api.hero-wars.com/api/posts/limit/10');
  5086. const data = await response.json();
  5087. return data.data;
  5088. }
  5089.  
  5090. async getGiftCodes() {
  5091. const data = await this.fetchData();
  5092. data.forEach((post) => {
  5093. let code = '';
  5094. post.attributes.body.forEach((body) => {
  5095. if (body.type !== 'paragraph') {
  5096. return;
  5097. }
  5098.  
  5099. const bodyText = body.data.text;
  5100. const giftUrl = this.getGiftUrl(bodyText);
  5101. const urlText = giftUrl || bodyText;
  5102.  
  5103. const findCode = this.getCodeFromText(urlText);
  5104. if (findCode) {
  5105. code = findCode;
  5106. }
  5107. });
  5108. if (!code || this.collectedGiftCodes.includes(code)) {
  5109. return;
  5110. }
  5111. this.codes.push(code);
  5112. });
  5113. return this.codes;
  5114. }
  5115.  
  5116. getGiftUrl(text) {
  5117. const regex = /href=([\"\'])(.*?bit\.ly.*?)\1/;
  5118. const matches = text.match(regex);
  5119. return matches ? matches[2] : null;
  5120. }
  5121.  
  5122. getCodeFromText(text) {
  5123. const regex = /gift_id=(\w{10,32})/;
  5124. const matches = text.match(regex);
  5125. return matches ? matches[1] : null;
  5126. }
  5127. }
  5128.  
  5129. /**
  5130. * Sending expeditions
  5131. *
  5132. * Отправка экспедиций
  5133. */
  5134. function checkExpedition() {
  5135. return new Promise((resolve, reject) => {
  5136. const expedition = new Expedition(resolve, reject);
  5137. expedition.start();
  5138. });
  5139. }
  5140.  
  5141. class Expedition {
  5142. checkExpedInfo = {
  5143. calls: [
  5144. {
  5145. name: 'expeditionGet',
  5146. args: {},
  5147. ident: 'expeditionGet',
  5148. },
  5149. {
  5150. name: 'heroGetAll',
  5151. args: {},
  5152. ident: 'heroGetAll',
  5153. },
  5154. ],
  5155. };
  5156.  
  5157. constructor(resolve, reject) {
  5158. this.resolve = resolve;
  5159. this.reject = reject;
  5160. }
  5161.  
  5162. async start() {
  5163. const data = await Send(JSON.stringify(this.checkExpedInfo));
  5164.  
  5165. const expedInfo = data.results[0].result.response;
  5166. const dataHeroes = data.results[1].result.response;
  5167. const dataExped = { useHeroes: [], exped: [] };
  5168. const calls = [];
  5169.  
  5170. /**
  5171. * Adding expeditions to collect
  5172. * Добавляем экспедиции для сбора
  5173. */
  5174. let countGet = 0;
  5175. for (var n in expedInfo) {
  5176. const exped = expedInfo[n];
  5177. const dateNow = Date.now() / 1000;
  5178. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  5179. countGet++;
  5180. calls.push({
  5181. name: 'expeditionFarm',
  5182. args: { expeditionId: exped.id },
  5183. ident: 'expeditionFarm_' + exped.id,
  5184. });
  5185. } else {
  5186. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  5187. }
  5188. if (exped.status == 1) {
  5189. dataExped.exped.push({ id: exped.id, power: exped.power });
  5190. }
  5191. }
  5192. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  5193.  
  5194. /**
  5195. * Putting together a list of heroes
  5196. * Собираем список героев
  5197. */
  5198. const heroesArr = [];
  5199. for (let n in dataHeroes) {
  5200. const hero = dataHeroes[n];
  5201. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  5202. let heroPower = hero.power;
  5203. // Лара Крофт * 3
  5204. if (hero.id == 63 && hero.color >= 16) {
  5205. heroPower *= 3;
  5206. }
  5207. heroesArr.push({ id: hero.id, power: heroPower });
  5208. }
  5209. }
  5210.  
  5211. /**
  5212. * Adding expeditions to send
  5213. * Добавляем экспедиции для отправки
  5214. */
  5215. let countSend = 0;
  5216. heroesArr.sort((a, b) => a.power - b.power);
  5217. for (const exped of dataExped.exped) {
  5218. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  5219. if (heroesIds && heroesIds.length > 4) {
  5220. for (let q in heroesArr) {
  5221. if (heroesIds.includes(heroesArr[q].id)) {
  5222. delete heroesArr[q];
  5223. }
  5224. }
  5225. countSend++;
  5226. calls.push({
  5227. name: 'expeditionSendHeroes',
  5228. args: {
  5229. expeditionId: exped.id,
  5230. heroes: heroesIds,
  5231. },
  5232. ident: 'expeditionSendHeroes_' + exped.id,
  5233. });
  5234. }
  5235. }
  5236.  
  5237. if (calls.length) {
  5238. await Send({ calls });
  5239. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5240. return;
  5241. }
  5242. this.end(I18N('EXPEDITIONS_NOTHING'));
  5243. }
  5244.  
  5245. /**
  5246. * Selection of heroes for expeditions
  5247. *
  5248. * Подбор героев для экспедиций
  5249. */
  5250. selectionHeroes(heroes, power) {
  5251. const resultHeroers = [];
  5252. const heroesIds = [];
  5253. for (let q = 0; q < 5; q++) {
  5254. for (let i in heroes) {
  5255. let hero = heroes[i];
  5256. if (heroesIds.includes(hero.id)) {
  5257. continue;
  5258. }
  5259.  
  5260. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5261. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5262. if (hero.power > need) {
  5263. resultHeroers.push(hero);
  5264. heroesIds.push(hero.id);
  5265. break;
  5266. }
  5267. }
  5268. }
  5269.  
  5270. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5271. if (summ < power) {
  5272. return false;
  5273. }
  5274. return heroesIds;
  5275. }
  5276.  
  5277. /**
  5278. * Ends expedition script
  5279. *
  5280. * Завершает скрипт экспедиции
  5281. */
  5282. end(msg) {
  5283. setProgress(msg, true);
  5284. this.resolve();
  5285. }
  5286. }
  5287.  
  5288. /**
  5289. * Walkthrough of the dungeon
  5290. *
  5291. * Прохождение подземелья
  5292. */
  5293. function testDungeon() {
  5294. return new Promise((resolve, reject) => {
  5295. const dung = new executeDungeon(resolve, reject);
  5296. const titanit = getInput('countTitanit');
  5297. dung.start(titanit);
  5298. });
  5299. }
  5300.  
  5301. /**
  5302. * Walkthrough of the dungeon
  5303. *
  5304. * Прохождение подземелья
  5305. */
  5306. function executeDungeon(resolve, reject) {
  5307. dungeonActivity = 0;
  5308. maxDungeonActivity = 150;
  5309.  
  5310. titanGetAll = [];
  5311.  
  5312. teams = {
  5313. heroes: [],
  5314. earth: [],
  5315. fire: [],
  5316. neutral: [],
  5317. water: [],
  5318. }
  5319.  
  5320. titanStats = [];
  5321.  
  5322. titansStates = {};
  5323.  
  5324. let talentMsg = '';
  5325. let talentMsgReward = '';
  5326. callsExecuteDungeon = {
  5327. calls: [{
  5328. name: "dungeonGetInfo",
  5329. args: {},
  5330. ident: "dungeonGetInfo"
  5331. }, {
  5332. name: "teamGetAll",
  5333. args: {},
  5334. ident: "teamGetAll"
  5335. }, {
  5336. name: "teamGetFavor",
  5337. args: {},
  5338. ident: "teamGetFavor"
  5339. }, {
  5340. name: "clanGetInfo",
  5341. args: {},
  5342. ident: "clanGetInfo"
  5343. }, {
  5344. name: "titanGetAll",
  5345. args: {},
  5346. ident: "titanGetAll"
  5347. }, {
  5348. name: "inventoryGet",
  5349. args: {},
  5350. ident: "inventoryGet"
  5351. }]
  5352. }
  5353.  
  5354. this.start = function(titanit) {
  5355. maxDungeonActivity = titanit || getInput('countTitanit');
  5356. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5357. }
  5358.  
  5359. /**
  5360. * Getting data on the dungeon
  5361. *
  5362. * Получаем данные по подземелью
  5363. */
  5364. function startDungeon(e) {
  5365. stopDung = false; // стоп подземка
  5366. res = e.results;
  5367. dungeonGetInfo = res[0].result.response;
  5368. if (!dungeonGetInfo) {
  5369. endDungeon('noDungeon', res);
  5370. return;
  5371. }
  5372. teamGetAll = res[1].result.response;
  5373. teamGetFavor = res[2].result.response;
  5374. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5375. titanGetAll = Object.values(res[4].result.response);
  5376. countPredictionCard = res[5].result.response.consumable[81];
  5377.  
  5378. teams.hero = {
  5379. favor: teamGetFavor.dungeon_hero,
  5380. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5381. teamNum: 0,
  5382. }
  5383. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5384. if (heroPet) {
  5385. teams.hero.pet = heroPet;
  5386. }
  5387.  
  5388. teams.neutral = {
  5389. favor: {},
  5390. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5391. teamNum: 0,
  5392. };
  5393. teams.water = {
  5394. favor: {},
  5395. heroes: getTitanTeam(titanGetAll, 'water'),
  5396. teamNum: 0,
  5397. };
  5398. teams.fire = {
  5399. favor: {},
  5400. heroes: getTitanTeam(titanGetAll, 'fire'),
  5401. teamNum: 0,
  5402. };
  5403. teams.earth = {
  5404. favor: {},
  5405. heroes: getTitanTeam(titanGetAll, 'earth'),
  5406. teamNum: 0,
  5407. };
  5408.  
  5409.  
  5410. checkFloor(dungeonGetInfo);
  5411. }
  5412.  
  5413. function getTitanTeam(titans, type) {
  5414. switch (type) {
  5415. case 'neutral':
  5416. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5417. case 'water':
  5418. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5419. case 'fire':
  5420. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5421. case 'earth':
  5422. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5423. }
  5424. }
  5425.  
  5426. function getNeutralTeam() {
  5427. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5428. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5429. }
  5430.  
  5431. function fixTitanTeam(titans) {
  5432. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5433. return titans;
  5434. }
  5435.  
  5436. /**
  5437. * Checking the floor
  5438. *
  5439. * Проверяем этаж
  5440. */
  5441. async function checkFloor(dungeonInfo) {
  5442. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5443. saveProgress();
  5444. return;
  5445. }
  5446. checkTalent(dungeonInfo);
  5447. // console.log(dungeonInfo, dungeonActivity);
  5448. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5449. if (dungeonActivity >= maxDungeonActivity) {
  5450. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5451. return;
  5452. }
  5453. titansStates = dungeonInfo.states.titans;
  5454. titanStats = titanObjToArray(titansStates);
  5455. if (stopDung){
  5456. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  5457. return;
  5458. }
  5459. const floorChoices = dungeonInfo.floor.userData;
  5460. const floorType = dungeonInfo.floorType;
  5461. //const primeElement = dungeonInfo.elements.prime;
  5462. if (floorType == "battle") {
  5463. const calls = [];
  5464. for (let teamNum in floorChoices) {
  5465. attackerType = floorChoices[teamNum].attackerType;
  5466. const args = fixTitanTeam(teams[attackerType]);
  5467. if (attackerType == 'neutral') {
  5468. args.heroes = getNeutralTeam();
  5469. }
  5470. if (!args.heroes.length) {
  5471. continue;
  5472. }
  5473. args.teamNum = teamNum;
  5474. calls.push({
  5475. name: "dungeonStartBattle",
  5476. args,
  5477. ident: "body_" + teamNum
  5478. })
  5479. }
  5480. if (!calls.length) {
  5481. endDungeon('endDungeon', 'All Dead');
  5482. return;
  5483. }
  5484. const battleDatas = await Send(JSON.stringify({ calls }))
  5485. .then(e => e.results.map(n => n.result.response))
  5486. const battleResults = [];
  5487. for (n in battleDatas) {
  5488. battleData = battleDatas[n]
  5489. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5490. battleResults.push(await Calc(battleData).then(result => {
  5491. result.teamNum = n;
  5492. result.attackerType = floorChoices[n].attackerType;
  5493. return result;
  5494. }));
  5495. }
  5496. processingPromises(battleResults)
  5497. }
  5498. }
  5499.  
  5500. async function checkTalent(dungeonInfo) {
  5501. const talent = dungeonInfo.talent;
  5502. if (!talent) {
  5503. return;
  5504. }
  5505. const dungeonFloor = +dungeonInfo.floorNumber;
  5506. const talentFloor = +talent.floorRandValue;
  5507. let doorsAmount = 3 - talent.conditions.doorsAmount;
  5508. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  5509. const reward = await Send({
  5510. calls: [
  5511. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  5512. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  5513. ],
  5514. }).then((e) => e.results[0].result.response);
  5515. const type = Object.keys(reward).pop();
  5516. const itemId = Object.keys(reward[type]).pop();
  5517. const count = reward[type][itemId];
  5518. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  5519. talentMsgReward += `<br> ${count} ${itemName}`;
  5520. doorsAmount++;
  5521. }
  5522. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  5523. }
  5524. function processingPromises(results) {
  5525. let selectBattle = results[0];
  5526. if (results.length < 2) {
  5527. // console.log(selectBattle);
  5528. if (!selectBattle.result.win) {
  5529. endDungeon('dungeonEndBattle\n', selectBattle);
  5530. return;
  5531. }
  5532. endBattle(selectBattle);
  5533. return;
  5534. }
  5535.  
  5536. selectBattle = false;
  5537. let bestState = -1000;
  5538. for (const result of results) {
  5539. const recovery = getState(result);
  5540. if (recovery > bestState) {
  5541. bestState = recovery;
  5542. selectBattle = result
  5543. }
  5544. }
  5545. // console.log(selectBattle.teamNum, results);
  5546. if (!selectBattle || bestState <= -1000) {
  5547. endDungeon('dungeonEndBattle\n', results);
  5548. return;
  5549. }
  5550.  
  5551. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5552. .then(endBattle);
  5553. }
  5554.  
  5555. /**
  5556. * Let's start the fight
  5557. *
  5558. * Начинаем бой
  5559. */
  5560. function startBattle(teamNum, attackerType) {
  5561. return new Promise(function (resolve, reject) {
  5562. args = fixTitanTeam(teams[attackerType]);
  5563. args.teamNum = teamNum;
  5564. if (attackerType == 'neutral') {
  5565. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5566. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5567. }
  5568. startBattleCall = {
  5569. calls: [{
  5570. name: "dungeonStartBattle",
  5571. args,
  5572. ident: "body"
  5573. }]
  5574. }
  5575. send(JSON.stringify(startBattleCall), resultBattle, {
  5576. resolve,
  5577. teamNum,
  5578. attackerType
  5579. });
  5580. });
  5581. }
  5582. /**
  5583. * Returns the result of the battle in a promise
  5584. *
  5585. * Возращает резульат боя в промис
  5586. */
  5587. function resultBattle(resultBattles, args) {
  5588. battleData = resultBattles.results[0].result.response;
  5589. battleType = "get_tower";
  5590. if (battleData.type == "dungeon_titan") {
  5591. battleType = "get_titan";
  5592. }
  5593. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5594. BattleCalc(battleData, battleType, function (result) {
  5595. result.teamNum = args.teamNum;
  5596. result.attackerType = args.attackerType;
  5597. args.resolve(result);
  5598. });
  5599. }
  5600. /**
  5601. * Finishing the fight
  5602. *
  5603. * Заканчиваем бой
  5604. */
  5605. async function endBattle(battleInfo) {
  5606. if (battleInfo.result.win) {
  5607. const args = {
  5608. result: battleInfo.result,
  5609. progress: battleInfo.progress,
  5610. }
  5611. if (countPredictionCard > 0) {
  5612. args.isRaid = true;
  5613. } else {
  5614. const timer = getTimer(battleInfo.battleTime);
  5615. console.log(timer);
  5616. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  5617. }
  5618. const calls = [{
  5619. name: "dungeonEndBattle",
  5620. args,
  5621. ident: "body"
  5622. }];
  5623. lastDungeonBattleData = null;
  5624. send(JSON.stringify({ calls }), resultEndBattle);
  5625. } else {
  5626. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5627. }
  5628. }
  5629.  
  5630. /**
  5631. * Getting and processing battle results
  5632. *
  5633. * Получаем и обрабатываем результаты боя
  5634. */
  5635. function resultEndBattle(e) {
  5636. if ('error' in e) {
  5637. popup.confirm(I18N('ERROR_MSG', {
  5638. name: e.error.name,
  5639. description: e.error.description,
  5640. }));
  5641. endDungeon('errorRequest', e);
  5642. return;
  5643. }
  5644. battleResult = e.results[0].result.response;
  5645. if ('error' in battleResult) {
  5646. endDungeon('errorBattleResult', battleResult);
  5647. return;
  5648. }
  5649. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5650. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5651. checkFloor(dungeonGetInfo);
  5652. }
  5653.  
  5654. /**
  5655. * Returns the coefficient of condition of the
  5656. * difference in titanium before and after the battle
  5657. *
  5658. * Возвращает коэффициент состояния титанов после боя
  5659. */
  5660. function getState(result) {
  5661. if (!result.result.win) {
  5662. return -1000;
  5663. }
  5664.  
  5665. let beforeSumFactor = 0;
  5666. const beforeTitans = result.battleData.attackers;
  5667. for (let titanId in beforeTitans) {
  5668. const titan = beforeTitans[titanId];
  5669. const state = titan.state;
  5670. let factor = 1;
  5671. if (state) {
  5672. const hp = state.hp / titan.hp;
  5673. const energy = state.energy / 1e3;
  5674. factor = hp + energy / 20
  5675. }
  5676. beforeSumFactor += factor;
  5677. }
  5678.  
  5679. let afterSumFactor = 0;
  5680. const afterTitans = result.progress[0].attackers.heroes;
  5681. for (let titanId in afterTitans) {
  5682. const titan = afterTitans[titanId];
  5683. const hp = titan.hp / beforeTitans[titanId].hp;
  5684. const energy = titan.energy / 1e3;
  5685. const factor = hp + energy / 20;
  5686. afterSumFactor += factor;
  5687. }
  5688. return afterSumFactor - beforeSumFactor;
  5689. }
  5690.  
  5691. /**
  5692. * Converts an object with IDs to an array with IDs
  5693. *
  5694. * Преобразует объект с идетификаторами в массив с идетификаторами
  5695. */
  5696. function titanObjToArray(obj) {
  5697. let titans = [];
  5698. for (let id in obj) {
  5699. obj[id].id = id;
  5700. titans.push(obj[id]);
  5701. }
  5702. return titans;
  5703. }
  5704.  
  5705. function saveProgress() {
  5706. let saveProgressCall = {
  5707. calls: [{
  5708. name: "dungeonSaveProgress",
  5709. args: {},
  5710. ident: "body"
  5711. }]
  5712. }
  5713. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5714. }
  5715.  
  5716. function endDungeon(reason, info) {
  5717. console.warn(reason, info);
  5718. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5719. resolve();
  5720. }
  5721. }
  5722.  
  5723. /**
  5724. * Passing the tower
  5725. *
  5726. * Прохождение башни
  5727. */
  5728. function testTower() {
  5729. return new Promise((resolve, reject) => {
  5730. tower = new executeTower(resolve, reject);
  5731. tower.start();
  5732. });
  5733. }
  5734.  
  5735. /**
  5736. * Passing the tower
  5737. *
  5738. * Прохождение башни
  5739. */
  5740. function executeTower(resolve, reject) {
  5741. lastTowerInfo = {};
  5742.  
  5743. scullCoin = 0;
  5744.  
  5745. heroGetAll = [];
  5746.  
  5747. heroesStates = {};
  5748.  
  5749. argsBattle = {
  5750. heroes: [],
  5751. favor: {},
  5752. };
  5753.  
  5754. callsExecuteTower = {
  5755. calls: [{
  5756. name: "towerGetInfo",
  5757. args: {},
  5758. ident: "towerGetInfo"
  5759. }, {
  5760. name: "teamGetAll",
  5761. args: {},
  5762. ident: "teamGetAll"
  5763. }, {
  5764. name: "teamGetFavor",
  5765. args: {},
  5766. ident: "teamGetFavor"
  5767. }, {
  5768. name: "inventoryGet",
  5769. args: {},
  5770. ident: "inventoryGet"
  5771. }, {
  5772. name: "heroGetAll",
  5773. args: {},
  5774. ident: "heroGetAll"
  5775. }]
  5776. }
  5777.  
  5778. buffIds = [
  5779. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5780. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5781. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5782. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5783. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5784. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5785. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5786. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5787. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5788. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5789. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5790. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5791. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5792. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5793. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5794. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5795. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5796. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5797. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5798. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5799. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5800. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5801. ]
  5802.  
  5803. this.start = function () {
  5804. send(JSON.stringify(callsExecuteTower), startTower);
  5805. }
  5806.  
  5807. /**
  5808. * Getting data on the Tower
  5809. *
  5810. * Получаем данные по башне
  5811. */
  5812. function startTower(e) {
  5813. res = e.results;
  5814. towerGetInfo = res[0].result.response;
  5815. if (!towerGetInfo) {
  5816. endTower('noTower', res);
  5817. return;
  5818. }
  5819. teamGetAll = res[1].result.response;
  5820. teamGetFavor = res[2].result.response;
  5821. inventoryGet = res[3].result.response;
  5822. heroGetAll = Object.values(res[4].result.response);
  5823.  
  5824. scullCoin = inventoryGet.coin[7] ?? 0;
  5825.  
  5826. argsBattle.favor = teamGetFavor.tower;
  5827. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5828. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5829. if (pet) {
  5830. argsBattle.pet = pet;
  5831. }
  5832.  
  5833. checkFloor(towerGetInfo);
  5834. }
  5835.  
  5836. function fixHeroesTeam(argsBattle) {
  5837. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5838. if (fixHeroes.length < 5) {
  5839. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5840. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5841. Object.keys(argsBattle.favor).forEach(e => {
  5842. if (!fixHeroes.includes(+e)) {
  5843. delete argsBattle.favor[e];
  5844. }
  5845. })
  5846. }
  5847. argsBattle.heroes = fixHeroes;
  5848. return argsBattle;
  5849. }
  5850.  
  5851. /**
  5852. * Check the floor
  5853. *
  5854. * Проверяем этаж
  5855. */
  5856. function checkFloor(towerInfo) {
  5857. lastTowerInfo = towerInfo;
  5858. maySkipFloor = +towerInfo.maySkipFloor;
  5859. floorNumber = +towerInfo.floorNumber;
  5860. heroesStates = towerInfo.states.heroes;
  5861. floorInfo = towerInfo.floor;
  5862.  
  5863. /**
  5864. * Is there at least one chest open on the floor
  5865. * Открыт ли на этаже хоть один сундук
  5866. */
  5867. isOpenChest = false;
  5868. if (towerInfo.floorType == "chest") {
  5869. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5870. }
  5871.  
  5872. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5873. if (floorNumber > 49) {
  5874. if (isOpenChest) {
  5875. endTower('alreadyOpenChest 50 floor', floorNumber);
  5876. return;
  5877. }
  5878. }
  5879. /**
  5880. * If the chest is open and you can skip floors, then move on
  5881. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5882. */
  5883. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5884. if (floorNumber == 1) {
  5885. fullSkipTower();
  5886. return;
  5887. }
  5888. if (isOpenChest) {
  5889. nextOpenChest(floorNumber);
  5890. } else {
  5891. nextChestOpen(floorNumber);
  5892. }
  5893. return;
  5894. }
  5895.  
  5896. // console.log(towerInfo, scullCoin);
  5897. switch (towerInfo.floorType) {
  5898. case "battle":
  5899. if (floorNumber <= maySkipFloor) {
  5900. skipFloor();
  5901. return;
  5902. }
  5903. if (floorInfo.state == 2) {
  5904. nextFloor();
  5905. return;
  5906. }
  5907. startBattle().then(endBattle);
  5908. return;
  5909. case "buff":
  5910. checkBuff(towerInfo);
  5911. return;
  5912. case "chest":
  5913. openChest(floorNumber);
  5914. return;
  5915. default:
  5916. console.log('!', towerInfo.floorType, towerInfo);
  5917. break;
  5918. }
  5919. }
  5920.  
  5921. /**
  5922. * Let's start the fight
  5923. *
  5924. * Начинаем бой
  5925. */
  5926. function startBattle() {
  5927. return new Promise(function (resolve, reject) {
  5928. towerStartBattle = {
  5929. calls: [{
  5930. name: "towerStartBattle",
  5931. args: fixHeroesTeam(argsBattle),
  5932. ident: "body"
  5933. }]
  5934. }
  5935. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5936. });
  5937. }
  5938. /**
  5939. * Returns the result of the battle in a promise
  5940. *
  5941. * Возращает резульат боя в промис
  5942. */
  5943. function resultBattle(resultBattles, resolve) {
  5944. battleData = resultBattles.results[0].result.response;
  5945. battleType = "get_tower";
  5946. BattleCalc(battleData, battleType, function (result) {
  5947. resolve(result);
  5948. });
  5949. }
  5950. /**
  5951. * Finishing the fight
  5952. *
  5953. * Заканчиваем бой
  5954. */
  5955. function endBattle(battleInfo) {
  5956. if (battleInfo.result.stars >= 3) {
  5957. endBattleCall = {
  5958. calls: [{
  5959. name: "towerEndBattle",
  5960. args: {
  5961. result: battleInfo.result,
  5962. progress: battleInfo.progress,
  5963. },
  5964. ident: "body"
  5965. }]
  5966. }
  5967. send(JSON.stringify(endBattleCall), resultEndBattle);
  5968. } else {
  5969. endTower('towerEndBattle win: false\n', battleInfo);
  5970. }
  5971. }
  5972.  
  5973. /**
  5974. * Getting and processing battle results
  5975. *
  5976. * Получаем и обрабатываем результаты боя
  5977. */
  5978. function resultEndBattle(e) {
  5979. battleResult = e.results[0].result.response;
  5980. if ('error' in battleResult) {
  5981. endTower('errorBattleResult', battleResult);
  5982. return;
  5983. }
  5984. if ('reward' in battleResult) {
  5985. scullCoin += battleResult.reward?.coin[7] ?? 0;
  5986. }
  5987. nextFloor();
  5988. }
  5989.  
  5990. function nextFloor() {
  5991. nextFloorCall = {
  5992. calls: [{
  5993. name: "towerNextFloor",
  5994. args: {},
  5995. ident: "body"
  5996. }]
  5997. }
  5998. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5999. }
  6000.  
  6001. function openChest(floorNumber) {
  6002. floorNumber = floorNumber || 0;
  6003. openChestCall = {
  6004. calls: [{
  6005. name: "towerOpenChest",
  6006. args: {
  6007. num: 2
  6008. },
  6009. ident: "body"
  6010. }]
  6011. }
  6012. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  6013. }
  6014.  
  6015. function lastChest() {
  6016. endTower('openChest 50 floor', floorNumber);
  6017. }
  6018.  
  6019. function skipFloor() {
  6020. skipFloorCall = {
  6021. calls: [{
  6022. name: "towerSkipFloor",
  6023. args: {},
  6024. ident: "body"
  6025. }]
  6026. }
  6027. send(JSON.stringify(skipFloorCall), checkDataFloor);
  6028. }
  6029.  
  6030. function checkBuff(towerInfo) {
  6031. buffArr = towerInfo.floor;
  6032. promises = [];
  6033. for (let buff of buffArr) {
  6034. buffInfo = buffIds[buff.id];
  6035. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  6036. scullCoin -= buffInfo.cost;
  6037. promises.push(buyBuff(buff.id));
  6038. }
  6039. }
  6040. Promise.all(promises).then(nextFloor);
  6041. }
  6042.  
  6043. function buyBuff(buffId) {
  6044. return new Promise(function (resolve, reject) {
  6045. buyBuffCall = {
  6046. calls: [{
  6047. name: "towerBuyBuff",
  6048. args: {
  6049. buffId
  6050. },
  6051. ident: "body"
  6052. }]
  6053. }
  6054. send(JSON.stringify(buyBuffCall), resolve);
  6055. });
  6056. }
  6057.  
  6058. function checkDataFloor(result) {
  6059. towerInfo = result.results[0].result.response;
  6060. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  6061. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  6062. }
  6063. if ('tower' in towerInfo) {
  6064. towerInfo = towerInfo.tower;
  6065. }
  6066. if ('skullReward' in towerInfo) {
  6067. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6068. }
  6069. checkFloor(towerInfo);
  6070. }
  6071. /**
  6072. * Getting tower rewards
  6073. *
  6074. * Получаем награды башни
  6075. */
  6076. function farmTowerRewards(reason) {
  6077. let { pointRewards, points } = lastTowerInfo;
  6078. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  6079. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  6080. if (!farmPoints.length) {
  6081. return;
  6082. }
  6083. let farmTowerRewardsCall = {
  6084. calls: [{
  6085. name: "tower_farmPointRewards",
  6086. args: {
  6087. points: farmPoints
  6088. },
  6089. ident: "tower_farmPointRewards"
  6090. }]
  6091. }
  6092.  
  6093. if (scullCoin > 0) {
  6094. farmTowerRewardsCall.calls.push({
  6095. name: "tower_farmSkullReward",
  6096. args: {},
  6097. ident: "tower_farmSkullReward"
  6098. });
  6099. }
  6100.  
  6101. send(JSON.stringify(farmTowerRewardsCall), () => { });
  6102. }
  6103.  
  6104. function fullSkipTower() {
  6105. /**
  6106. * Next chest
  6107. *
  6108. * Следующий сундук
  6109. */
  6110. function nextChest(n) {
  6111. return {
  6112. name: "towerNextChest",
  6113. args: {},
  6114. ident: "group_" + n + "_body"
  6115. }
  6116. }
  6117. /**
  6118. * Open chest
  6119. *
  6120. * Открыть сундук
  6121. */
  6122. function openChest(n) {
  6123. return {
  6124. name: "towerOpenChest",
  6125. args: {
  6126. "num": 2
  6127. },
  6128. ident: "group_" + n + "_body"
  6129. }
  6130. }
  6131.  
  6132. const fullSkipTowerCall = {
  6133. calls: []
  6134. }
  6135.  
  6136. let n = 0;
  6137. for (let i = 0; i < 15; i++) {
  6138. // 15 сундуков
  6139. fullSkipTowerCall.calls.push(nextChest(++n));
  6140. fullSkipTowerCall.calls.push(openChest(++n));
  6141. // +5 сундуков, 250 изюма // towerOpenChest
  6142. // if (i < 5) {
  6143. // fullSkipTowerCall.calls.push(openChest(++n, 2));
  6144. // }
  6145. }
  6146. fullSkipTowerCall.calls.push({
  6147. name: 'towerGetInfo',
  6148. args: {},
  6149. ident: 'group_' + ++n + '_body',
  6150. });
  6151. send(JSON.stringify(fullSkipTowerCall), data => {
  6152. for (const r of data.results) {
  6153. const towerInfo = r?.result?.response;
  6154. if (towerInfo && 'skullReward' in towerInfo) {
  6155. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  6156. }
  6157. }
  6158. data.results[0] = data.results[data.results.length - 1];
  6159. checkDataFloor(data);
  6160. });
  6161. }
  6162.  
  6163. function nextChestOpen(floorNumber) {
  6164. const calls = [{
  6165. name: "towerOpenChest",
  6166. args: {
  6167. num: 2
  6168. },
  6169. ident: "towerOpenChest"
  6170. }];
  6171.  
  6172. Send(JSON.stringify({ calls })).then(e => {
  6173. nextOpenChest(floorNumber);
  6174. });
  6175. }
  6176.  
  6177. function nextOpenChest(floorNumber) {
  6178. if (floorNumber > 49) {
  6179. endTower('openChest 50 floor', floorNumber);
  6180. return;
  6181. }
  6182. let nextOpenChestCall = {
  6183. calls: [{
  6184. name: "towerNextChest",
  6185. args: {},
  6186. ident: "towerNextChest"
  6187. }, {
  6188. name: "towerOpenChest",
  6189. args: {
  6190. num: 2
  6191. },
  6192. ident: "towerOpenChest"
  6193. }]
  6194. }
  6195. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  6196. }
  6197.  
  6198. function endTower(reason, info) {
  6199. console.log(reason, info);
  6200. if (reason != 'noTower') {
  6201. farmTowerRewards(reason);
  6202. }
  6203. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  6204. resolve();
  6205. }
  6206. }
  6207.  
  6208. /**
  6209. * Passage of the arena of the titans
  6210. *
  6211. * Прохождение арены титанов
  6212. */
  6213. function testTitanArena() {
  6214. return new Promise((resolve, reject) => {
  6215. titAren = new executeTitanArena(resolve, reject);
  6216. titAren.start();
  6217. });
  6218. }
  6219.  
  6220. /**
  6221. * Passage of the arena of the titans
  6222. *
  6223. * Прохождение арены титанов
  6224. */
  6225. function executeTitanArena(resolve, reject) {
  6226. let titan_arena = [];
  6227. let finishListBattle = [];
  6228. /**
  6229. * ID of the current batch
  6230. *
  6231. * Идетификатор текущей пачки
  6232. */
  6233. let currentRival = 0;
  6234. /**
  6235. * Number of attempts to finish off the pack
  6236. *
  6237. * Количество попыток добития пачки
  6238. */
  6239. let attempts = 0;
  6240. /**
  6241. * Was there an attempt to finish off the current shooting range
  6242. *
  6243. * Была ли попытка добития текущего тира
  6244. */
  6245. let isCheckCurrentTier = false;
  6246. /**
  6247. * Current shooting range
  6248. *
  6249. * Текущий тир
  6250. */
  6251. let currTier = 0;
  6252. /**
  6253. * Number of battles on the current dash
  6254. *
  6255. * Количество битв на текущем тире
  6256. */
  6257. let countRivalsTier = 0;
  6258.  
  6259. let callsStart = {
  6260. calls: [{
  6261. name: "titanArenaGetStatus",
  6262. args: {},
  6263. ident: "titanArenaGetStatus"
  6264. }, {
  6265. name: "teamGetAll",
  6266. args: {},
  6267. ident: "teamGetAll"
  6268. }]
  6269. }
  6270.  
  6271. this.start = function () {
  6272. send(JSON.stringify(callsStart), startTitanArena);
  6273. }
  6274.  
  6275. function startTitanArena(data) {
  6276. let titanArena = data.results[0].result.response;
  6277. if (titanArena.status == 'disabled') {
  6278. endTitanArena('disabled', titanArena);
  6279. return;
  6280. }
  6281.  
  6282. let teamGetAll = data.results[1].result.response;
  6283. titan_arena = teamGetAll.titan_arena;
  6284.  
  6285. checkTier(titanArena)
  6286. }
  6287.  
  6288. function checkTier(titanArena) {
  6289. if (titanArena.status == "peace_time") {
  6290. endTitanArena('Peace_time', titanArena);
  6291. return;
  6292. }
  6293. currTier = titanArena.tier;
  6294. if (currTier) {
  6295. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6296. }
  6297.  
  6298. if (titanArena.status == "completed_tier") {
  6299. titanArenaCompleteTier();
  6300. return;
  6301. }
  6302. /**
  6303. * Checking for the possibility of a raid
  6304. * Проверка на возможность рейда
  6305. */
  6306. if (titanArena.canRaid) {
  6307. titanArenaStartRaid();
  6308. return;
  6309. }
  6310. /**
  6311. * Check was an attempt to achieve the current shooting range
  6312. * Проверка была ли попытка добития текущего тира
  6313. */
  6314. if (!isCheckCurrentTier) {
  6315. checkRivals(titanArena.rivals);
  6316. return;
  6317. }
  6318.  
  6319. endTitanArena('Done or not canRaid', titanArena);
  6320. }
  6321. /**
  6322. * Submit dash information for verification
  6323. *
  6324. * Отправка информации о тире на проверку
  6325. */
  6326. function checkResultInfo(data) {
  6327. let titanArena = data.results[0].result.response;
  6328. checkTier(titanArena);
  6329. }
  6330. /**
  6331. * Finish the current tier
  6332. *
  6333. * Завершить текущий тир
  6334. */
  6335. function titanArenaCompleteTier() {
  6336. isCheckCurrentTier = false;
  6337. let calls = [{
  6338. name: "titanArenaCompleteTier",
  6339. args: {},
  6340. ident: "body"
  6341. }];
  6342. send(JSON.stringify({calls}), checkResultInfo);
  6343. }
  6344. /**
  6345. * Gathering points to be completed
  6346. *
  6347. * Собираем точки которые нужно добить
  6348. */
  6349. function checkRivals(rivals) {
  6350. finishListBattle = [];
  6351. for (let n in rivals) {
  6352. if (rivals[n].attackScore < 250) {
  6353. finishListBattle.push(n);
  6354. }
  6355. }
  6356. console.log('checkRivals', finishListBattle);
  6357. countRivalsTier = finishListBattle.length;
  6358. roundRivals();
  6359. }
  6360. /**
  6361. * Selecting the next point to finish off
  6362. *
  6363. * Выбор следующей точки для добития
  6364. */
  6365. function roundRivals() {
  6366. let countRivals = finishListBattle.length;
  6367. if (!countRivals) {
  6368. /**
  6369. * Whole range checked
  6370. *
  6371. * Весь тир проверен
  6372. */
  6373. isCheckCurrentTier = true;
  6374. titanArenaGetStatus();
  6375. return;
  6376. }
  6377. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6378. currentRival = finishListBattle.pop();
  6379. attempts = +currentRival;
  6380. // console.log('roundRivals', currentRival);
  6381. titanArenaStartBattle(currentRival);
  6382. }
  6383. /**
  6384. * The start of a solo battle
  6385. *
  6386. * Начало одиночной битвы
  6387. */
  6388. function titanArenaStartBattle(rivalId) {
  6389. let calls = [{
  6390. name: "titanArenaStartBattle",
  6391. args: {
  6392. rivalId: rivalId,
  6393. titans: titan_arena
  6394. },
  6395. ident: "body"
  6396. }];
  6397. send(JSON.stringify({calls}), calcResult);
  6398. }
  6399. /**
  6400. * Calculation of the results of the battle
  6401. *
  6402. * Расчет результатов боя
  6403. */
  6404. function calcResult(data) {
  6405. let battlesInfo = data.results[0].result.response.battle;
  6406. /**
  6407. * If attempts are equal to the current battle number we make
  6408. * Если попытки равны номеру текущего боя делаем прерасчет
  6409. */
  6410. if (attempts == currentRival) {
  6411. preCalcBattle(battlesInfo);
  6412. return;
  6413. }
  6414. /**
  6415. * If there are still attempts, we calculate a new battle
  6416. * Если попытки еще есть делаем расчет нового боя
  6417. */
  6418. if (attempts > 0) {
  6419. attempts--;
  6420. calcBattleResult(battlesInfo)
  6421. .then(resultCalcBattle);
  6422. return;
  6423. }
  6424. /**
  6425. * Otherwise, go to the next opponent
  6426. * Иначе переходим к следующему сопернику
  6427. */
  6428. roundRivals();
  6429. }
  6430. /**
  6431. * Processing the results of the battle calculation
  6432. *
  6433. * Обработка результатов расчета битвы
  6434. */
  6435. function resultCalcBattle(resultBattle) {
  6436. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6437. /**
  6438. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6439. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6440. */
  6441. if (resultBattle.result.win || !attempts) {
  6442. titanArenaEndBattle({
  6443. progress: resultBattle.progress,
  6444. result: resultBattle.result,
  6445. rivalId: resultBattle.battleData.typeId
  6446. });
  6447. return;
  6448. }
  6449. /**
  6450. * If not victory and there are attempts we start a new battle
  6451. * Если не победа и есть попытки начинаем новый бой
  6452. */
  6453. titanArenaStartBattle(resultBattle.battleData.typeId);
  6454. }
  6455. /**
  6456. * Returns the promise of calculating the results of the battle
  6457. *
  6458. * Возращает промис расчета результатов битвы
  6459. */
  6460. function getBattleInfo(battle, isRandSeed) {
  6461. return new Promise(function (resolve) {
  6462. if (isRandSeed) {
  6463. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6464. }
  6465. // console.log(battle.seed);
  6466. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6467. });
  6468. }
  6469. /**
  6470. * Recalculate battles
  6471. *
  6472. * Прерасчтет битвы
  6473. */
  6474. function preCalcBattle(battle) {
  6475. let actions = [getBattleInfo(battle, false)];
  6476. const countTestBattle = getInput('countTestBattle');
  6477. for (let i = 0; i < countTestBattle; i++) {
  6478. actions.push(getBattleInfo(battle, true));
  6479. }
  6480. Promise.all(actions)
  6481. .then(resultPreCalcBattle);
  6482. }
  6483. /**
  6484. * Processing the results of the battle recalculation
  6485. *
  6486. * Обработка результатов прерасчета битвы
  6487. */
  6488. function resultPreCalcBattle(e) {
  6489. let wins = e.map(n => n.result.win);
  6490. let firstBattle = e.shift();
  6491. let countWin = wins.reduce((w, s) => w + s);
  6492. const countTestBattle = getInput('countTestBattle');
  6493. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6494. if (countWin > 0) {
  6495. attempts = getInput('countAutoBattle');
  6496. } else {
  6497. attempts = 0;
  6498. }
  6499. resultCalcBattle(firstBattle);
  6500. }
  6501.  
  6502. /**
  6503. * Complete an arena battle
  6504. *
  6505. * Завершить битву на арене
  6506. */
  6507. function titanArenaEndBattle(args) {
  6508. let calls = [{
  6509. name: "titanArenaEndBattle",
  6510. args,
  6511. ident: "body"
  6512. }];
  6513. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6514. }
  6515.  
  6516. function resultTitanArenaEndBattle(e) {
  6517. let attackScore = e.results[0].result.response.attackScore;
  6518. let numReval = countRivalsTier - finishListBattle.length;
  6519. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6520. /**
  6521. * TODO: Might need to improve the results.
  6522. * TODO: Возможно стоит сделать улучшение результатов
  6523. */
  6524. // console.log('resultTitanArenaEndBattle', e)
  6525. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6526. roundRivals();
  6527. }
  6528. /**
  6529. * Arena State
  6530. *
  6531. * Состояние арены
  6532. */
  6533. function titanArenaGetStatus() {
  6534. let calls = [{
  6535. name: "titanArenaGetStatus",
  6536. args: {},
  6537. ident: "body"
  6538. }];
  6539. send(JSON.stringify({calls}), checkResultInfo);
  6540. }
  6541. /**
  6542. * Arena Raid Request
  6543. *
  6544. * Запрос рейда арены
  6545. */
  6546. function titanArenaStartRaid() {
  6547. let calls = [{
  6548. name: "titanArenaStartRaid",
  6549. args: {
  6550. titans: titan_arena
  6551. },
  6552. ident: "body"
  6553. }];
  6554. send(JSON.stringify({calls}), calcResults);
  6555. }
  6556.  
  6557. function calcResults(data) {
  6558. let battlesInfo = data.results[0].result.response;
  6559. let {attackers, rivals} = battlesInfo;
  6560.  
  6561. let promises = [];
  6562. for (let n in rivals) {
  6563. rival = rivals[n];
  6564. promises.push(calcBattleResult({
  6565. attackers: attackers,
  6566. defenders: [rival.team],
  6567. seed: rival.seed,
  6568. typeId: n,
  6569. }));
  6570. }
  6571.  
  6572. Promise.all(promises)
  6573. .then(results => {
  6574. const endResults = {};
  6575. for (let info of results) {
  6576. let id = info.battleData.typeId;
  6577. endResults[id] = {
  6578. progress: info.progress,
  6579. result: info.result,
  6580. }
  6581. }
  6582. titanArenaEndRaid(endResults);
  6583. });
  6584. }
  6585.  
  6586. function calcBattleResult(battleData) {
  6587. return new Promise(function (resolve, reject) {
  6588. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6589. });
  6590. }
  6591.  
  6592. /**
  6593. * Sending Raid Results
  6594. *
  6595. * Отправка результатов рейда
  6596. */
  6597. function titanArenaEndRaid(results) {
  6598. titanArenaEndRaidCall = {
  6599. calls: [{
  6600. name: "titanArenaEndRaid",
  6601. args: {
  6602. results
  6603. },
  6604. ident: "body"
  6605. }]
  6606. }
  6607. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6608. }
  6609.  
  6610. function checkRaidResults(data) {
  6611. results = data.results[0].result.response.results;
  6612. isSucsesRaid = true;
  6613. for (let i in results) {
  6614. isSucsesRaid &&= (results[i].attackScore >= 250);
  6615. }
  6616.  
  6617. if (isSucsesRaid) {
  6618. titanArenaCompleteTier();
  6619. } else {
  6620. titanArenaGetStatus();
  6621. }
  6622. }
  6623.  
  6624. function titanArenaFarmDailyReward() {
  6625. titanArenaFarmDailyRewardCall = {
  6626. calls: [{
  6627. name: "titanArenaFarmDailyReward",
  6628. args: {},
  6629. ident: "body"
  6630. }]
  6631. }
  6632. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6633. }
  6634.  
  6635. function endTitanArena(reason, info) {
  6636. if (!['Peace_time', 'disabled'].includes(reason)) {
  6637. titanArenaFarmDailyReward();
  6638. }
  6639. console.log(reason, info);
  6640. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6641. resolve();
  6642. }
  6643. }
  6644.  
  6645. function hackGame() {
  6646. const self = this;
  6647. selfGame = null;
  6648. bindId = 1e9;
  6649. this.libGame = null;
  6650. this.doneLibLoad = () => {}
  6651.  
  6652. /**
  6653. * List of correspondence of used classes to their names
  6654. *
  6655. * Список соответствия используемых классов их названиям
  6656. */
  6657. ObjectsList = [
  6658. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6659. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6660. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6661. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6662. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6663. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6664. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6665. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6666. { name: 'GameModel', prop: 'game.model.GameModel' },
  6667. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6668. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6669. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6670. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6671. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6672. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6673. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6674. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6675. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6676. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6677. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6678. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6679. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6680. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6681. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6682. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6683. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6684. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6685. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6686. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6687. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6688. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6689. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6690. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6691. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6692. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6693. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6694. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6695. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6696. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6697. { name: 'SendReplayPopUp', prop: 'game.mediator.gui.popup.chat.sendreplay.SendReplayPopUp' }, //полное окно реплей на вг
  6698. ];
  6699.  
  6700. /**
  6701. * Contains the game classes needed to write and override game methods
  6702. *
  6703. * Содержит классы игры необходимые для написания и подмены методов игры
  6704. */
  6705. Game = {
  6706. /**
  6707. * Function 'e'
  6708. * Функция 'e'
  6709. */
  6710. bindFunc: function (a, b) {
  6711. if (null == b)
  6712. return null;
  6713. null == b.__id__ && (b.__id__ = bindId++);
  6714. var c;
  6715. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6716. c = a.hx__closures__[b.__id__];
  6717. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6718. return c
  6719. },
  6720. };
  6721.  
  6722. /**
  6723. * Connects to game objects via the object creation event
  6724. *
  6725. * Подключается к объектам игры через событие создания объекта
  6726. */
  6727. function connectGame() {
  6728. for (let obj of ObjectsList) {
  6729. /**
  6730. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6731. */
  6732. Object.defineProperty(Object.prototype, obj.prop, {
  6733. set: function (value) {
  6734. if (!selfGame) {
  6735. selfGame = this;
  6736. }
  6737. if (!Game[obj.name]) {
  6738. Game[obj.name] = value;
  6739. }
  6740. // console.log('set ' + obj.prop, this, value);
  6741. this[obj.prop + '_'] = value;
  6742. },
  6743. get: function () {
  6744. // console.log('get ' + obj.prop, this);
  6745. return this[obj.prop + '_'];
  6746. }
  6747. });
  6748. }
  6749. }
  6750.  
  6751. /**
  6752. * Game.BattlePresets
  6753. * @param {bool} a isReplay
  6754. * @param {bool} b autoToggleable
  6755. * @param {bool} c auto On Start
  6756. * @param {object} d config
  6757. * @param {bool} f showBothTeams
  6758. */
  6759. /**
  6760. * Returns the results of the battle to the callback function
  6761. * Возвращает в функцию callback результаты боя
  6762. * @param {*} battleData battle data данные боя
  6763. * @param {*} battleConfig combat configuration type options:
  6764. *
  6765. * тип конфигурации боя варианты:
  6766. *
  6767. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6768. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6769. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6770. *
  6771. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6772. *
  6773. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6774. * @param {*} callback функция в которую вернуться результаты боя
  6775. */
  6776. this.BattleCalc = function (battleData, battleConfig, callback) {
  6777. // battleConfig = battleConfig || getBattleType(battleData.type)
  6778. if (!Game.BattlePresets) throw Error('Use connectGame');
  6779. battlePresets = new Game.BattlePresets(battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6780. let battleInstantPlay;
  6781. if (battleData.progress?.length > 1) {
  6782. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6783. } else {
  6784. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6785. }
  6786. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6787. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6788. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6789. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6790. const battleLogs = [];
  6791. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6792. let battleTime = 0;
  6793. let battleTimer = 0;
  6794. for (const battleResult of battleResults[MBR_2]) {
  6795. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6796. battleLogs.push(battleLog);
  6797. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6798. battleTimer += getTimer(maxTime)
  6799. battleTime += maxTime;
  6800. }
  6801. callback({
  6802. battleLogs,
  6803. battleTime,
  6804. battleTimer,
  6805. battleData,
  6806. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6807. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6808. });
  6809. });
  6810. battleInstantPlay.start();
  6811. }
  6812.  
  6813. /**
  6814. * Returns a function with the specified name from the class
  6815. *
  6816. * Возвращает из класса функцию с указанным именем
  6817. * @param {Object} classF Class // класс
  6818. * @param {String} nameF function name // имя функции
  6819. * @param {String} pos name and alias order // порядок имени и псевдонима
  6820. * @returns
  6821. */
  6822. function getF(classF, nameF, pos) {
  6823. pos = pos || false;
  6824. let prop = Object.entries(classF.prototype.__properties__)
  6825. if (!pos) {
  6826. return prop.filter((e) => e[1] == nameF).pop()[0];
  6827. } else {
  6828. return prop.filter((e) => e[0] == nameF).pop()[1];
  6829. }
  6830. }
  6831.  
  6832. /**
  6833. * Returns a function with the specified name from the class
  6834. *
  6835. * Возвращает из класса функцию с указанным именем
  6836. * @param {Object} classF Class // класс
  6837. * @param {String} nameF function name // имя функции
  6838. * @returns
  6839. */
  6840. function getFnP(classF, nameF) {
  6841. let prop = Object.entries(classF.__properties__)
  6842. return prop.filter((e) => e[1] == nameF).pop()[0];
  6843. }
  6844.  
  6845. /**
  6846. * Returns the function name with the specified ordinal from the class
  6847. *
  6848. * Возвращает имя функции с указаным порядковым номером из класса
  6849. * @param {Object} classF Class // класс
  6850. * @param {Number} nF Order number of function // порядковый номер функции
  6851. * @returns
  6852. */
  6853. function getFn(classF, nF) {
  6854. let prop = Object.keys(classF);
  6855. return prop[nF];
  6856. }
  6857.  
  6858. /**
  6859. * Returns the name of the function with the specified serial number from the prototype of the class
  6860. *
  6861. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6862. * @param {Object} classF Class // класс
  6863. * @param {Number} nF Order number of function // порядковый номер функции
  6864. * @returns
  6865. */
  6866. function getProtoFn(classF, nF) {
  6867. let prop = Object.keys(classF.prototype);
  6868. return prop[nF];
  6869. }
  6870. /**
  6871. * Description of replaced functions
  6872. *
  6873. * Описание подменяемых функций
  6874. */
  6875. replaceFunction = {
  6876. company: function () {
  6877. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6878. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6879. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6880. if (!isChecked('passBattle')) {
  6881. oldSkipMisson.call(this, a, b, c);
  6882. return;
  6883. }
  6884.  
  6885. try {
  6886. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6887.  
  6888. var a = new Game.BattlePresets(
  6889. !1,
  6890. !1,
  6891. !0,
  6892. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6893. !1
  6894. );
  6895. a = new Game.BattleInstantPlay(c, a);
  6896. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6897. a.start();
  6898. } catch (error) {
  6899. console.error('company', error);
  6900. oldSkipMisson.call(this, a, b, c);
  6901. }
  6902. };
  6903.  
  6904. Game.PlayerMissionData.prototype.P$h = function (a) {
  6905. let GM_2 = getFn(Game.GameModel, 2);
  6906. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6907. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6908. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6909. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6910. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6911. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6912. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  6913. };
  6914. },
  6915. /*
  6916. tower: function () {
  6917. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6918. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6919. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6920. if (!isChecked('passBattle')) {
  6921. oldSkipTower.call(this, a);
  6922. return;
  6923. }
  6924. try {
  6925. var p = new Game.BattlePresets(
  6926. !1,
  6927. !1,
  6928. !0,
  6929. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6930. !1
  6931. );
  6932. a = new Game.BattleInstantPlay(a, p);
  6933. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6934. a.start();
  6935. } catch (error) {
  6936. console.error('tower', error);
  6937. oldSkipMisson.call(this, a, b, c);
  6938. }
  6939. };
  6940.  
  6941. Game.PlayerTowerData.prototype.P$h = function (a) {
  6942. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  6943. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6944. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6945. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6946. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6947. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6948. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6949. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6950. };
  6951. },
  6952. */
  6953. // skipSelectHero: function() {
  6954. // if (!HOST) throw Error('Use connectGame');
  6955. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6956. // },
  6957. // кнопка пропустить
  6958. passBattle: function () {
  6959. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6960. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6961. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6962. if (!isChecked('passBattle')) {
  6963. oldPassBattle.call(this, a);
  6964. return;
  6965. }
  6966. try {
  6967. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6968. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6969. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6970. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  6971. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  6972. );
  6973. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6974. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  6975. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  6976. );
  6977. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6978. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  6979. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  6980. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6981. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6982. );
  6983. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  6984. getProtoFn(Game.ClipLabelBase, 24)
  6985. ]();
  6986. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  6987. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  6988. );
  6989. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  6990. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  6991. );
  6992. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  6993. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  6994. );
  6995. } catch (error) {
  6996. console.error('passBattle', error);
  6997. oldPassBattle.call(this, a);
  6998. }
  6999. };
  7000. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  7001. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  7002. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  7003. if (isChecked('passBattle')) {
  7004. return I18N('BTN_PASS');
  7005. } else {
  7006. return oldFunc.call(this);
  7007. }
  7008. };
  7009. },
  7010. endlessCards: function () {
  7011. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  7012. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  7013. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  7014. if (countPredictionCard <= 0) {
  7015. return true;
  7016. } else {
  7017. return oldEndlessCards.call(this);
  7018. }
  7019. };
  7020. },
  7021. speedBattle: function () {
  7022. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  7023. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  7024. Game.BattleController.prototype[get_timeScale] = function () {
  7025. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  7026. if (!speedBattle) {
  7027. return oldSpeedBattle.call(this);
  7028. }
  7029. try {
  7030. const BC_12 = getProtoFn(Game.BattleController, 12);
  7031. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  7032. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  7033. if (this[BC_12][BSM_12][BP_get_value]()) {
  7034. return 0;
  7035. }
  7036. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  7037. const BC_49 = getProtoFn(Game.BattleController, 49);
  7038. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  7039. const BC_14 = getProtoFn(Game.BattleController, 14);
  7040. const BC_3 = getFn(Game.BattleController, 3);
  7041. if (this[BC_12][BSM_2][BP_get_value]()) {
  7042. var a = speedBattle * this[BC_49]();
  7043. } else {
  7044. a = this[BC_12][BSM_1][BP_get_value]();
  7045. const maxSpeed = Math.max(...this[BC_14]);
  7046. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  7047. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  7048. }
  7049. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  7050. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  7051. const DS_23 = getFn(Game.DataStorage, 23);
  7052. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  7053. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  7054. const R_1 = getFn(selfGame.Reflect, 1);
  7055. const BC_1 = getFn(Game.BattleController, 1);
  7056. const get_config = getF(Game.BattlePresets, 'get_config');
  7057. null != b &&
  7058. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7059. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  7060. : a * selfGame.Reflect[R_1](b, 'default'));
  7061. return a;
  7062. } catch (error) {
  7063. console.error('passBatspeedBattletle', error);
  7064. return oldSpeedBattle.call(this);
  7065. }
  7066. };
  7067. },
  7068.  
  7069. /**
  7070. * Acceleration button without Valkyries favor
  7071. *
  7072. * Кнопка ускорения без Покровительства Валькирий
  7073. */
  7074. battleFastKey: function () {
  7075. const PSIVO_9 = getProtoFn(Game.PlayerSubscriptionInfoValueObject, 9);
  7076. const oldBattleFastKey = Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9];
  7077. Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9] = function () {
  7078. //const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  7079. //const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  7080. //Game.BattleGuiMediator.prototype[BGM_44] = function () {
  7081. let flag = true;
  7082. //console.log(flag)
  7083. if (flag) {
  7084. return true;
  7085. } else {
  7086. return oldBattleFastKey.call(this);
  7087. }
  7088. };
  7089. },
  7090. fastSeason: function () {
  7091. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  7092. const oldFuncName = getProtoFn(GameNavigator, 18);
  7093. const newFuncName = getProtoFn(GameNavigator, 16);
  7094. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  7095. const newFastSeason = GameNavigator.prototype[newFuncName];
  7096. GameNavigator.prototype[oldFuncName] = function (a, b) {
  7097. if (isChecked('fastSeason')) {
  7098. return newFastSeason.apply(this, [a]);
  7099. } else {
  7100. return oldFastSeason.apply(this, [a, b]);
  7101. }
  7102. };
  7103. },
  7104. ShowChestReward: function () {
  7105. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  7106. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  7107. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  7108. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  7109. if (correctShowOpenArtifact) {
  7110. correctShowOpenArtifact--;
  7111. return 100;
  7112. }
  7113. return oldGetOpenAmountTitan.call(this);
  7114. };
  7115.  
  7116. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  7117. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  7118. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  7119. ArtifactChest.prototype[getOpenAmount] = function () {
  7120. if (correctShowOpenArtifact) {
  7121. correctShowOpenArtifact--;
  7122. return 100;
  7123. }
  7124. return oldGetOpenAmount.call(this);
  7125. };
  7126.  
  7127. },
  7128. fixCompany: function () {
  7129. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  7130. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  7131. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  7132. const getThread = getF(GameBattleView, 'get_thread');
  7133. const oldFunc = GameBattleView.prototype[getThread];
  7134. GameBattleView.prototype[getThread] = function () {
  7135. return (
  7136. oldFunc.call(this) || {
  7137. [getOnViewDisposed]: async () => {},
  7138. }
  7139. );
  7140. };
  7141. },
  7142. BuyTitanArtifact: function () {
  7143. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  7144. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  7145. const oldFunc = BuyItemPopup.prototype[BIP_4];
  7146. BuyItemPopup.prototype[BIP_4] = function () {
  7147. if (isChecked('countControl')) {
  7148. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  7149. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  7150. if (this[BTAP_0]) {
  7151. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  7152. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  7153. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  7154. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  7155. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  7156. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  7157.  
  7158. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  7159. need = need ? need : 60;
  7160. this[BTAP_0][BIPM_9] = need;
  7161. this[BTAP_0][BIPM_5] = 10;
  7162. }
  7163. }
  7164. oldFunc.call(this);
  7165. };
  7166. },
  7167. ClanQuestsFastFarm: function () {
  7168. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  7169. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  7170. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  7171. return 0;
  7172. };
  7173. },
  7174. adventureCamera: function () {
  7175. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  7176. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  7177. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  7178. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  7179. this[AMC_5] = 0.4;
  7180. oldFunc.bind(this)(a);
  7181. };
  7182. },
  7183. unlockMission: function () {
  7184. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  7185. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  7186. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  7187. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  7188. return true;
  7189. };
  7190. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  7191. return true;
  7192. };
  7193. },
  7194. SendReplayPopUp: function() {
  7195. game_view_popup_ClipBasedPopup.prototype.SendReplayPopUp.call(this);
  7196. //if(this.mediator.get_canShareChat()) {
  7197. var clipFull = new game_mediator_gui_popup_chat_sendreplay_SendReplayPopUpClip();
  7198. game_assets_storage_AssetStorage.rsx.popup_theme.get_factory().create(clipFull,game_assets_storage_AssetStorage.rsx.popup_theme.data.getClipByName("send_replay_popup"));
  7199. this.addChild(clipFull.get_graphics());
  7200. clipFull.tf_title.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_SEND_REPLAY_TEXT"));
  7201. clipFull.replay_info.tf_label.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_REPLAY_TEXT"));
  7202. clipFull.action_btn.set_label(com_progrestar_common_lang_Translate.translate("UI_POPUP_CHAT_SEND"));
  7203. clipFull.tf_message_input.set_prompt(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_INPUT_MESSAGE_PROMPT"));
  7204. clipFull.tf_message_input.set_text(this.mediator.get_defauiltText());
  7205. clipFull.action_btn.get_signal_click().add($bind(this,this.handler_sendClick));
  7206. clipFull.replay_info.btn_option.get_signal_click().add($bind(this,this.handler_replayClick));
  7207. this.clip = clipFull;
  7208. /*} else {
  7209. var clipShort = new game_mediator_gui_popup_chat_sendreplay_SendReplayPopUpClipShort();
  7210. game_assets_storage_AssetStorage.rsx.popup_theme.get_factory().create(clipShort,game_assets_storage_AssetStorage.rsx.popup_theme.data.getClipByName("send_replay_popup_short"));
  7211. this.addChild(clipShort.get_graphics());
  7212. this.clip = clipShort;
  7213. }*/
  7214. this.clip.button_close.get_signal_click().add(($_=this.mediator,$bind($_,$_.close)));
  7215. this.clip.tf_replay.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_ARENA_REPLAY_URL"));
  7216. this.clip.replay_url_input.set_text(this.mediator.get_replayURL());
  7217. this.clip.replay_url_input.addEventListener("change",$bind(this,this.handler_replayUrlInputChange));
  7218. this.clip.copy_btn.set_label(com_progrestar_common_lang_Translate.translate("UI_DIALOG_BUTTON_COPY"));
  7219. },
  7220. };
  7221.  
  7222. /**
  7223. * Starts replacing recorded functions
  7224. *
  7225. * Запускает замену записанных функций
  7226. */
  7227. this.activateHacks = function () {
  7228. if (!selfGame) throw Error('Use connectGame');
  7229. for (let func in replaceFunction) {
  7230. try {
  7231. replaceFunction[func]();
  7232. } catch (error) {
  7233. console.error(error);
  7234. }
  7235. }
  7236. }
  7237.  
  7238. /**
  7239. * Returns the game object
  7240. *
  7241. * Возвращает объект игры
  7242. */
  7243. this.getSelfGame = function () {
  7244. return selfGame;
  7245. }
  7246.  
  7247. /**
  7248. * Updates game data
  7249. *
  7250. * Обновляет данные игры
  7251. */
  7252. this.refreshGame = function () {
  7253. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  7254. try {
  7255. cheats.refreshInventory();
  7256. } catch (e) { }
  7257. }
  7258.  
  7259. /**
  7260. * Update inventory
  7261. *
  7262. * Обновляет инвентарь
  7263. */
  7264. this.refreshInventory = async function () {
  7265. const GM_INST = getFnP(Game.GameModel, "get_instance");
  7266. const GM_0 = getProtoFn(Game.GameModel, 0);
  7267. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  7268. const Player = Game.GameModel[GM_INST]()[GM_0];
  7269. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  7270. Player[P_24].init(await Send({calls:[{name:"inventoryGet",args:{},ident:"body"}]}).then(e => e.results[0].result.response))
  7271. }
  7272. this.updateInventory = function (reward) {
  7273. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7274. const GM_0 = getProtoFn(Game.GameModel, 0);
  7275. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7276. const Player = Game.GameModel[GM_INST]()[GM_0];
  7277. Player[P_24].init(reward);
  7278. };
  7279. this.updateMap = function (data) {
  7280. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7281. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7282. const GM_0 = getProtoFn(Game.GameModel, 0);
  7283. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7284. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7285. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7286. };
  7287.  
  7288. /**
  7289. * Change the play screen on windowName
  7290. *
  7291. * Сменить экран игры на windowName
  7292. *
  7293. * Possible options:
  7294. *
  7295. * Возможные варианты:
  7296. *
  7297. * 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
  7298. */
  7299. this.goNavigtor = function (windowName) {
  7300. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  7301. let window = mechanicStorage[windowName];
  7302. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  7303. let Game = selfGame['Game'];
  7304. let navigator = getF(Game, "get_navigator")
  7305. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 20)
  7306. let instance = getFnP(Game, 'get_instance');
  7307. Game[instance]()[navigator]()[navigate](window, event);
  7308. }
  7309.  
  7310. /**
  7311. * Move to the sanctuary cheats.goSanctuary()
  7312. *
  7313. * Переместиться в святилище cheats.goSanctuary()
  7314. */
  7315. this.goSanctuary = () => {
  7316. this.goNavigtor("SANCTUARY");
  7317. }
  7318.  
  7319. /**
  7320. * Go to Guild War
  7321. *
  7322. * Перейти к Войне Гильдий
  7323. */
  7324. this.goClanWar = function() {
  7325. let instance = getFnP(Game.GameModel, 'get_instance')
  7326. let player = Game.GameModel[instance]().A;
  7327. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  7328. new clanWarSelect(player).open();
  7329. }
  7330.  
  7331. /**
  7332. * Go to BrawlShop
  7333. *
  7334. * Переместиться в BrawlShop
  7335. */
  7336. this.goBrawlShop = () => {
  7337. const instance = getFnP(Game.GameModel, 'get_instance')
  7338. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7339. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7340. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7341. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7342.  
  7343. const player = Game.GameModel[instance]().A;
  7344. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7345. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  7346. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  7347. }
  7348.  
  7349. /**
  7350. * Returns all stores from game data
  7351. *
  7352. * Возвращает все магазины из данных игры
  7353. */
  7354. this.getShops = () => {
  7355. const instance = getFnP(Game.GameModel, 'get_instance')
  7356. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7357. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7358. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7359.  
  7360. const player = Game.GameModel[instance]().A;
  7361. return player[P_36][PSD_0][IM_0];
  7362. }
  7363.  
  7364. /**
  7365. * Returns the store from the game data by ID
  7366. *
  7367. * Возвращает магазин из данных игры по идетификатору
  7368. */
  7369. this.getShop = (id) => {
  7370. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7371. const shops = this.getShops();
  7372. const shop = shops[id]?.[PSDE_4];
  7373. return shop;
  7374. }
  7375. /**
  7376. * Moves to the store with the specified ID
  7377. *
  7378. * Перемещает к магазину с указанным идетификатором
  7379. */
  7380. this.goShopId = function (id) {
  7381. const shop = this.getShop(id);
  7382. if (!shop) {
  7383. return;
  7384. }
  7385. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  7386. let Game = selfGame['Game'];
  7387. let navigator = getF(Game, "get_navigator");
  7388. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 21);
  7389. let instance = getFnP(Game, 'get_instance');
  7390. Game[instance]()[navigator]()[navigate](shop, event);
  7391. }
  7392. /**
  7393. * Opens a list of non-standard stores
  7394. *
  7395. * Открывает список не стандартных магазинов
  7396. */
  7397. this.goCustomShops = async (p = 0) => {
  7398. /** Запрос данных нужных магазинов */
  7399. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  7400. const shops = lib.getData('shop');
  7401. for (const id in shops) {
  7402. const check = !shops[id].ident.includes('merchantPromo') &&
  7403. ![1, 4, 5, 6, 7, 8, 9, 10, 11, 1023, 1024].includes(+id);
  7404. if (check) {
  7405. calls.push({
  7406. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  7407. })
  7408. }
  7409. }
  7410. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  7411. const shopAll = result.shift();
  7412. const DS_32 = getFn(Game.DataStorage, 32)
  7413. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7414. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7415. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  7416. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  7417. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  7418. for (let shop of result) {
  7419. shopAll[shop.id] = shop;
  7420. // Снимаем все ограничения с магазинов
  7421. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  7422. shopLibData[SD_21] = 1;
  7423. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7424. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7425. teamLevel: 10
  7426. });
  7427. }
  7428. /** Скрываем все остальные магазины */
  7429. for (let id in shops) {
  7430. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7431. if (shopLibData[ident].includes('merchantPromo')) {
  7432. shopLibData[SD_21] = 0;
  7433. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7434. teamLevel: 999
  7435. });
  7436. }
  7437. }
  7438. const instance = getFnP(Game.GameModel, 'get_instance')
  7439. const GM_0 = getProtoFn(Game.GameModel, 0);
  7440. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7441. const player = Game.GameModel[instance]()[GM_0];
  7442. /** Пересоздаем объект с магазинами */
  7443. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7444. player[P_36].init(shopAll);
  7445. /** Даем магазинам новые названия */
  7446. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7447. const shopName = getFn(cheats.getShop(1), 14);
  7448. const currentShops = this.getShops();
  7449. let count = 0;
  7450. const start = 9 * p + 1;
  7451. const end = start + 8;
  7452. for (let id in currentShops) {
  7453. const shop = currentShops[id][PSDE_4];
  7454. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7455. /** Скрываем стандартные магазины */
  7456. shop[SD_21] = 0;
  7457. } else {
  7458. count++;
  7459. if (count < start || count > end) {
  7460. shop[SD_21] = 0;
  7461. continue;
  7462. }
  7463. shop[SD_21] = 1;
  7464. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  7465. shop[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7466. shop[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7467. teamLevel: 10
  7468. });
  7469. }
  7470. }
  7471. console.log(count, start, end)
  7472. /** Отправляемся в городскую лавку */
  7473. this.goShopId(1);
  7474. }
  7475. /**
  7476. * Opens a list of standard stores
  7477. *
  7478. * Открывает список стандартных магазинов
  7479. */
  7480. this.goDefaultShops = async () => {
  7481. const result = await Send({ calls: [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }] })
  7482. .then(e => e.results.map(n => n.result.response));
  7483. const shopAll = result.shift();
  7484. const shops = lib.getData('shop');
  7485. const DS_8 = getFn(Game.DataStorage, 8)
  7486. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  7487. /** Получаем объект валюты магазина для оторажения */
  7488. const coins = Game.DataStorage[DS_8][DSB_4](85);
  7489. coins.__proto__ = selfGame["game.data.storage.resource.ConsumableDescription"].prototype;
  7490. const DS_32 = getFn(Game.DataStorage, 32)
  7491. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7492. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7493. for (const id in shops) {
  7494. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7495. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7496. shopLibData[SD_21] = 1;
  7497. } else {
  7498. shopLibData[SD_21] = 0;
  7499. }
  7500. }
  7501. const instance = getFnP(Game.GameModel, 'get_instance')
  7502. const GM_0 = getProtoFn(Game.GameModel, 0);
  7503. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7504. const player = Game.GameModel[instance]()[GM_0];
  7505. /** Пересоздаем объект с магазинами */
  7506. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7507. player[P_36].init(shopAll);
  7508. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7509. const currentShops = this.getShops();
  7510. for (let id in currentShops) {
  7511. const shop = currentShops[id][PSDE_4];
  7512. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7513. shop[SD_21] = 1;
  7514. } else {
  7515. shop[SD_21] = 0;
  7516. }
  7517. }
  7518. this.goShopId(1);
  7519. }
  7520. /**
  7521. * Opens a list of Secret Wealth stores
  7522. *
  7523. * Открывает список магазинов Тайное богатство
  7524. */
  7525. this.goSecretWealthShops = async () => {
  7526. /** Запрос данных нужных магазинов */
  7527. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  7528. const shops = lib.getData('shop');
  7529. for (const id in shops) {
  7530. if (shops[id].ident.includes('merchantPromo') && shops[id].teamLevelToUnlock <= 130) {
  7531. calls.push({
  7532. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  7533. })
  7534. }
  7535. }
  7536. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  7537. const shopAll = result.shift();
  7538. const DS_32 = getFn(Game.DataStorage, 32)
  7539. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7540. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7541. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  7542. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  7543. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  7544. const specialCurrency = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 15);
  7545. const DS_8 = getFn(Game.DataStorage, 8)
  7546. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  7547. /** Получаем объект валюты магазина для оторажения */
  7548. const coins = Game.DataStorage[DS_8][DSB_4](85);
  7549. coins.__proto__ = selfGame["game.data.storage.resource.CoinDescription"].prototype;
  7550. for (let shop of result) {
  7551. shopAll[shop.id] = shop;
  7552. /** Снимаем все ограничения с магазинов */
  7553. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  7554. if (shopLibData[ident].includes('merchantPromo')) {
  7555. shopLibData[SD_21] = 1;
  7556. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7557. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7558. teamLevel: 10
  7559. });
  7560. }
  7561. }
  7562. /** Скрываем все остальные магазины */
  7563. for (let id in shops) {
  7564. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7565. if (!shopLibData[ident].includes('merchantPromo')) {
  7566. shopLibData[SD_21] = 0;
  7567. }
  7568. }
  7569. const instance = getFnP(Game.GameModel, 'get_instance')
  7570. const GM_0 = getProtoFn(Game.GameModel, 0);
  7571. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7572. const player = Game.GameModel[instance]()[GM_0];
  7573. /** Пересоздаем объект с магазинами */
  7574. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7575. player[P_36].init(shopAll);
  7576. /** Даем магазинам новые названия */
  7577. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7578. const shopName = getFn(cheats.getShop(1), 14);
  7579. const currentShops = this.getShops();
  7580. for (let id in currentShops) {
  7581. const shop = currentShops[id][PSDE_4];
  7582. if (shop[ident].includes('merchantPromo')) {
  7583. shop[SD_21] = 1;
  7584. shop[specialCurrency] = coins;
  7585. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  7586. } else if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7587. /** Скрываем стандартные магазины */
  7588. shop[SD_21] = 0;
  7589. }
  7590. }
  7591. /** Отправляемся в городскую лавку */
  7592. this.goShopId(1);
  7593. }
  7594. /**
  7595. * Change island map
  7596. *
  7597. * Сменить карту острова
  7598. */
  7599. this.changeIslandMap = (mapId = 2) => {
  7600. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7601. const GM_0 = getProtoFn(Game.GameModel, 0);
  7602. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 60);
  7603. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7604. const Player = Game.GameModel[GameInst]()[GM_0];
  7605. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7606.  
  7607. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 17)
  7608. const navigator = getF(selfGame['Game'], "get_navigator");
  7609. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  7610. }
  7611.  
  7612. /**
  7613. * Game library availability tracker
  7614. *
  7615. * Отслеживание доступности игровой библиотеки
  7616. */
  7617. function checkLibLoad() {
  7618. timeout = setTimeout(() => {
  7619. if (Game.GameModel) {
  7620. changeLib();
  7621. } else {
  7622. checkLibLoad();
  7623. }
  7624. }, 100)
  7625. }
  7626.  
  7627. /**
  7628. * Game library data spoofing
  7629. *
  7630. * Подмена данных игровой библиотеки
  7631. */
  7632. function changeLib() {
  7633. console.log('lib connect');
  7634. const originalStartFunc = Game.GameModel.prototype.start;
  7635. Game.GameModel.prototype.start = function (a, b, c) {
  7636. self.libGame = b.raw;
  7637. self.doneLibLoad(self.libGame);
  7638. try {
  7639. const levels = b.raw.seasonAdventure.level;
  7640. for (const id in levels) {
  7641. const level = levels[id];
  7642. level.clientData.graphics.fogged = level.clientData.graphics.visible
  7643. }
  7644. const adv = b.raw.seasonAdventure.list[1];
  7645. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7646. } catch (e) {
  7647. console.warn(e);
  7648. }
  7649. originalStartFunc.call(this, a, b, c);
  7650. }
  7651. }
  7652.  
  7653. this.LibLoad = function() {
  7654. return new Promise((e) => {
  7655. this.doneLibLoad = e;
  7656. });
  7657. }
  7658. /**
  7659. * Returns the value of a language constant
  7660. *
  7661. * Возвращает значение языковой константы
  7662. * @param {*} langConst language constant // языковая константа
  7663. * @returns
  7664. */
  7665. this.translate = function (langConst) {
  7666. return Game.Translate.translate(langConst);
  7667. }
  7668.  
  7669. connectGame();
  7670. checkLibLoad();
  7671. }
  7672.  
  7673. /**
  7674. * Auto collection of gifts
  7675. *
  7676. * Автосбор подарков
  7677. */
  7678. async function getAutoGifts() {
  7679. const collector = new GiftCodeCollector();
  7680. const giftCodes = await collector.getGiftCodes();
  7681. console.log(giftCodes);
  7682.  
  7683. for (const key of giftCodes)
  7684. send({ calls: [{ name: "registration", args: { giftId:key, user: { referrer: {} } },
  7685. context: { actionTs: Math.floor(performance.now()), cookie: window?.NXAppInfo?.session_id || null }, ident: "body" }] });
  7686. }
  7687.  
  7688. /**
  7689. * To fill the kills in the Forge of Souls
  7690. *
  7691. * Набить килов в горниле душ
  7692. */
  7693. async function bossRatingEvent() {
  7694. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7695. if (!topGet || !topGet.results[0].result.response[0]) {
  7696. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7697. return;
  7698. }
  7699. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7700. const result = await Send(JSON.stringify({
  7701. calls: [
  7702. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7703. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7704. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7705. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7706. ]
  7707. }));
  7708. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7709. if (!bossEventInfo) {
  7710. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7711. return;
  7712. }
  7713. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7714. const party = Object.values(result.results[0].result.response.replay.attackers);
  7715. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7716. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7717. const calls = [];
  7718. /**
  7719. * First pack
  7720. *
  7721. * Первая пачка
  7722. */
  7723. const args = {
  7724. heroes: [],
  7725. favor: {}
  7726. }
  7727. for (let hero of party) {
  7728. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7729. args.pet = hero.id;
  7730. continue;
  7731. }
  7732. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7733. continue;
  7734. }
  7735. args.heroes.push(hero.id);
  7736. if (hero.favorPetId) {
  7737. args.favor[hero.id] = hero.favorPetId;
  7738. }
  7739. }
  7740. if (args.heroes.length) {
  7741. calls.push({
  7742. name: "bossRatingEvent_startBattle",
  7743. args,
  7744. ident: "body_0"
  7745. });
  7746. }
  7747. /**
  7748. * Other packs
  7749. *
  7750. * Другие пачки
  7751. */
  7752. let heroes = [];
  7753. let count = 1;
  7754. while (heroId = availableHeroes.pop()) {
  7755. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7756. continue;
  7757. }
  7758. heroes.push(heroId);
  7759. if (heroes.length == 5) {
  7760. calls.push({
  7761. name: "bossRatingEvent_startBattle",
  7762. args: {
  7763. heroes: [...heroes],
  7764. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7765. },
  7766. ident: "body_" + count
  7767. });
  7768. heroes = [];
  7769. count++;
  7770. }
  7771. }
  7772.  
  7773. if (!calls.length) {
  7774. setProgress(`${I18N('NO_HEROES')}`, true);
  7775. return;
  7776. }
  7777.  
  7778. const resultBattles = await Send(JSON.stringify({ calls }));
  7779. console.log(resultBattles);
  7780. rewardBossRatingEvent();
  7781. }
  7782.  
  7783. /**
  7784. * Collecting Rewards from the Forge of Souls
  7785. *
  7786. * Сбор награды из Горнила Душ
  7787. */
  7788. function rewardBossRatingEvent() {
  7789. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7790. send(rewardBossRatingCall, function (data) {
  7791. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7792. if (!bossEventInfo) {
  7793. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7794. return;
  7795. }
  7796.  
  7797. let farmedChests = bossEventInfo.progress.farmedChests;
  7798. let score = bossEventInfo.progress.score;
  7799. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7800. let revard = bossEventInfo.reward;
  7801.  
  7802. let getRewardCall = {
  7803. calls: []
  7804. }
  7805.  
  7806. let count = 0;
  7807. for (let i = 1; i < 10; i++) {
  7808. if (farmedChests.includes(i)) {
  7809. continue;
  7810. }
  7811. if (score < revard[i].score) {
  7812. break;
  7813. }
  7814. getRewardCall.calls.push({
  7815. name: "bossRatingEvent_getReward",
  7816. args: {
  7817. rewardId: i
  7818. },
  7819. ident: "body_" + i
  7820. });
  7821. count++;
  7822. }
  7823. if (!count) {
  7824. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7825. return;
  7826. }
  7827.  
  7828. send(JSON.stringify(getRewardCall), e => {
  7829. console.log(e);
  7830. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7831. });
  7832. });
  7833. }
  7834.  
  7835. /**
  7836. * Collect Easter eggs and event rewards
  7837. *
  7838. * Собрать пасхалки и награды событий
  7839. */
  7840. function offerFarmAllReward() {
  7841. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7842. return Send(offerGetAllCall).then((data) => {
  7843. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7844. if (!offerGetAll.length) {
  7845. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7846. return;
  7847. }
  7848.  
  7849. const calls = [];
  7850. for (let reward of offerGetAll) {
  7851. calls.push({
  7852. name: "offerFarmReward",
  7853. args: {
  7854. offerId: reward.id
  7855. },
  7856. ident: "offerFarmReward_" + reward.id
  7857. });
  7858. }
  7859.  
  7860. return Send(JSON.stringify({ calls })).then(e => {
  7861. console.log(e);
  7862. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7863. });
  7864. });
  7865. }
  7866.  
  7867. /**
  7868. * Assemble Outland
  7869. *
  7870. * Собрать запределье
  7871. */
  7872. function getOutland() {
  7873. return new Promise(function (resolve, reject) {
  7874. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7875. let bosses = e.results[0].result.response;
  7876.  
  7877. let bossRaidOpenChestCall = {
  7878. calls: []
  7879. };
  7880.  
  7881. for (let boss of bosses) {
  7882. if (boss.mayRaid) {
  7883. bossRaidOpenChestCall.calls.push({
  7884. name: "bossRaid",
  7885. args: {
  7886. bossId: boss.id
  7887. },
  7888. ident: "bossRaid_" + boss.id
  7889. });
  7890. bossRaidOpenChestCall.calls.push({
  7891. name: "bossOpenChest",
  7892. args: {
  7893. bossId: boss.id,
  7894. amount: 1,
  7895. starmoney: 0
  7896. },
  7897. ident: "bossOpenChest_" + boss.id
  7898. });
  7899. } else if (boss.chestId == 1) {
  7900. bossRaidOpenChestCall.calls.push({
  7901. name: "bossOpenChest",
  7902. args: {
  7903. bossId: boss.id,
  7904. amount: 1,
  7905. starmoney: 0
  7906. },
  7907. ident: "bossOpenChest_" + boss.id
  7908. });
  7909. }
  7910. }
  7911.  
  7912. if (!bossRaidOpenChestCall.calls.length) {
  7913. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7914. resolve();
  7915. return;
  7916. }
  7917.  
  7918. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7919. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7920. resolve();
  7921. });
  7922. });
  7923. });
  7924. }
  7925.  
  7926. /**
  7927. * Collect all rewards
  7928. *
  7929. * Собрать все награды
  7930. */
  7931. function questAllFarm() {
  7932. return new Promise(function (resolve, reject) {
  7933. let questGetAllCall = {
  7934. calls: [{
  7935. name: "questGetAll",
  7936. args: {},
  7937. ident: "body"
  7938. }]
  7939. }
  7940. send(JSON.stringify(questGetAllCall), function (data) {
  7941. let questGetAll = data.results[0].result.response;
  7942. const questAllFarmCall = {
  7943. calls: []
  7944. }
  7945. let number = 0;
  7946. for (let quest of questGetAll) {
  7947. if (quest.id < 1e6 && quest.state == 2) {
  7948. questAllFarmCall.calls.push({
  7949. name: "questFarm",
  7950. args: {
  7951. questId: quest.id
  7952. },
  7953. ident: `group_${number}_body`
  7954. });
  7955. number++;
  7956. }
  7957. }
  7958.  
  7959. if (!questAllFarmCall.calls.length) {
  7960. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7961. resolve();
  7962. return;
  7963. }
  7964.  
  7965. send(JSON.stringify(questAllFarmCall), function (res) {
  7966. console.log(res);
  7967. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7968. resolve();
  7969. });
  7970. });
  7971. })
  7972. }
  7973.  
  7974. /**
  7975. * Mission auto repeat
  7976. *
  7977. * Автоповтор миссии
  7978. * isStopSendMission = false;
  7979. * isSendsMission = true;
  7980. **/
  7981. this.sendsMission = async function (param) {
  7982. if (isStopSendMission) {
  7983. isSendsMission = false;
  7984. console.log(I18N('STOPPED'));
  7985. setProgress('');
  7986. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7987. msg: 'Ok',
  7988. result: true
  7989. }, ])
  7990. return;
  7991. }
  7992. lastMissionBattleStart = Date.now();
  7993. let missionStartCall = {
  7994. "calls": [{
  7995. "name": "missionStart",
  7996. "args": lastMissionStart,
  7997. "ident": "body"
  7998. }]
  7999. }
  8000. /**
  8001. * Mission Request
  8002. *
  8003. * Запрос на выполнение мисcии
  8004. */
  8005. SendRequest(JSON.stringify(missionStartCall), async e => {
  8006. if (e['error']) {
  8007. isSendsMission = false;
  8008. console.log(e['error']);
  8009. setProgress('');
  8010. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8011. await popup.confirm(msg, [
  8012. {msg: 'Ok', result: true},
  8013. ])
  8014. return;
  8015. }
  8016. /**
  8017. * Mission data calculation
  8018. *
  8019. * Расчет данных мисcии
  8020. */
  8021. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  8022. /** missionTimer */
  8023. let timer = getTimer(r.battleTime) + 5;
  8024. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  8025. if (period < timer) {
  8026. timer = timer - period;
  8027. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  8028. }
  8029.  
  8030. let missionEndCall = {
  8031. "calls": [{
  8032. "name": "missionEnd",
  8033. "args": {
  8034. "id": param.id,
  8035. "result": r.result,
  8036. "progress": r.progress
  8037. },
  8038. "ident": "body"
  8039. }]
  8040. }
  8041. /**
  8042. * Mission Completion Request
  8043. *
  8044. * Запрос на завершение миссии
  8045. */
  8046. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  8047. if (e['error']) {
  8048. isSendsMission = false;
  8049. console.log(e['error']);
  8050. setProgress('');
  8051. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  8052. await popup.confirm(msg, [
  8053. {msg: 'Ok', result: true},
  8054. ])
  8055. return;
  8056. }
  8057. r = e.results[0].result.response;
  8058. if (r['error']) {
  8059. isSendsMission = false;
  8060. console.log(r['error']);
  8061. setProgress('');
  8062. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  8063. {msg: 'Ok', result: true},
  8064. ])
  8065. return;
  8066. }
  8067.  
  8068. param.count++;
  8069. let RaidMission = getInput('countRaid');
  8070.  
  8071. if (RaidMission==param.count){
  8072. isStopSendMission = true;
  8073. console.log(RaidMission);
  8074. }
  8075. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  8076. isStopSendMission = true;
  8077. });
  8078. setTimeout(sendsMission, 1, param);
  8079. });
  8080. })
  8081. });
  8082. }
  8083.  
  8084. /**
  8085. * Opening of russian dolls
  8086. *
  8087. * Открытие матрешек
  8088. */
  8089. async function openRussianDolls(libId, amount) {
  8090. let sum = 0;
  8091. const sumResult = {};
  8092. let count = 0;
  8093. while (amount) {
  8094. sum += amount;
  8095. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  8096. const calls = [
  8097. {
  8098. name: 'consumableUseLootBox',
  8099. args: { libId, amount },
  8100. ident: 'body',
  8101. },
  8102. ];
  8103. const response = await Send(JSON.stringify({ calls })).then((e) => e.results[0].result.response);
  8104. let [countLootBox, result] = Object.entries(response).pop();
  8105. count += +countLootBox;
  8106. let newCount = 0;
  8107. if (result?.consumable && result.consumable[libId]) {
  8108. newCount = result.consumable[libId];
  8109. delete result.consumable[libId];
  8110. }
  8111. mergeItemsObj(sumResult, result);
  8112. amount = newCount;
  8113. }
  8114. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  8115. return [count, sumResult];
  8116. }
  8117.  
  8118. function mergeItemsObj(obj1, obj2) {
  8119. for (const key in obj2) {
  8120. if (obj1[key]) {
  8121. if (typeof obj1[key] == 'object') {
  8122. for (const innerKey in obj2[key]) {
  8123. obj1[key][innerKey] = (obj1[key][innerKey] || 0) + obj2[key][innerKey];
  8124. }
  8125. } else {
  8126. obj1[key] += obj2[key] || 0;
  8127. }
  8128. } else {
  8129. obj1[key] = obj2[key];
  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. name: "userGetInfo",
  8228. args: {},
  8229. ident: "userGetInfo"
  8230. },
  8231. {
  8232. name: "clanWarGetInfo",
  8233. args: {},
  8234. ident: "clanWarGetInfo"
  8235. },
  8236. {
  8237. name: "titanArenaGetStatus",
  8238. args: {},
  8239. ident: "titanArenaGetStatus"
  8240. }];
  8241. const result = await Send(JSON.stringify({ calls }));
  8242. const infos = result.results;
  8243. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  8244. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8245. const arePointsMax = infos[1].result.response?.arePointsMax;
  8246. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8247. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8248.  
  8249. const sanctuaryButton = buttons['goToSanctuary'].button;
  8250. const clanWarButton = buttons['goToClanWar'].button;
  8251. const titansArenaButton = buttons['testTitanArena'].button;
  8252.  
  8253. /*if (portalSphere.amount) {
  8254. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  8255. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  8256. } else {*/
  8257. sanctuaryButton.style.color = '';
  8258. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  8259. //}
  8260. /*if (clanWarMyTries && !arePointsMax) {
  8261. clanWarButton.style.color = 'red';
  8262. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  8263. } else {*/
  8264. clanWarButton.style.color = '';
  8265. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  8266. //}
  8267.  
  8268. /*if (titansLevel < 7 && titansStatus == 'battle') {
  8269. const partColor = Math.floor(125 * titansLevel / 7);
  8270. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  8271. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  8272. } else {*/
  8273. titansArenaButton.style.color = '';
  8274. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  8275. //}
  8276. //тест убрал подсветку красным в меню
  8277. const imgPortal =
  8278. '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';
  8279.  
  8280. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8281. resolve();
  8282. });
  8283. }
  8284. // тест сделать все
  8285. /** Отправить подарки мое*/
  8286. function testclanSendDailyGifts() {
  8287.  
  8288. send('{"calls":[{"name":"clanSendDailyGifts","args":{},"ident":"clanSendDailyGifts"}]}', e => {
  8289. setProgress('Награды собраны', true);});
  8290. }
  8291. /** Открой сферу артефактов титанов*/
  8292. function testtitanArtifactChestOpen() {
  8293. send('{"calls":[{"name":"titanArtifactChestOpen","args":{"amount":1,"free":true},"ident":"body"}]}',
  8294. isWeCanDo => {
  8295. return info['inventoryGet']?.consumable[55] > 0
  8296. //setProgress('Награды собраны', true);
  8297. });
  8298. }
  8299. /** Воспользуйся призывом питомцев 1 раз*/
  8300. function testpet_chestOpen() {
  8301. send('{"calls":[{"name":"pet_chestOpen","args":{"amount":1,"paid":false},"ident":"pet_chestOpen"}]}',
  8302. isWeCanDo => {
  8303. return info['inventoryGet']?.consumable[90] > 0
  8304. //setProgress('Награды собраны', true);
  8305. });
  8306. }
  8307.  
  8308. async function getDailyBonus() {
  8309. const dailyBonusInfo = await Send(JSON.stringify({
  8310. calls: [{
  8311. name: "dailyBonusGetInfo",
  8312. args: {},
  8313. ident: "body"
  8314. }]
  8315. })).then(e => e.results[0].result.response);
  8316. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8317.  
  8318. if (!availableToday) {
  8319. console.log('Уже собрано');
  8320. return;
  8321. }
  8322.  
  8323. const currentVipPoints = +userInfo.vipPoints;
  8324. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8325. const vipInfo = lib.getData('level').vip;
  8326. let currentVipLevel = 0;
  8327. for (let i in vipInfo) {
  8328. vipLvl = vipInfo[i];
  8329. if (currentVipPoints >= vipLvl.vipPoints) {
  8330. currentVipLevel = vipLvl.level;
  8331. }
  8332. }
  8333. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8334.  
  8335. const calls = [{
  8336. name: "dailyBonusFarm",
  8337. args: {
  8338. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8339. },
  8340. ident: "body"
  8341. }];
  8342.  
  8343. const result = await Send(JSON.stringify({ calls }));
  8344. if (result.error) {
  8345. console.error(result.error);
  8346. return;
  8347. }
  8348.  
  8349. const reward = result.results[0].result.response;
  8350. const type = Object.keys(reward).pop();
  8351. const itemId = Object.keys(reward[type]).pop();
  8352. const count = reward[type][itemId];
  8353. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8354.  
  8355. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8356. }
  8357.  
  8358. async function farmStamina(lootBoxId = 148) {
  8359. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8360. .then(e => e.results[0].result.response.consumable[148]);
  8361.  
  8362. /** Добавить другие ящики */
  8363. /**
  8364. * 144 - медная шкатулка
  8365. * 145 - бронзовая шкатулка
  8366. * 148 - платиновая шкатулка
  8367. */
  8368. if (!lootBox) {
  8369. setProgress(I18N('NO_BOXES'), true);
  8370. return;
  8371. }
  8372.  
  8373. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8374. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8375. { result: false, isClose: true },
  8376. { msg: I18N('BTN_YES'), result: true },
  8377. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8378. ]);
  8379.  
  8380. if (!+result) {
  8381. return;
  8382. }
  8383.  
  8384. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8385. maxFarmEnergy = +result;
  8386. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8387. } else {
  8388. maxFarmEnergy = 0;
  8389. }
  8390.  
  8391. let collectEnergy = 0;
  8392. for (let count = lootBox; count > 0; count--) {
  8393. const response = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}').then(
  8394. (e) => e.results[0].result.response
  8395. );
  8396. const result = Object.values(response).pop();
  8397. if ('stamina' in result) {
  8398. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8399. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8400. if (!maxFarmEnergy) {
  8401. return;
  8402. }
  8403. collectEnergy += +result.stamina;
  8404. if (collectEnergy >= maxFarmEnergy) {
  8405. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8406. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8407. return;
  8408. }
  8409. } else {
  8410. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8411. console.log(result);
  8412. }
  8413. }
  8414.  
  8415. setProgress(I18N('BOXES_OVER'), true);
  8416. }
  8417.  
  8418. async function fillActive() {
  8419. const data = await Send(JSON.stringify({
  8420. calls: [{
  8421. name: "questGetAll",
  8422. args: {},
  8423. ident: "questGetAll"
  8424. }, {
  8425. name: "inventoryGet",
  8426. args: {},
  8427. ident: "inventoryGet"
  8428. }, {
  8429. name: "clanGetInfo",
  8430. args: {},
  8431. ident: "clanGetInfo"
  8432. }
  8433. ]
  8434. })).then(e => e.results.map(n => n.result.response));
  8435.  
  8436. const quests = data[0];
  8437. const inv = data[1];
  8438. const stat = data[2].stat;
  8439. const maxActive = 2000 - stat.todayItemsActivity;
  8440. if (maxActive <= 0) {
  8441. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8442. return;
  8443. }
  8444.  
  8445. let countGetActive = 0;
  8446. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8447. if (quest) {
  8448. countGetActive = 1750 - quest.progress;
  8449. }
  8450.  
  8451. if (countGetActive <= 0) {
  8452. countGetActive = maxActive;
  8453. }
  8454. console.log(countGetActive);
  8455.  
  8456. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8457. { result: false, isClose: true },
  8458. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8459. ]));
  8460.  
  8461. if (!countGetActive) {
  8462. return;
  8463. }
  8464.  
  8465. if (countGetActive > maxActive) {
  8466. countGetActive = maxActive;
  8467. }
  8468.  
  8469. const items = lib.getData('inventoryItem');
  8470.  
  8471. let itemsInfo = [];
  8472. for (let type of ['gear', 'scroll']) {
  8473. for (let i in inv[type]) {
  8474. const v = items[type][i]?.enchantValue || 0;
  8475. itemsInfo.push({
  8476. id: i,
  8477. count: inv[type][i],
  8478. v,
  8479. type
  8480. })
  8481. }
  8482. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8483. for (let i in inv[invType]) {
  8484. const v = items[type][i]?.fragmentEnchantValue || 0;
  8485. itemsInfo.push({
  8486. id: i,
  8487. count: inv[invType][i],
  8488. v,
  8489. type: invType
  8490. })
  8491. }
  8492. }
  8493. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8494. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8495. console.log(itemsInfo);
  8496. const activeItem = itemsInfo.shift();
  8497. console.log(activeItem);
  8498. const countItem = Math.ceil(countGetActive / activeItem.v);
  8499. if (countItem > activeItem.count) {
  8500. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8501. console.log(activeItem);
  8502. return;
  8503. }
  8504.  
  8505. await Send(JSON.stringify({
  8506. calls: [{
  8507. name: "clanItemsForActivity",
  8508. args: {
  8509. items: {
  8510. [activeItem.type]: {
  8511. [activeItem.id]: countItem
  8512. }
  8513. }
  8514. },
  8515. ident: "body"
  8516. }]
  8517. })).then(e => {
  8518. /** TODO: Вывести потраченые предметы */
  8519. console.log(e);
  8520. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8521. });
  8522. }
  8523.  
  8524. async function buyHeroFragments() {
  8525. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8526. .then(e => e.results.map(n => n.result.response));
  8527. const inv = result[0];
  8528. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8529. const calls = [];
  8530.  
  8531. for (let shop of shops) {
  8532. const slots = Object.values(shop.slots);
  8533. for (const slot of slots) {
  8534. /* Уже куплено */
  8535. if (slot.bought) {
  8536. continue;
  8537. }
  8538. /* Не душа героя */
  8539. if (!('fragmentHero' in slot.reward)) {
  8540. continue;
  8541. }
  8542. const coin = Object.keys(slot.cost).pop();
  8543. const coinId = Object.keys(slot.cost[coin]).pop();
  8544. const stock = inv[coin][coinId] || 0;
  8545. /* Не хватает на покупку */
  8546. if (slot.cost[coin][coinId] > stock) {
  8547. continue;
  8548. }
  8549. inv[coin][coinId] -= slot.cost[coin][coinId];
  8550. calls.push({
  8551. name: "shopBuy",
  8552. args: {
  8553. shopId: shop.id,
  8554. slot: slot.id,
  8555. cost: slot.cost,
  8556. reward: slot.reward,
  8557. },
  8558. ident: `shopBuy_${shop.id}_${slot.id}`,
  8559. })
  8560. }
  8561. }
  8562.  
  8563. if (!calls.length) {
  8564. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8565. return;
  8566. }
  8567.  
  8568. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8569. if (!bought) {
  8570. console.log('что-то пошло не так')
  8571. return;
  8572. }
  8573.  
  8574. let countHeroSouls = 0;
  8575. for (const buy of bought) {
  8576. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8577. }
  8578. console.log(countHeroSouls, bought, calls);
  8579. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8580. }
  8581.  
  8582. /** Открыть платные сундуки в Запределье за 90 */
  8583. async function bossOpenChestPay() {
  8584. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8585. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8586. e.results.map((n) => n.result.response)
  8587. );
  8588. const user = info[0];
  8589. const boses = info[1];
  8590. const offers = info[2];
  8591. const time = info[3];
  8592. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8593. let discount = 1;
  8594. if (discountOffer && discountOffer.endTime > time) {
  8595. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8596. }
  8597. cost9chests = 540 * discount;
  8598. cost18chests = 1740 * discount;
  8599. costFirstChest = 90 * discount;
  8600. costSecondChest = 200 * discount;
  8601. const currentStarMoney = user.starMoney;
  8602. if (currentStarMoney < cost9chests) {
  8603. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8604. return;
  8605. }
  8606. const imgEmerald =
  8607. "<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='>";
  8608. if (currentStarMoney < cost9chests) {
  8609. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8610. return;
  8611. }
  8612. const buttons = [{ result: false, isClose: true }];
  8613. if (currentStarMoney >= cost9chests) {
  8614. buttons.push({
  8615. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8616. result: [costFirstChest, costFirstChest, 0],
  8617. });
  8618. }
  8619. if (currentStarMoney >= cost18chests) {
  8620. buttons.push({
  8621. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8622. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8623. });
  8624. }
  8625. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8626. if (!answer) {
  8627. return;
  8628. }
  8629. const callBoss = [];
  8630. let n = 0;
  8631. for (let boss of boses) {
  8632. const bossId = boss.id;
  8633. if (boss.chestNum != 2) {
  8634. continue;
  8635. }
  8636. const calls = [];
  8637. for (const starmoney of answer) {
  8638. calls.push({
  8639. name: 'bossOpenChest',
  8640. args: {
  8641. amount: 1,
  8642. bossId,
  8643. starmoney,
  8644. },
  8645. ident: 'bossOpenChest_' + ++n,
  8646. });
  8647. }
  8648. callBoss.push(calls);
  8649. }
  8650. if (!callBoss.length) {
  8651. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8652. return;
  8653. }
  8654. let count = 0;
  8655. let errors = 0;
  8656. for (const calls of callBoss) {
  8657. const result = await Send({ calls });
  8658. console.log(result);
  8659. if (result?.results) {
  8660. count += result.results.length;
  8661. } else {
  8662. errors++;
  8663. }
  8664. }
  8665. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8666. }
  8667.  
  8668. async function autoRaidAdventure() {
  8669. const calls = [
  8670. {
  8671. name: "userGetInfo",
  8672. args: {},
  8673. ident: "userGetInfo"
  8674. },
  8675. {
  8676. name: "adventure_raidGetInfo",
  8677. args: {},
  8678. ident: "adventure_raidGetInfo"
  8679. }
  8680. ];
  8681. const result = await Send(JSON.stringify({ calls }))
  8682. .then(e => e.results.map(n => n.result.response));
  8683.  
  8684. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8685. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8686. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8687.  
  8688. if (!portalSphere.amount || !adventureId) {
  8689. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8690. return;
  8691. }
  8692.  
  8693. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8694. { result: false, isClose: true },
  8695. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8696. ]));
  8697.  
  8698. if (!countRaid) {
  8699. return;
  8700. }
  8701.  
  8702. if (countRaid > portalSphere.amount) {
  8703. countRaid = portalSphere.amount;
  8704. }
  8705.  
  8706. const resultRaid = await Send(JSON.stringify({
  8707. calls: [...Array(countRaid)].map((e, i) => ({
  8708. name: "adventure_raid",
  8709. args: {
  8710. adventureId
  8711. },
  8712. ident: `body_${i}`
  8713. }))
  8714. })).then(e => e.results.map(n => n.result.response));
  8715.  
  8716. if (!resultRaid.length) {
  8717. console.log(resultRaid);
  8718. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8719. return;
  8720. }
  8721.  
  8722. console.log(resultRaid, adventureId, portalSphere.amount);
  8723. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8724. }
  8725.  
  8726. /** Вывести всю клановую статистику в консоль браузера */
  8727. async function clanStatistic() {
  8728. const copy = function (text) {
  8729. const copyTextarea = document.createElement("textarea");
  8730. copyTextarea.style.opacity = "0";
  8731. copyTextarea.textContent = text;
  8732. document.body.appendChild(copyTextarea);
  8733. copyTextarea.select();
  8734. document.execCommand("copy");
  8735. document.body.removeChild(copyTextarea);
  8736. delete copyTextarea;
  8737. }
  8738. const calls = [
  8739. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8740. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8741. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8742. ];
  8743.  
  8744. const result = await Send(JSON.stringify({ calls }));
  8745.  
  8746. const dataClanInfo = result.results[0].result.response;
  8747. const dataClanStat = result.results[1].result.response;
  8748. const dataClanLog = result.results[2].result.response;
  8749.  
  8750. const membersStat = {};
  8751. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8752. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8753. }
  8754.  
  8755. const joinStat = {};
  8756. historyLog = dataClanLog.history;
  8757. for (let j in historyLog) {
  8758. his = historyLog[j];
  8759. if (his.event == 'join') {
  8760. joinStat[his.userId] = his.ctime;
  8761. }
  8762. }
  8763.  
  8764. const infoArr = [];
  8765. const members = dataClanInfo.clan.members;
  8766. for (let n in members) {
  8767. var member = [
  8768. n,
  8769. members[n].name,
  8770. members[n].level,
  8771. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8772. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8773. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8774. membersStat[n].activity.reverse().join('\t'),
  8775. membersStat[n].adventureStat.reverse().join('\t'),
  8776. membersStat[n].clanGifts.reverse().join('\t'),
  8777. membersStat[n].clanWarStat.reverse().join('\t'),
  8778. membersStat[n].dungeonActivity.reverse().join('\t'),
  8779. ];
  8780. infoArr.push(member);
  8781. }
  8782. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8783. console.log(info);
  8784. copy(info);
  8785. setProgress(I18N('CLAN_STAT_COPY'), true);
  8786. }
  8787.  
  8788. async function buyInStoreForGold() {
  8789. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8790. const shops = result[0];
  8791. const user = result[1];
  8792. let gold = user.gold;
  8793. const calls = [];
  8794. if (shops[17]) {
  8795. const slots = shops[17].slots;
  8796. for (let i = 1; i <= 2; i++) {
  8797. if (!slots[i].bought) {
  8798. const costGold = slots[i].cost.gold;
  8799. if ((gold - costGold) < 0) {
  8800. continue;
  8801. }
  8802. gold -= costGold;
  8803. calls.push({
  8804. name: "shopBuy",
  8805. args: {
  8806. shopId: 17,
  8807. slot: i,
  8808. cost: slots[i].cost,
  8809. reward: slots[i].reward,
  8810. },
  8811. ident: 'body_' + i,
  8812. })
  8813. }
  8814. }
  8815. }
  8816. const slots = shops[1].slots;
  8817. for (let i = 4; i <= 6; i++) {
  8818. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8819. const costGold = slots[i].cost.gold;
  8820. if ((gold - costGold) < 0) {
  8821. continue;
  8822. }
  8823. gold -= costGold;
  8824. calls.push({
  8825. name: "shopBuy",
  8826. args: {
  8827. shopId: 1,
  8828. slot: i,
  8829. cost: slots[i].cost,
  8830. reward: slots[i].reward,
  8831. },
  8832. ident: 'body_' + i,
  8833. })
  8834. }
  8835. }
  8836.  
  8837. if (!calls.length) {
  8838. setProgress(I18N('NOTHING_BUY'), true);
  8839. return;
  8840. }
  8841.  
  8842. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8843. console.log(resultBuy);
  8844. const countBuy = resultBuy.length;
  8845. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8846. }
  8847.  
  8848. function rewardsAndMailFarm() {
  8849. return new Promise(function (resolve, reject) {
  8850. let questGetAllCall = {
  8851. calls: [{
  8852. name: "questGetAll",
  8853. args: {},
  8854. ident: "questGetAll"
  8855. }, {
  8856. name: "mailGetAll",
  8857. args: {},
  8858. ident: "mailGetAll"
  8859. }]
  8860. }
  8861. send(JSON.stringify(questGetAllCall), function (data) {
  8862. if (!data) return;
  8863. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8864. const questBattlePass = lib.getData('quest').battlePass;
  8865. const questChainBPass = lib.getData('battlePass').questChain;
  8866. const listBattlePass = lib.getData('battlePass').list;
  8867.  
  8868. const questAllFarmCall = {
  8869. calls: [],
  8870. };
  8871. const questIds = [];
  8872. for (let quest of questGetAll) {
  8873. if (quest.id >= 2001e4) {
  8874. continue;
  8875. }
  8876. if (quest.id > 1e6 && quest.id < 2e7) {
  8877. const questInfo = questBattlePass[quest.id];
  8878. const chain = questChainBPass[questInfo.chain];
  8879. if (chain.requirement?.battlePassTicket) {
  8880. continue;
  8881. }
  8882. const battlePass = listBattlePass[chain.battlePass];
  8883. const startTime = battlePass.startCondition.time.value * 1e3
  8884. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8885. if (startTime > Date.now() || endTime < Date.now()) {
  8886. continue;
  8887. }
  8888. }
  8889. if (quest.id >= 2e7) {
  8890. questIds.push(quest.id);
  8891. continue;
  8892. }
  8893. questAllFarmCall.calls.push({
  8894. name: 'questFarm',
  8895. args: {
  8896. questId: quest.id,
  8897. },
  8898. ident: `questFarm_${quest.id}`,
  8899. });
  8900. }
  8901.  
  8902. if (questIds.length) {
  8903. questAllFarmCall.calls.push({
  8904. name: 'quest_questsFarm',
  8905. args: { questIds },
  8906. ident: 'quest_questsFarm',
  8907. });
  8908. }
  8909.  
  8910. let letters = data?.results[1]?.result?.response?.letters;
  8911. letterIds = lettersFilter(letters);
  8912.  
  8913. if (letterIds.length) {
  8914. questAllFarmCall.calls.push({
  8915. name: 'mailFarm',
  8916. args: { letterIds },
  8917. ident: 'mailFarm',
  8918. });
  8919. }
  8920.  
  8921. if (!questAllFarmCall.calls.length) {
  8922. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8923. resolve();
  8924. return;
  8925. }
  8926.  
  8927. send(JSON.stringify(questAllFarmCall), async function (res) {
  8928. let countQuests = 0;
  8929. let countMail = 0;
  8930. let questsIds = [];
  8931. for (let call of res.results) {
  8932. if (call.ident.includes('questFarm')) {
  8933. countQuests++;
  8934. } else if (call.ident.includes('questsFarm')) {
  8935. countQuests += Object.keys(call.result.response).length;
  8936. } else if (call.ident.includes('mailFarm')) {
  8937. countMail = Object.keys(call.result.response).length;
  8938. }
  8939.  
  8940. const newQuests = call.result.newQuests;
  8941. if (newQuests) {
  8942. for (let quest of newQuests) {
  8943. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8944. questsIds.push(quest.id);
  8945. }
  8946. }
  8947. }
  8948. }
  8949. while (questsIds.length) {
  8950. const questIds = [];
  8951. const calls = [];
  8952. for (let questId of questsIds) {
  8953. if (questId < 1e6) {
  8954. calls.push({
  8955. name: 'questFarm',
  8956. args: {
  8957. questId,
  8958. },
  8959. ident: `questFarm_${questId}`,
  8960. });
  8961. countQuests++;
  8962. } else if (questId >= 2e7 && questId < 2001e4) {
  8963. questIds.push(questId);
  8964. countQuests++;
  8965. }
  8966. }
  8967. calls.push({
  8968. name: 'quest_questsFarm',
  8969. args: { questIds },
  8970. ident: 'body',
  8971. });
  8972. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8973. questsIds = [];
  8974. for (const result of results) {
  8975. const newQuests = result.newQuests;
  8976. if (newQuests) {
  8977. for (let quest of newQuests) {
  8978. if (quest.state == 2) {
  8979. questsIds.push(quest.id);
  8980. }
  8981. }
  8982. }
  8983. }
  8984. }
  8985. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8986. resolve();
  8987. });
  8988. });
  8989. })
  8990. }
  8991.  
  8992. class epicBrawl {
  8993. timeout = null;
  8994. time = null;
  8995.  
  8996. constructor() {
  8997. if (epicBrawl.inst) {
  8998. return epicBrawl.inst;
  8999. }
  9000. epicBrawl.inst = this;
  9001. return this;
  9002. }
  9003.  
  9004. runTimeout(func, timeDiff) {
  9005. const worker = new Worker(URL.createObjectURL(new Blob([`
  9006. self.onmessage = function(e) {
  9007. const timeDiff = e.data;
  9008.  
  9009. if (timeDiff > 0) {
  9010. setTimeout(() => {
  9011. self.postMessage(1);
  9012. self.close();
  9013. }, timeDiff);
  9014. }
  9015. };
  9016. `])));
  9017. worker.postMessage(timeDiff);
  9018. worker.onmessage = () => {
  9019. func();
  9020. };
  9021. return true;
  9022. }
  9023.  
  9024. timeDiff(date1, date2) {
  9025. const date1Obj = new Date(date1);
  9026. const date2Obj = new Date(date2);
  9027.  
  9028. const timeDiff = Math.abs(date2Obj - date1Obj);
  9029.  
  9030. const totalSeconds = timeDiff / 1000;
  9031. const minutes = Math.floor(totalSeconds / 60);
  9032. const seconds = Math.floor(totalSeconds % 60);
  9033.  
  9034. const formattedMinutes = String(minutes).padStart(2, '0');
  9035. const formattedSeconds = String(seconds).padStart(2, '0');
  9036.  
  9037. return `${formattedMinutes}:${formattedSeconds}`;
  9038. }
  9039.  
  9040. check() {
  9041. console.log(new Date(this.time))
  9042. if (Date.now() > this.time) {
  9043. this.timeout = null;
  9044. this.start()
  9045. return;
  9046. }
  9047. this.timeout = this.runTimeout(() => this.check(), 6e4);
  9048. return this.timeDiff(this.time, Date.now())
  9049. }
  9050.  
  9051. async start() {
  9052. if (this.timeout) {
  9053. const time = this.timeDiff(this.time, Date.now());
  9054. console.log(new Date(this.time))
  9055. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  9056. return;
  9057. }
  9058. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  9059. 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));
  9060. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  9061. this.time = (refill.lastRefill + 3600) * 1000
  9062. const attempts = refill.amount;
  9063. if (!attempts) {
  9064. console.log(new Date(this.time));
  9065. const time = this.check();
  9066. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  9067. return;
  9068. }
  9069.  
  9070. if (!teamInfo[0].epic_brawl) {
  9071. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  9072. return;
  9073. }
  9074.  
  9075. const args = {
  9076. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  9077. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  9078. favor: teamInfo[1].epic_brawl,
  9079. }
  9080.  
  9081. let wins = 0;
  9082. let coins = 0;
  9083. let streak = { progress: 0, nextStage: 0 };
  9084. for (let i = attempts; i > 0; i--) {
  9085. const info = await Send(JSON.stringify({
  9086. calls: [
  9087. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  9088. ]
  9089. })).then(e => e.results.map(n => n.result.response));
  9090.  
  9091. const { progress, result } = await Calc(info[1].battle);
  9092. 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));
  9093.  
  9094. const resultInfo = endResult[0].result;
  9095. streak = endResult[1];
  9096.  
  9097. wins += resultInfo.win;
  9098. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  9099.  
  9100. console.log(endResult[0].result)
  9101. if (endResult[1].progress == endResult[1].nextStage) {
  9102. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  9103. coins += farm.coin[39];
  9104. }
  9105.  
  9106. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9107. i, wins, attempts, coins,
  9108. progress: streak.progress,
  9109. nextStage: streak.nextStage,
  9110. end: '',
  9111. }), false, hideProgress);
  9112. }
  9113.  
  9114. console.log(new Date(this.time));
  9115. const time = this.check();
  9116. setProgress(I18N('EPIC_BRAWL_RESULT', {
  9117. wins, attempts, coins,
  9118. i: '',
  9119. progress: streak.progress,
  9120. nextStage: streak.nextStage,
  9121. end: I18N('ATTEMPT_ENDED', { time }),
  9122. }), false, hideProgress);
  9123. }
  9124. }
  9125. /* тест остановка подземки*/
  9126. function stopDungeon(e) {
  9127. stopDung = true;
  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. /** Набить килов в горниле душк */
  9147. async function bossRatingEventSouls() {
  9148. const data = await Send({
  9149. calls: [
  9150. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  9151. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  9152. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  9153. ]
  9154. });
  9155. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  9156. if (!bossEventInfo) {
  9157. setProgress('Эвент завершен', true);
  9158. return;
  9159. }
  9160.  
  9161. if (bossEventInfo.progress.score > 250) {
  9162. setProgress('Уже убито больше 250 врагов');
  9163. rewardBossRatingEventSouls();
  9164. return;
  9165. }
  9166. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  9167. const heroGetAllList = data.results[0].result.response;
  9168. const usedHeroes = bossEventInfo.progress.usedHeroes;
  9169. const heroList = [];
  9170.  
  9171. for (let heroId in heroGetAllList) {
  9172. let hero = heroGetAllList[heroId];
  9173. if (usedHeroes.includes(hero.id)) {
  9174. continue;
  9175. }
  9176. heroList.push(hero.id);
  9177. }
  9178.  
  9179. if (!heroList.length) {
  9180. setProgress('Нет героев', true);
  9181. return;
  9182. }
  9183.  
  9184. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  9185. const petLib = lib.getData('pet');
  9186. let count = 1;
  9187.  
  9188. for (const heroId of heroList) {
  9189. const args = {
  9190. heroes: [heroId],
  9191. pet
  9192. }
  9193. /** Поиск питомца для героя */
  9194. for (const petId of availablePets) {
  9195. if (petLib[petId].favorHeroes.includes(heroId)) {
  9196. args.favor = {
  9197. [heroId]: petId
  9198. }
  9199. break;
  9200. }
  9201. }
  9202.  
  9203. const calls = [{
  9204. name: "bossRatingEvent_startBattle",
  9205. args,
  9206. ident: "body"
  9207. }, {
  9208. name: "offerGetAll",
  9209. args: {},
  9210. ident: "offerGetAll"
  9211. }];
  9212.  
  9213. const res = await Send({ calls });
  9214. count++;
  9215.  
  9216. if ('error' in res) {
  9217. console.error(res.error);
  9218. setProgress('Перезагрузите игру и попробуйте позже', true);
  9219. return;
  9220. }
  9221.  
  9222. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  9223. if (eventInfo.progress.score > 250) {
  9224. break;
  9225. }
  9226. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  9227. }
  9228.  
  9229. rewardBossRatingEventSouls();
  9230. }
  9231. /** Сбор награды из Горнила Душ */
  9232. async function rewardBossRatingEventSouls() {
  9233. const data = await Send({
  9234. calls: [
  9235. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  9236. ]
  9237. });
  9238.  
  9239. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  9240. if (!bossEventInfo) {
  9241. setProgress('Эвент завершен', true);
  9242. return;
  9243. }
  9244.  
  9245. const farmedChests = bossEventInfo.progress.farmedChests;
  9246. const score = bossEventInfo.progress.score;
  9247. // setProgress('Количество убитых врагов: ' + score);
  9248. const revard = bossEventInfo.reward;
  9249. const calls = [];
  9250.  
  9251. let count = 0;
  9252. for (let i = 1; i < 10; i++) {
  9253. if (farmedChests.includes(i)) {
  9254. continue;
  9255. }
  9256. if (score < revard[i].score) {
  9257. break;
  9258. }
  9259. calls.push({
  9260. name: "bossRatingEvent_getReward",
  9261. args: {
  9262. rewardId: i
  9263. },
  9264. ident: "body_" + i
  9265. });
  9266. count++;
  9267. }
  9268. if (!count) {
  9269. setProgress('Нечего собирать', true);
  9270. return;
  9271. }
  9272.  
  9273. Send({ calls }).then(e => {
  9274. console.log(e);
  9275. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9276. })
  9277. }
  9278. /**
  9279. * Spin the Seer
  9280. *
  9281. * Покрутить провидца
  9282. */
  9283. async function rollAscension() {
  9284. const refillable = await Send({calls:[
  9285. {
  9286. name:"userGetInfo",
  9287. args:{},
  9288. ident:"userGetInfo"
  9289. }
  9290. ]}).then(e => e.results[0].result.response.refillable);
  9291. const i47 = refillable.find(i => i.id == 47);
  9292. if (i47?.amount) {
  9293. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9294. setProgress(I18N('DONE'), true);
  9295. } else {
  9296. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9297. }
  9298. }
  9299.  
  9300. /**
  9301. * Collect gifts for the New Year
  9302. *
  9303. * Собрать подарки на новый год
  9304. */
  9305. function getGiftNewYear() {
  9306. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9307. const gifts = e.results[0].result.response.gifts;
  9308. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9309. name: "newYearGiftOpen",
  9310. args: {
  9311. giftId: e.id
  9312. },
  9313. ident: `body_${e.id}`
  9314. }));
  9315. if (!calls.length) {
  9316. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9317. return;
  9318. }
  9319. Send({ calls }).then(e => {
  9320. console.log(e.results)
  9321. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9322. console.log(msg);
  9323. setProgress(msg, 5000);
  9324. });
  9325. })
  9326. }
  9327.  
  9328. async function updateArtifacts() {
  9329. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9330. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9331. { result: false, isClose: true }
  9332. ]);
  9333. if (!count) {
  9334. return;
  9335. }
  9336. const quest = new questRun;
  9337. await quest.autoInit();
  9338. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9339. const inventory = quest.questInfo['inventoryGet'];
  9340. const calls = [];
  9341. for (let i = count; i > 0; i--) {
  9342. const upArtifact = quest.getUpgradeArtifact();
  9343. if (!upArtifact.heroId) {
  9344. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9345. { msg: I18N('YES'), result: true },
  9346. { result: false, isClose: true }
  9347. ])) {
  9348. break;
  9349. } else {
  9350. return;
  9351. }
  9352. }
  9353. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9354. hero.artifacts[upArtifact.slotId].level++;
  9355. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9356. calls.push({
  9357. name: "heroArtifactLevelUp",
  9358. args: {
  9359. heroId: upArtifact.heroId,
  9360. slotId: upArtifact.slotId
  9361. },
  9362. ident: `heroArtifactLevelUp_${i}`
  9363. });
  9364. }
  9365.  
  9366. if (!calls.length) {
  9367. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9368. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9369. return;
  9370. }
  9371.  
  9372. await Send(JSON.stringify({ calls })).then(e => {
  9373. if ('error' in e) {
  9374. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9375. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9376. } else {
  9377. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9378. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9379. }
  9380. });
  9381. }
  9382.  
  9383. window.sign = a => {
  9384. const i = this['\x78\x79\x7a'];
  9385. 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'))
  9386. }
  9387.  
  9388. async function updateSkins() {
  9389. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9390. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9391. { result: false, isClose: true }
  9392. ]);
  9393. if (!count) {
  9394. return;
  9395. }
  9396.  
  9397. const quest = new questRun;
  9398. await quest.autoInit();
  9399. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9400. const inventory = quest.questInfo['inventoryGet'];
  9401. const calls = [];
  9402. for (let i = count; i > 0; i--) {
  9403. const upSkin = quest.getUpgradeSkin();
  9404. if (!upSkin.heroId) {
  9405. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9406. { msg: I18N('YES'), result: true },
  9407. { result: false, isClose: true }
  9408. ])) {
  9409. break;
  9410. } else {
  9411. return;
  9412. }
  9413. }
  9414. const hero = heroes.find(e => e.id == upSkin.heroId);
  9415. hero.skins[upSkin.skinId]++;
  9416. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9417. calls.push({
  9418. name: "heroSkinUpgrade",
  9419. args: {
  9420. heroId: upSkin.heroId,
  9421. skinId: upSkin.skinId
  9422. },
  9423. ident: `heroSkinUpgrade_${i}`
  9424. })
  9425. }
  9426.  
  9427. if (!calls.length) {
  9428. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9429. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9430. return;
  9431. }
  9432.  
  9433. await Send(JSON.stringify({ calls })).then(e => {
  9434. if ('error' in e) {
  9435. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9436. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9437. } else {
  9438. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9439. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9440. }
  9441. });
  9442. }
  9443.  
  9444. function getQuestionInfo(img, nameOnly = false) {
  9445. const libHeroes = Object.values(lib.data.hero);
  9446. const parts = img.split(':');
  9447. const id = parts[1];
  9448. switch (parts[0]) {
  9449. case 'titanArtifact_id':
  9450. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9451. case 'titan':
  9452. return cheats.translate("LIB_HERO_NAME_" + id);
  9453. case 'skill':
  9454. return cheats.translate("LIB_SKILL_" + id);
  9455. case 'inventoryItem_gear':
  9456. return cheats.translate("LIB_GEAR_NAME_" + id);
  9457. case 'inventoryItem_coin':
  9458. return cheats.translate("LIB_COIN_NAME_" + id);
  9459. case 'artifact':
  9460. if (nameOnly) {
  9461. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9462. }
  9463. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9464. return {
  9465. /** Как называется этот артефакт? */
  9466. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9467. /** Какому герою принадлежит этот артефакт? */
  9468. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9469. };
  9470. case 'hero':
  9471. if (nameOnly) {
  9472. return cheats.translate("LIB_HERO_NAME_" + id);
  9473. }
  9474. artifacts = lib.data.hero[id].artifacts;
  9475. return {
  9476. /** Как зовут этого героя? */
  9477. name: cheats.translate("LIB_HERO_NAME_" + id),
  9478. /** Какой артефакт принадлежит этому герою? */
  9479. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9480. };
  9481. }
  9482. }
  9483.  
  9484. function hintQuest(quest) {
  9485. const result = {};
  9486. if (quest?.questionIcon) {
  9487. const info = getQuestionInfo(quest.questionIcon);
  9488. if (info?.heroes) {
  9489. /** Какому герою принадлежит этот артефакт? */
  9490. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9491. }
  9492. if (info?.artifact) {
  9493. /** Какой артефакт принадлежит этому герою? */
  9494. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9495. }
  9496. if (typeof info == 'string') {
  9497. result.info = { name: info };
  9498. } else {
  9499. result.info = info;
  9500. }
  9501. }
  9502.  
  9503. if (quest.answers[0]?.answerIcon) {
  9504. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9505. }
  9506.  
  9507. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9508. return false;
  9509. }
  9510.  
  9511. let resultText = '';
  9512. if (result?.info) {
  9513. resultText += I18N('PICTURE') + result.info.name;
  9514. }
  9515. console.log(result);
  9516. if (result?.answer && result.answer.length) {
  9517. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9518. }
  9519.  
  9520. return resultText;
  9521. }
  9522.  
  9523. async function farmBattlePass() {
  9524. const isFarmReward = (reward) => {
  9525. return !(reward?.buff || reward?.fragmentHero || reward?.bundleHeroReward);
  9526. };
  9527. const battlePassProcess = (pass) => {
  9528. if (!pass.id) {return []}
  9529. const levels = Object.values(lib.data.battlePass.level).filter(x => x.battlePass == pass.id)
  9530. const last_level = levels[levels.length - 1];
  9531. let actual = Math.max(...levels.filter(p => pass.exp >= p.experience).map(p => p.level))
  9532. if (pass.exp > last_level.experience) {
  9533. actual = last_level.level + (pass.exp - last_level.experience) / last_level.experienceByLevel;
  9534. }
  9535. const calls = [];
  9536. for(let i = 1; i <= actual; i++) {
  9537. const level = i >= last_level.level ? last_level : levels.find(l => l.level === i);
  9538. const reward = {free: level?.freeReward, paid:level?.paidReward};
  9539. if (!pass.rewards[i]?.free && isFarmReward(reward.free)) {
  9540. const args = {level: i, free:true};
  9541. if (!pass.gold) { args.id = pass.id }
  9542. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_free_${args.id}_${i}` });
  9543. }
  9544. if (pass.ticket && !pass.rewards[i]?.paid && isFarmReward(reward.paid)) {
  9545. const args = {level: i, free:false};
  9546. if (!pass.gold) { args.id = pass.id}
  9547. calls.push({ name: 'battlePass_farmReward', args, ident: `${pass.gold ? 'body' : 'spesial'}_paid_${args.id}_${i}` });
  9548. }
  9549. }
  9550. return calls;
  9551. }
  9552. const passes = await Send({
  9553. calls: [
  9554. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9555. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9556. ],
  9557. }).then((e) => [{...e.results[0].result.response?.battlePass, gold: true}, ...Object.values(e.results[1].result.response)]);
  9558. const calls = passes.map(p => battlePassProcess(p)).flat()
  9559. if (!calls.length) {
  9560. setProgress(I18N('NOTHING_TO_COLLECT'));
  9561. return;
  9562. }
  9563.  
  9564. let results = await Send({calls});
  9565. if (results.error) {
  9566. console.log(results.error);
  9567. setProgress(I18N('SOMETHING_WENT_WRONG'));
  9568. } else {
  9569. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.results.length}), true);
  9570. }
  9571. }
  9572. async function sellHeroSoulsForGold() {
  9573. let { fragmentHero, heroes } = await Send({
  9574. calls: [
  9575. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9576. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9577. ],
  9578. })
  9579. .then((e) => e.results.map((r) => r.result.response))
  9580. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9581. const calls = [];
  9582. for (let i in fragmentHero) {
  9583. if (heroes[i] && heroes[i].star == 6) {
  9584. calls.push({
  9585. name: 'inventorySell',
  9586. args: {
  9587. type: 'hero',
  9588. libId: i,
  9589. amount: fragmentHero[i],
  9590. fragment: true,
  9591. },
  9592. ident: 'inventorySell_' + i,
  9593. });
  9594. }
  9595. }
  9596. if (!calls.length) {
  9597. console.log(0);
  9598. return 0;
  9599. }
  9600. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9601. const gold = rewards.reduce((e, a) => e + a, 0);
  9602. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9603. }
  9604.  
  9605. /**
  9606. * Attack of the minions of Asgard
  9607. *
  9608. * Атака прислужников Асгарда
  9609. */
  9610. function testRaidNodes() {
  9611. return new Promise((resolve, reject) => {
  9612. const tower = new executeRaidNodes(resolve, reject);
  9613. tower.start();
  9614. });
  9615. }
  9616.  
  9617. /**
  9618. * Attack of the minions of Asgard
  9619. *
  9620. * Атака прислужников Асгарда
  9621. */
  9622. function executeRaidNodes(resolve, reject) {
  9623. let raidData = {
  9624. teams: [],
  9625. favor: {},
  9626. nodes: [],
  9627. attempts: 0,
  9628. countExecuteBattles: 0,
  9629. cancelBattle: 0,
  9630. }
  9631.  
  9632. callsExecuteRaidNodes = {
  9633. calls: [{
  9634. name: "clanRaid_getInfo",
  9635. args: {},
  9636. ident: "clanRaid_getInfo"
  9637. }, {
  9638. name: "teamGetAll",
  9639. args: {},
  9640. ident: "teamGetAll"
  9641. }, {
  9642. name: "teamGetFavor",
  9643. args: {},
  9644. ident: "teamGetFavor"
  9645. }]
  9646. }
  9647.  
  9648. this.start = function () {
  9649. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9650. }
  9651.  
  9652. async function startRaidNodes(data) {
  9653. res = data.results;
  9654. clanRaidInfo = res[0].result.response;
  9655. teamGetAll = res[1].result.response;
  9656. teamGetFavor = res[2].result.response;
  9657.  
  9658. let index = 0;
  9659. let isNotFullPack = false;
  9660. for (let team of teamGetAll.clanRaid_nodes) {
  9661. if (team.length < 6) {
  9662. isNotFullPack = true;
  9663. }
  9664. raidData.teams.push({
  9665. data: {},
  9666. heroes: team.filter(id => id < 6000),
  9667. pet: team.filter(id => id >= 6000).pop(),
  9668. battleIndex: index++
  9669. });
  9670. }
  9671. raidData.favor = teamGetFavor.clanRaid_nodes;
  9672.  
  9673. if (isNotFullPack) {
  9674. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9675. { msg: I18N('BTN_NO'), result: true },
  9676. { msg: I18N('BTN_YES'), result: false },
  9677. ])) {
  9678. endRaidNodes('isNotFullPack');
  9679. return;
  9680. }
  9681. }
  9682.  
  9683. raidData.nodes = clanRaidInfo.nodes;
  9684. raidData.attempts = clanRaidInfo.attempts;
  9685. isCancalBattle = false;
  9686.  
  9687. checkNodes();
  9688. }
  9689.  
  9690. function getAttackNode() {
  9691. for (let nodeId in raidData.nodes) {
  9692. let node = raidData.nodes[nodeId];
  9693. let points = 0
  9694. for (team of node.teams) {
  9695. points += team.points;
  9696. }
  9697. let now = Date.now() / 1000;
  9698. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9699. let countTeam = node.teams.length;
  9700. delete raidData.nodes[nodeId];
  9701. return {
  9702. nodeId,
  9703. countTeam
  9704. };
  9705. }
  9706. }
  9707. return null;
  9708. }
  9709.  
  9710. function checkNodes() {
  9711. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9712. let nodeInfo = getAttackNode();
  9713. if (nodeInfo && raidData.attempts) {
  9714. startNodeBattles(nodeInfo);
  9715. return;
  9716. }
  9717.  
  9718. endRaidNodes('EndRaidNodes');
  9719. }
  9720.  
  9721. function startNodeBattles(nodeInfo) {
  9722. let {nodeId, countTeam} = nodeInfo;
  9723. let teams = raidData.teams.slice(0, countTeam);
  9724. let heroes = raidData.teams.map(e => e.heroes).flat();
  9725. let favor = {...raidData.favor};
  9726. for (let heroId in favor) {
  9727. if (!heroes.includes(+heroId)) {
  9728. delete favor[heroId];
  9729. }
  9730. }
  9731.  
  9732. let calls = [{
  9733. name: "clanRaid_startNodeBattles",
  9734. args: {
  9735. nodeId,
  9736. teams,
  9737. favor
  9738. },
  9739. ident: "body"
  9740. }];
  9741.  
  9742. send(JSON.stringify({calls}), resultNodeBattles);
  9743. }
  9744.  
  9745. function resultNodeBattles(e) {
  9746. if (e['error']) {
  9747. endRaidNodes('nodeBattlesError', e['error']);
  9748. return;
  9749. }
  9750.  
  9751. console.log(e);
  9752. let battles = e.results[0].result.response.battles;
  9753. let promises = [];
  9754. let battleIndex = 0;
  9755. for (let battle of battles) {
  9756. battle.battleIndex = battleIndex++;
  9757. promises.push(calcBattleResult(battle));
  9758. }
  9759.  
  9760. Promise.all(promises)
  9761. .then(results => {
  9762. const endResults = {};
  9763. let isAllWin = true;
  9764. for (let r of results) {
  9765. isAllWin &&= r.result.win;
  9766. }
  9767. if (!isAllWin) {
  9768. cancelEndNodeBattle(results[0]);
  9769. return;
  9770. }
  9771. raidData.countExecuteBattles = results.length;
  9772. let timeout = 500;
  9773. for (let r of results) {
  9774. setTimeout(endNodeBattle, timeout, r);
  9775. timeout += 500;
  9776. }
  9777. });
  9778. }
  9779. /**
  9780. * Returns the battle calculation promise
  9781. *
  9782. * Возвращает промис расчета боя
  9783. */
  9784. function calcBattleResult(battleData) {
  9785. return new Promise(function (resolve, reject) {
  9786. BattleCalc(battleData, "get_clanPvp", resolve);
  9787. });
  9788. }
  9789. /**
  9790. * Cancels the fight
  9791. *
  9792. * Отменяет бой
  9793. */
  9794. function cancelEndNodeBattle(r) {
  9795. const fixBattle = function (heroes) {
  9796. for (const ids in heroes) {
  9797. hero = heroes[ids];
  9798. hero.energy = random(1, 999);
  9799. if (hero.hp > 0) {
  9800. hero.hp = random(1, hero.hp);
  9801. }
  9802. }
  9803. }
  9804. fixBattle(r.progress[0].attackers.heroes);
  9805. fixBattle(r.progress[0].defenders.heroes);
  9806. endNodeBattle(r);
  9807. }
  9808. /**
  9809. * Ends the fight
  9810. *
  9811. * Завершает бой
  9812. */
  9813. function endNodeBattle(r) {
  9814. let nodeId = r.battleData.result.nodeId;
  9815. let battleIndex = r.battleData.battleIndex;
  9816. let calls = [{
  9817. name: "clanRaid_endNodeBattle",
  9818. args: {
  9819. nodeId,
  9820. battleIndex,
  9821. result: r.result,
  9822. progress: r.progress
  9823. },
  9824. ident: "body"
  9825. }]
  9826.  
  9827. SendRequest(JSON.stringify({calls}), battleResult);
  9828. }
  9829. /**
  9830. * Processing the results of the battle
  9831. *
  9832. * Обработка результатов боя
  9833. */
  9834. function battleResult(e) {
  9835. if (e['error']) {
  9836. endRaidNodes('missionEndError', e['error']);
  9837. return;
  9838. }
  9839. r = e.results[0].result.response;
  9840. if (r['error']) {
  9841. if (r.reason == "invalidBattle") {
  9842. raidData.cancelBattle++;
  9843. checkNodes();
  9844. } else {
  9845. endRaidNodes('missionEndError', e['error']);
  9846. }
  9847. return;
  9848. }
  9849.  
  9850. if (!(--raidData.countExecuteBattles)) {
  9851. raidData.attempts--;
  9852. checkNodes();
  9853. }
  9854. }
  9855. /**
  9856. * Completing a task
  9857. *
  9858. * Завершение задачи
  9859. */
  9860. function endRaidNodes(reason, info) {
  9861. isCancalBattle = true;
  9862. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9863. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9864. console.log(reason, info);
  9865. resolve();
  9866. }
  9867. }
  9868.  
  9869. /**
  9870. * Asgard Boss Attack Replay
  9871. *
  9872. * Повтор атаки босса Асгарда
  9873. */
  9874. function testBossBattle() {
  9875. return new Promise((resolve, reject) => {
  9876. const bossBattle = new executeBossBattle(resolve, reject);
  9877. bossBattle.start(lastBossBattle);
  9878. });
  9879. }
  9880.  
  9881. /**
  9882. * Asgard Boss Attack Replay
  9883. *
  9884. * Повтор атаки босса Асгарда
  9885. */
  9886. function executeBossBattle(resolve, reject) {
  9887. this.start = function (battleInfo) {
  9888. preCalcBattle(battleInfo);
  9889. }
  9890.  
  9891. function getBattleInfo(battle) {
  9892. return new Promise(function (resolve) {
  9893. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9894. BattleCalc(battle, getBattleType(battle.type), e => {
  9895. let extra = e.progress[0].defenders.heroes[1].extra;
  9896. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9897. });
  9898. });
  9899. }
  9900.  
  9901. function preCalcBattle(battle) {
  9902. let actions = [];
  9903. const countTestBattle = getInput('countTestBattle');
  9904. for (let i = 0; i < countTestBattle; i++) {
  9905. actions.push(getBattleInfo(battle, true));
  9906. }
  9907. Promise.all(actions)
  9908. .then(resultPreCalcBattle);
  9909. }
  9910.  
  9911. async function resultPreCalcBattle(damages) {
  9912. let maxDamage = 0;
  9913. let minDamage = 1e10;
  9914. let avgDamage = 0;
  9915. for (let damage of damages) {
  9916. avgDamage += damage
  9917. if (damage > maxDamage) {
  9918. maxDamage = damage;
  9919. }
  9920. if (damage < minDamage) {
  9921. minDamage = damage;
  9922. }
  9923. }
  9924. avgDamage /= damages.length;
  9925. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9926.  
  9927. await popup.confirm(
  9928. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9929. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9930. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9931. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9932. , [
  9933. { msg: I18N('BTN_OK'), result: 0},
  9934. ])
  9935. endBossBattle(I18N('BTN_CANCEL'));
  9936. }
  9937.  
  9938. /**
  9939. * Completing a task
  9940. *
  9941. * Завершение задачи
  9942. */
  9943. function endBossBattle(reason, info) {
  9944. console.log(reason, info);
  9945. resolve();
  9946. }
  9947. }
  9948.  
  9949. class FixBattle {
  9950. minTimer = 1.3;
  9951. maxTimer = 15.3;
  9952. constructor(battle, isTimeout = true) {
  9953. this.battle = structuredClone(battle);
  9954. this.isTimeout = isTimeout;
  9955. }
  9956. timeout(callback, timeout) {
  9957. if (this.isTimeout) {
  9958. this.worker.postMessage(timeout);
  9959. this.worker.onmessage = callback;
  9960. } else {
  9961. callback();
  9962. }
  9963. }
  9964. randTimer() {
  9965. return Math.random() * (this.maxTimer - this.minTimer + 1) + this.minTimer;
  9966. }
  9967. setAvgTime(startTime) {
  9968. this.fixTime += Date.now() - startTime;
  9969. this.avgTime = this.fixTime / this.count;
  9970. }
  9971. init() {
  9972. this.fixTime = 0;
  9973. this.lastTimer = 0;
  9974. this.index = 0;
  9975. this.lastBossDamage = 0;
  9976. this.bestResult = {
  9977. count: 0,
  9978. timer: 0,
  9979. value: 0,
  9980. result: null,
  9981. progress: null,
  9982. };
  9983. this.lastBattleResult = {
  9984. win: false,
  9985. };
  9986. this.worker = new Worker(
  9987. URL.createObjectURL(
  9988. new Blob([
  9989. `self.onmessage = function(e) {
  9990. const timeout = e.data;
  9991. setTimeout(() => {
  9992. self.postMessage(1);
  9993. }, timeout);
  9994. };`,
  9995. ])
  9996. )
  9997. );
  9998. }
  9999. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10000. this.endTime = endTime;
  10001. this.maxCount = maxCount;
  10002. this.init();
  10003. return await new Promise((resolve) => {
  10004. this.resolve = resolve;
  10005. this.count = 0;
  10006. this.loop();
  10007. });
  10008. }
  10009. endFix() {
  10010. this.bestResult.maxCount = this.count;
  10011. this.worker.terminate();
  10012. this.resolve(this.bestResult);
  10013. }
  10014. async loop() {
  10015. const start = Date.now();
  10016. if (this.isEndLoop()) {
  10017. this.endFix();
  10018. return;
  10019. }
  10020. this.count++;
  10021. try {
  10022. this.lastResult = await Calc(this.battle);
  10023. } catch (e) {
  10024. this.updateProgressTimer(this.index++);
  10025. this.timeout(this.loop.bind(this), 0);
  10026. return;
  10027. }
  10028. const { progress, result } = this.lastResult;
  10029. this.lastBattleResult = result;
  10030. this.lastBattleProgress = progress;
  10031. this.setAvgTime(start);
  10032. this.checkResult();
  10033. this.showResult();
  10034. this.updateProgressTimer();
  10035. this.timeout(this.loop.bind(this), 0);
  10036. }
  10037. isEndLoop() {
  10038. return this.count >= this.maxCount || this.endTime < Date.now();
  10039. }
  10040. updateProgressTimer(index = 0) {
  10041. this.lastTimer = this.randTimer();
  10042. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10043. }
  10044. showResult() {
  10045. console.log(
  10046. this.count,
  10047. this.avgTime.toFixed(2),
  10048. (this.endTime - Date.now()) / 1000,
  10049. this.lastTimer.toFixed(2),
  10050. this.lastBossDamage.toLocaleString(),
  10051. this.bestResult.value.toLocaleString()
  10052. );
  10053. }
  10054. checkResult() {
  10055. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10056. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10057. if (this.lastBossDamage > this.bestResult.value) {
  10058. this.bestResult = {
  10059. count: this.count,
  10060. timer: this.lastTimer,
  10061. value: this.lastBossDamage,
  10062. result: structuredClone(this.lastBattleResult),
  10063. progress: structuredClone(this.lastBattleProgress),
  10064. };
  10065. }
  10066. }
  10067. stopFix() {
  10068. this.endTime = 0;
  10069. }
  10070. }
  10071. class WinFixBattle extends FixBattle {
  10072. checkResult() {
  10073. if (this.lastBattleResult.win) {
  10074. this.bestResult = {
  10075. count: this.count,
  10076. timer: this.lastTimer,
  10077. value: this.lastBattleResult.stars,
  10078. result: structuredClone(this.lastBattleResult),
  10079. progress: structuredClone(this.lastBattleProgress),
  10080. battleTimer: this.lastResult.battleTimer,
  10081. };
  10082. }
  10083. }
  10084. setWinTimer(value) {
  10085. this.winTimer = value;
  10086. }
  10087. setMaxTimer(value) {
  10088. this.maxTimer = value;
  10089. }
  10090. randTimer() {
  10091. const min = 1.3;
  10092. const max = 30.3;
  10093. return Math.random() * (max - min + 1) + min;
  10094. }
  10095. isEndLoop() {
  10096. return super.isEndLoop() || this.bestResult.result?.win;
  10097. }
  10098. showResult() {
  10099. console.log(
  10100. this.count,
  10101. this.avgTime.toFixed(2),
  10102. (this.endTime - Date.now()) / 1000,
  10103. this.lastResult.battleTime,
  10104. this.lastTimer,
  10105. this.bestResult.value
  10106. );
  10107. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10108. const avgTime = this.avgTime.toFixed(2);
  10109. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10110. setProgress(msg, false, this.stopFix.bind(this));
  10111. }
  10112. }
  10113.  
  10114. class BestOrWinFixBattle extends WinFixBattle {
  10115. isNoMakeWin = false;
  10116. getState(result) {
  10117. let beforeSumFactor = 0;
  10118. const beforeHeroes = result.battleData.defenders[0];
  10119. for (let heroId in beforeHeroes) {
  10120. const hero = beforeHeroes[heroId];
  10121. const state = hero.state;
  10122. let factor = 1;
  10123. if (state) {
  10124. const hp = state.hp / (hero?.hp || 1);
  10125. const energy = state.energy / 1e3;
  10126. factor = hp + energy / 20;
  10127. }
  10128. beforeSumFactor += factor;
  10129. }
  10130. let afterSumFactor = 0;
  10131. const afterHeroes = result.progress[0].defenders.heroes;
  10132. for (let heroId in afterHeroes) {
  10133. const hero = afterHeroes[heroId];
  10134. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10135. const energy = hero.energy / 1e3;
  10136. const factor = hp + energy / 20;
  10137. afterSumFactor += factor;
  10138. }
  10139. return 100 - Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10140. }
  10141. setNoMakeWin(value) {
  10142. this.isNoMakeWin = value;
  10143. }
  10144. checkResult() {
  10145. const state = this.getState(this.lastResult);
  10146. console.log(state);
  10147. if (state > this.bestResult.value) {
  10148. if (!(this.isNoMakeWin && this.lastBattleResult.win)) {
  10149. this.bestResult = {
  10150. count: this.count,
  10151. timer: this.lastTimer,
  10152. value: state,
  10153. result: structuredClone(this.lastBattleResult),
  10154. progress: structuredClone(this.lastBattleProgress),
  10155. battleTimer: this.lastResult.battleTimer,
  10156. };
  10157. }
  10158. }
  10159. }
  10160. }
  10161.  
  10162. class BossFixBattle extends FixBattle {
  10163. showResult() {
  10164. super.showResult();
  10165. //setTimeout(() => {
  10166. const best = this.bestResult;
  10167. const maxDmg = best.value.toLocaleString();
  10168. const avgTime = this.avgTime.toLocaleString();
  10169. const msg = `${I18N('LETS_FIX')} ${this.count}/${this.maxCount}<br/>${maxDmg}<br/>${avgTime}ms`;
  10170. setProgress(msg, false, this.stopFix.bind(this));
  10171. //}, 0);
  10172. }
  10173. }
  10174.  
  10175. class DungeonFixBattle extends FixBattle {
  10176. init() {
  10177. super.init();
  10178. this.isTimeout = false;
  10179. }
  10180. setState() {
  10181. const result = this.lastResult;
  10182. let beforeSumFactor = 0;
  10183. const beforeHeroes = result.battleData.attackers;
  10184. for (let heroId in beforeHeroes) {
  10185. const hero = beforeHeroes[heroId];
  10186. const state = hero.state;
  10187. let factor = 1;
  10188. if (state) {
  10189. const hp = state.hp / (hero?.hp || 1);
  10190. const energy = state.energy / 1e3;
  10191. factor = hp + energy / 20;
  10192. }
  10193. beforeSumFactor += factor;
  10194. }
  10195. let afterSumFactor = 0;
  10196. const afterHeroes = result.progress[0].attackers.heroes;
  10197. for (let heroId in afterHeroes) {
  10198. const hero = afterHeroes[heroId];
  10199. const hp = hero.hp / (beforeHeroes[heroId]?.hp || 1);
  10200. const energy = hero.energy / 1e3;
  10201. const factor = hp + energy / 20;
  10202. afterSumFactor += factor;
  10203. }
  10204. this.lastState = Math.floor((afterSumFactor / beforeSumFactor) * 1e4) / 100;
  10205. }
  10206. checkResult() {
  10207. this.setState();
  10208. if (this.lastResult.result.win && this.lastState > this.bestResult.value) {
  10209. this.bestResult = {
  10210. count: this.count,
  10211. timer: this.lastTimer,
  10212. value: this.lastState,
  10213. result: this.lastResult.result,
  10214. progress: this.lastResult.progress,
  10215. };
  10216. }
  10217. }
  10218. showResult() {
  10219. console.log(
  10220. this.count,
  10221. this.avgTime.toFixed(2),
  10222. (this.endTime - Date.now()) / 1000,
  10223. this.lastTimer.toFixed(2),
  10224. this.lastState.toLocaleString(),
  10225. this.bestResult.value.toLocaleString()
  10226. );
  10227. }
  10228. }
  10229.  
  10230. const masterWsMixin = {
  10231. wsStart() {
  10232. const socket = new WebSocket(this.url);
  10233. socket.onopen = () => {
  10234. console.log('Connected to server');
  10235. // Пример создания новой задачи
  10236. const newTask = {
  10237. type: 'newTask',
  10238. battle: this.battle,
  10239. endTime: this.endTime - 1e4,
  10240. maxCount: this.maxCount,
  10241. };
  10242. socket.send(JSON.stringify(newTask));
  10243. };
  10244. socket.onmessage = this.onmessage.bind(this);
  10245. socket.onclose = () => {
  10246. console.log('Disconnected from server');
  10247. };
  10248. this.ws = socket;
  10249. },
  10250. onmessage(event) {
  10251. const data = JSON.parse(event.data);
  10252. switch (data.type) {
  10253. case 'newTask': {
  10254. console.log('newTask:', data);
  10255. this.id = data.id;
  10256. this.countExecutor = data.count;
  10257. break;
  10258. }
  10259. case 'getSolTask': {
  10260. console.log('getSolTask:', data);
  10261. this.endFix(data.solutions);
  10262. break;
  10263. }
  10264. case 'resolveTask': {
  10265. console.log('resolveTask:', data);
  10266. if (data.id === this.id && data.solutions.length === this.countExecutor) {
  10267. this.worker.terminate();
  10268. this.endFix(data.solutions);
  10269. }
  10270. break;
  10271. }
  10272. default:
  10273. console.log('Unknown message type:', data.type);
  10274. }
  10275. },
  10276. getTask() {
  10277. this.ws.send(
  10278. JSON.stringify({
  10279. type: 'getSolTask',
  10280. id: this.id,
  10281. })
  10282. );
  10283. },
  10284. };
  10285.  
  10286. /*
  10287. mFix = new action.masterFixBattle(battle)
  10288. await mFix.start(Date.now() + 6e4, 1);
  10289. */
  10290. class masterFixBattle extends FixBattle {
  10291. constructor(battle, url = 'wss://localho.st:3000') {
  10292. super(battle, true);
  10293. this.url = url;
  10294. }
  10295. async start(endTime, maxCount) {
  10296. this.endTime = endTime;
  10297. this.maxCount = maxCount;
  10298. this.init();
  10299. this.wsStart();
  10300. return await new Promise((resolve) => {
  10301. this.resolve = resolve;
  10302. const timeout = this.endTime - Date.now();
  10303. this.timeout(this.getTask.bind(this), timeout);
  10304. });
  10305. }
  10306. async endFix(solutions) {
  10307. this.ws.close();
  10308. let maxCount = 0;
  10309. for (const solution of solutions) {
  10310. maxCount += solution.maxCount;
  10311. if (solution.value > this.bestResult.value) {
  10312. this.bestResult = solution;
  10313. }
  10314. }
  10315. this.count = maxCount;
  10316. super.endFix();
  10317. }
  10318. }
  10319. Object.assign(masterFixBattle.prototype, masterWsMixin);
  10320. class masterWinFixBattle extends WinFixBattle {
  10321. constructor(battle, url = 'wss://localho.st:3000') {
  10322. super(battle, true);
  10323. this.url = url;
  10324. }
  10325. async start(endTime, maxCount) {
  10326. this.endTime = endTime;
  10327. this.maxCount = maxCount;
  10328. this.init();
  10329. this.wsStart();
  10330. return await new Promise((resolve) => {
  10331. this.resolve = resolve;
  10332. const timeout = this.endTime - Date.now();
  10333. this.timeout(this.getTask.bind(this), timeout);
  10334. });
  10335. }
  10336. async endFix(solutions) {
  10337. this.ws.close();
  10338. let maxCount = 0;
  10339. for (const solution of solutions) {
  10340. maxCount += solution.maxCount;
  10341. if (solution.value > this.bestResult.value) {
  10342. this.bestResult = solution;
  10343. }
  10344. }
  10345. this.count = maxCount;
  10346. super.endFix();
  10347. }
  10348. }
  10349. Object.assign(masterWinFixBattle.prototype, masterWsMixin);
  10350. const slaveWsMixin = {
  10351. wsStop() {
  10352. this.ws.close();
  10353. },
  10354. wsStart() {
  10355. const socket = new WebSocket(this.url);
  10356. socket.onopen = () => {
  10357. console.log('Connected to server');
  10358. };
  10359. socket.onmessage = this.onmessage.bind(this);
  10360. socket.onclose = () => {
  10361. console.log('Disconnected from server');
  10362. };
  10363. this.ws = socket;
  10364. },
  10365. async onmessage(event) {
  10366. const data = JSON.parse(event.data);
  10367. switch (data.type) {
  10368. case 'newTask': {
  10369. console.log('newTask:', data.task);
  10370. const { battle, endTime, maxCount } = data.task;
  10371. this.battle = battle;
  10372. const id = data.task.id;
  10373. const solution = await this.start(endTime, maxCount);
  10374. this.ws.send(
  10375. JSON.stringify({
  10376. type: 'resolveTask',
  10377. id,
  10378. solution,
  10379. })
  10380. );
  10381. break;
  10382. }
  10383. default:
  10384. console.log('Unknown message type:', data.type);
  10385. }
  10386. },
  10387. };
  10388. /*
  10389. sFix = new action.slaveFixBattle();
  10390. sFix.wsStart()
  10391. */
  10392. class slaveFixBattle extends FixBattle {
  10393. constructor(url = 'wss://localho.st:3000') {
  10394. super(null, false);
  10395. this.isTimeout = false;
  10396. this.url = url;
  10397. }
  10398. }
  10399. Object.assign(slaveFixBattle.prototype, slaveWsMixin);
  10400.  
  10401. class slaveWinFixBattle extends WinFixBattle {
  10402. constructor(url = 'wss://localho.st:3000') {
  10403. super(null, false);
  10404. this.isTimeout = false;
  10405. this.url = url;
  10406. }
  10407. }
  10408. Object.assign(slaveWinFixBattle.prototype, slaveWsMixin);
  10409. /**
  10410. * Auto-repeat attack
  10411. *
  10412. * Автоповтор атаки
  10413. */
  10414. function testAutoBattle() {
  10415. return new Promise((resolve, reject) => {
  10416. const bossBattle = new executeAutoBattle(resolve, reject);
  10417. bossBattle.start(lastBattleArg, lastBattleInfo);
  10418. });
  10419. }
  10420.  
  10421. /**
  10422. * Auto-repeat attack
  10423. *
  10424. * Автоповтор атаки
  10425. */
  10426. function executeAutoBattle(resolve, reject) {
  10427. let battleArg = {};
  10428. let countBattle = 0;
  10429. let countError = 0;
  10430. let findCoeff = 0;
  10431. let dataNotEeceived = 0;
  10432. let stopAutoBattle = false;
  10433.  
  10434. let isSetWinTimer = false;
  10435. 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>';
  10436. 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>';
  10437. 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>';
  10438.  
  10439. this.start = function (battleArgs, battleInfo) {
  10440. battleArg = battleArgs;
  10441. if (nameFuncStartBattle == 'invasion_bossStart') {
  10442. startBattle();
  10443. return;
  10444. }
  10445. preCalcBattle(battleInfo);
  10446. }
  10447. /**
  10448. * Returns a promise for combat recalculation
  10449. *
  10450. * Возвращает промис для прерасчета боя
  10451. */
  10452. function getBattleInfo(battle) {
  10453. return new Promise(function (resolve) {
  10454. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10455. Calc(battle).then(e => {
  10456. e.coeff = calcCoeff(e, 'defenders');
  10457. resolve(e);
  10458. });
  10459. });
  10460. }
  10461. /**
  10462. * Battle recalculation
  10463. *
  10464. * Прерасчет боя
  10465. */
  10466. function preCalcBattle(battle) {
  10467. let actions = [];
  10468. const countTestBattle = getInput('countTestBattle');
  10469. for (let i = 0; i < countTestBattle; i++) {
  10470. actions.push(getBattleInfo(battle));
  10471. }
  10472. Promise.all(actions)
  10473. .then(resultPreCalcBattle);
  10474. }
  10475. /**
  10476. * Processing the results of the battle recalculation
  10477. *
  10478. * Обработка результатов прерасчета боя
  10479. */
  10480. async function resultPreCalcBattle(results) {
  10481. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  10482. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  10483. if (countWin > 0) {
  10484. isCancalBattle = false;
  10485. startBattle();
  10486. return;
  10487. }
  10488.  
  10489. let minCoeff = 100;
  10490. let maxCoeff = -100;
  10491. let avgCoeff = 0;
  10492. results.forEach(e => {
  10493. if (e.coeff < minCoeff) minCoeff = e.coeff;
  10494. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  10495. avgCoeff += e.coeff;
  10496. });
  10497. avgCoeff /= results.length;
  10498.  
  10499. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10500. nameFuncStartBattle == 'bossAttack') {
  10501. const result = await popup.confirm(
  10502. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  10503. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10504. { msg: I18N('BTN_DO_IT'), result: true },
  10505. ])
  10506. if (result) {
  10507. isCancalBattle = false;
  10508. startBattle();
  10509. return;
  10510. }
  10511. setProgress(I18N('NOT_THIS_TIME'), true);
  10512. endAutoBattle('invasion_bossStart');
  10513. return;
  10514. }
  10515.  
  10516. const result = await popup.confirm(
  10517. I18N('VICTORY_IMPOSSIBLE') +
  10518. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  10519. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  10520. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  10521. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  10522. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  10523. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  10524. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  10525. ])
  10526. if (result) {
  10527. findCoeff = result;
  10528. isCancalBattle = false;
  10529. startBattle();
  10530. return;
  10531. }
  10532. setProgress(I18N('NOT_THIS_TIME'), true);
  10533. endAutoBattle(I18N('NOT_THIS_TIME'));
  10534. }
  10535.  
  10536. /**
  10537. * Calculation of the combat result coefficient
  10538. *
  10539. * Расчет коэфициента результата боя
  10540. */
  10541. function calcCoeff(result, packType) {
  10542. let beforeSumFactor = 0;
  10543. const beforePack = result.battleData[packType][0];
  10544. for (let heroId in beforePack) {
  10545. const hero = beforePack[heroId];
  10546. const state = hero.state;
  10547. let factor = 1;
  10548. if (state) {
  10549. const hp = state.hp / state.maxHp;
  10550. const energy = state.energy / 1e3;
  10551. factor = hp + energy / 20;
  10552. }
  10553. beforeSumFactor += factor;
  10554. }
  10555.  
  10556. let afterSumFactor = 0;
  10557. const afterPack = result.progress[0][packType].heroes;
  10558. for (let heroId in afterPack) {
  10559. const hero = afterPack[heroId];
  10560. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  10561. const hp = hero.hp / stateHp;
  10562. const energy = hero.energy / 1e3;
  10563. const factor = hp + energy / 20;
  10564. afterSumFactor += factor;
  10565. }
  10566. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  10567. return Math.round(resultCoeff * 1000) / 1000;
  10568. }
  10569. /**
  10570. * Start battle
  10571. *
  10572. * Начало боя
  10573. */
  10574. function startBattle() {
  10575. countBattle++;
  10576. const countMaxBattle = getInput('countAutoBattle');
  10577. // setProgress(countBattle + '/' + countMaxBattle);
  10578. if (countBattle > countMaxBattle) {
  10579. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  10580. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  10581. return;
  10582. }
  10583. if (stopAutoBattle) {
  10584. setProgress(I18N('STOPPED'), true);
  10585. endAutoBattle('STOPPED');
  10586. return;
  10587. }
  10588. send({calls: [{
  10589. name: nameFuncStartBattle,
  10590. args: battleArg,
  10591. ident: "body"
  10592. }]}, calcResultBattle);
  10593. }
  10594. /**
  10595. * Battle calculation
  10596. *
  10597. * Расчет боя
  10598. */
  10599. async function calcResultBattle(e) {
  10600. if ('error' in e) {
  10601. if (e.error.description === 'too many tries') {
  10602. invasionTimer += 100;
  10603. countBattle--;
  10604. countError++;
  10605. console.log(`Errors: ${countError}`, e.error);
  10606. startBattle();
  10607. return;
  10608. }
  10609. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  10610. { msg: I18N('BTN_OK'), result: false },
  10611. { msg: I18N('RELOAD_GAME'), result: true },
  10612. ]);
  10613. endAutoBattle('Error', e.error);
  10614. if (result) {
  10615. location.reload();
  10616. }
  10617. return;
  10618. }
  10619. let battle = e.results[0].result.response.battle
  10620. if (nameFuncStartBattle == 'towerStartBattle' ||
  10621. nameFuncStartBattle == 'bossAttack' ||
  10622. nameFuncStartBattle == 'invasion_bossStart') {
  10623. battle = e.results[0].result.response;
  10624. }
  10625. lastBattleInfo = battle;
  10626. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  10627. }
  10628. /**
  10629. * Processing the results of the battle
  10630. *
  10631. * Обработка результатов боя
  10632. */
  10633. async function resultBattle(e) {
  10634. const isWin = e.result.win;
  10635. if (isWin) {
  10636. endBattle(e, false);
  10637. return;
  10638. } else if (isChecked('tryFixIt_v2')) {
  10639. const cloneBattle = structuredClone(e.battleData);
  10640. const bFix = new WinFixBattle(cloneBattle);
  10641. let attempts = Infinity;
  10642. if (nameFuncStartBattle == 'invasion_bossStart' && !isSetWinTimer) {
  10643. let winTimer = await popup.confirm(`Secret number:`, [
  10644. { result: false, isClose: true },
  10645. { msg: 'Go', isInput: true, default: '0' },
  10646. ]);
  10647. winTimer = Number.parseFloat(winTimer);
  10648. if (winTimer) {
  10649. attempts = 5;
  10650. bFix.setWinTimer(winTimer);
  10651. }
  10652. isSetWinTimer = true;
  10653. }
  10654. let endTime = Date.now() + 6e4;
  10655. if (nameFuncStartBattle == 'invasion_bossStart') {
  10656. endTime = Date.now() + 6e4 * 4;
  10657. bFix.setMaxTimer(120.3);
  10658. }
  10659. const result = await bFix.start(endTime, attempts);
  10660. console.log(result);
  10661. if (result.value) {
  10662. endBattle(result, false);
  10663. return;
  10664. }
  10665. }
  10666. const countMaxBattle = getInput('countAutoBattle');
  10667. if (findCoeff) {
  10668. const coeff = calcCoeff(e, 'defenders');
  10669. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  10670. if (coeff > findCoeff) {
  10671. endBattle(e, false);
  10672. return;
  10673. }
  10674. } else {
  10675. if (nameFuncStartBattle == 'invasion_bossStart') {
  10676. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10677. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10678. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  10679. stopAutoBattle = true;
  10680. });
  10681. await new Promise((resolve) => setTimeout(resolve, 5000));
  10682. } else {
  10683. setProgress(`${countBattle}/${countMaxBattle}`);
  10684. }
  10685. }
  10686. if (nameFuncStartBattle == 'towerStartBattle' ||
  10687. nameFuncStartBattle == 'bossAttack' ||
  10688. nameFuncStartBattle == 'invasion_bossStart') {
  10689. startBattle();
  10690. return;
  10691. }
  10692. cancelEndBattle(e);
  10693. }
  10694. /**
  10695. * Cancel fight
  10696. *
  10697. * Отмена боя
  10698. */
  10699. function cancelEndBattle(r) {
  10700. const fixBattle = function (heroes) {
  10701. for (const ids in heroes) {
  10702. hero = heroes[ids];
  10703. hero.energy = random(1, 999);
  10704. if (hero.hp > 0) {
  10705. hero.hp = random(1, hero.hp);
  10706. }
  10707. }
  10708. }
  10709. fixBattle(r.progress[0].attackers.heroes);
  10710. fixBattle(r.progress[0].defenders.heroes);
  10711. endBattle(r, true);
  10712. }
  10713. /**
  10714. * End of the fight
  10715. *
  10716. * Завершение боя */
  10717. function endBattle(battleResult, isCancal) {
  10718. let calls = [{
  10719. name: nameFuncEndBattle,
  10720. args: {
  10721. result: battleResult.result,
  10722. progress: battleResult.progress
  10723. },
  10724. ident: "body"
  10725. }];
  10726.  
  10727. if (nameFuncStartBattle == 'invasion_bossStart') {
  10728. calls[0].args.id = lastBattleArg.id;
  10729. }
  10730.  
  10731. send(JSON.stringify({
  10732. calls
  10733. }), async e => {
  10734. console.log(e);
  10735. if (isCancal) {
  10736. startBattle();
  10737. return;
  10738. }
  10739.  
  10740. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10741. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10742. nameFuncStartBattle == 'bossAttack') {
  10743. const countMaxBattle = getInput('countAutoBattle');
  10744. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10745. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageModAndEnergyIncrease_any_99_100_300_99_1000_300 || 0;
  10746. let winTimer = '';
  10747. if (nameFuncStartBattle == 'invasion_bossStart') {
  10748. winTimer = '<br>Secret number: ' + battleResult.progress[0].attackers.input[5];
  10749. }
  10750. const result = await popup.confirm(
  10751. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10752. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10753. countBattle: svgAttempt + ' ' + countBattle,
  10754. countMaxBattle,}),
  10755. winTimer,
  10756. [
  10757. { msg: I18N('BTN_OK'), result: 0 },
  10758. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10759. { msg: I18N('RELOAD_GAME'), result: 2 },
  10760. ]);
  10761. if (result) {
  10762. if (result == 1) {
  10763. cheats.refreshGame();
  10764. }
  10765. if (result == 2) {
  10766. location.reload();
  10767. }
  10768. }
  10769.  
  10770. }
  10771. endAutoBattle(`${I18N('SUCCESS')}!`)
  10772. });
  10773. }
  10774. /**
  10775. * Completing a task
  10776. *
  10777. * Завершение задачи
  10778. */
  10779. function endAutoBattle(reason, info) {
  10780. isCancalBattle = true;
  10781. console.log(reason, info);
  10782. resolve();
  10783. }
  10784. }
  10785.  
  10786. function testDailyQuests() {
  10787. return new Promise((resolve, reject) => {
  10788. const quests = new dailyQuests(resolve, reject);
  10789. quests.init(questsInfo);
  10790. quests.start();
  10791. });
  10792. }
  10793.  
  10794. /**
  10795. * Automatic completion of daily quests
  10796. *
  10797. * Автоматическое выполнение ежедневных квестов
  10798. */
  10799. class dailyQuests {
  10800. /**
  10801. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10802. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10803. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10804. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10805. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10806. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10807. */
  10808. callsList = ['userGetInfo', 'heroGetAll', 'titanGetAll', 'inventoryGet', 'questGetAll', 'bossGetAll', 'missionGetAll'];
  10809.  
  10810. dataQuests = {
  10811. 10001: {
  10812. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10813. doItCall: () => {
  10814. const upgradeSkills = this.getUpgradeSkills();
  10815. return upgradeSkills.map(({ heroId, skill }, index) => ({
  10816. name: 'heroUpgradeSkill',
  10817. args: { heroId, skill },
  10818. ident: `heroUpgradeSkill_${index}`,
  10819. }));
  10820. },
  10821. isWeCanDo: () => {
  10822. const upgradeSkills = this.getUpgradeSkills();
  10823. let sumGold = 0;
  10824. for (const skill of upgradeSkills) {
  10825. sumGold += this.skillCost(skill.value);
  10826. if (!skill.heroId) {
  10827. return false;
  10828. }
  10829. }
  10830. return this.questInfo['userGetInfo'].gold > sumGold;
  10831. },
  10832. },
  10833. 10002: {
  10834. description: 'Пройди 10 миссий', // --------------
  10835. isWeCanDo: () => false,
  10836. },
  10837. 10003: {
  10838. description: 'Пройди 3 героические миссии', // ++++++++++++++++
  10839. isWeCanDo: () => {
  10840. const vipPoints = +this.questInfo.userGetInfo.vipPoints;
  10841. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10842. return (vipPoints > 100 || goldTicket) && this.getHeroicMissionId();
  10843. },
  10844. doItCall: () => {
  10845. const selectedMissionId = this.getHeroicMissionId();
  10846. const goldTicket = !!this.questInfo.inventoryGet.consumable[151];
  10847. const vipLevel = Math.max(...lib.data.level.vip.filter(l => l.vipPoints <= +this.questInfo.userGetInfo.vipPoints).map(l => l.level));
  10848. // Возвращаем массив команд для рейда
  10849. if (vipLevel >= 5 || goldTicket) {
  10850. return [{ name: 'missionRaid', args: { id: selectedMissionId, times: 3 }, ident: 'missionRaid_1' }];
  10851. } else {
  10852. return [
  10853. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_1' },
  10854. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_2' },
  10855. { name: 'missionRaid', args: { id: selectedMissionId, times: 1 }, ident: 'missionRaid_3' },
  10856. ];
  10857. }
  10858. },
  10859. },
  10860. 10004: {
  10861. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10862. isWeCanDo: () => false,
  10863. },
  10864. 10006: {
  10865. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10866. doItCall: () => [
  10867. {
  10868. name: 'refillableAlchemyUse',
  10869. args: { multi: false },
  10870. ident: 'refillableAlchemyUse',
  10871. },
  10872. ],
  10873. isWeCanDo: () => {
  10874. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10875. return starMoney >= 20;
  10876. },
  10877. },
  10878. 10007: {
  10879. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10880. doItCall: () => [{ name: 'gacha_open', args: { ident: 'heroGacha', free: true, pack: false }, ident: 'gacha_open' }],
  10881. isWeCanDo: () => {
  10882. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10883. return soulCrystal > 0;
  10884. },
  10885. },
  10886. /*10016: {
  10887. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10888. doItCall: () => [{ name: 'clanSendDailyGifts', args: {}, ident: 'clanSendDailyGifts' }],
  10889. isWeCanDo: () => true,
  10890. },*/
  10891. 10018: {
  10892. description: 'Используй зелье опыта', // ++++++++++++++++
  10893. doItCall: () => {
  10894. const expHero = this.getExpHero();
  10895. return [
  10896. {
  10897. name: 'consumableUseHeroXp',
  10898. args: {
  10899. heroId: expHero.heroId,
  10900. libId: expHero.libId,
  10901. amount: 1,
  10902. },
  10903. ident: 'consumableUseHeroXp',
  10904. },
  10905. ];
  10906. },
  10907. isWeCanDo: () => {
  10908. const expHero = this.getExpHero();
  10909. return expHero.heroId && expHero.libId;
  10910. },
  10911. },
  10912. 10019: {
  10913. description: 'Открой 1 сундук в Башне',
  10914. doItFunc: testTower,
  10915. isWeCanDo: () => false,
  10916. },
  10917. 10020: {
  10918. description: 'Открой 3 сундука в Запределье', // Готово
  10919. doItCall: () => {
  10920. return this.getOutlandChest();
  10921. },
  10922. isWeCanDo: () => {
  10923. const outlandChest = this.getOutlandChest();
  10924. return outlandChest.length > 0;
  10925. },
  10926. },
  10927. 10021: {
  10928. description: 'Собери 75 Титанита в Подземелье Гильдии',
  10929. isWeCanDo: () => false,
  10930. },
  10931. 10022: {
  10932. description: 'Собери 150 Титанита в Подземелье Гильдии',
  10933. doItFunc: testDungeon,
  10934. isWeCanDo: () => false,
  10935. },
  10936. 10023: {
  10937. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  10938. doItCall: () => {
  10939. const heroId = this.getHeroIdTitanGift();
  10940. return [
  10941. { name: 'heroTitanGiftLevelUp', args: { heroId }, ident: 'heroTitanGiftLevelUp' },
  10942. { name: 'heroTitanGiftDrop', args: { heroId }, ident: 'heroTitanGiftDrop' },
  10943. ];
  10944. },
  10945. isWeCanDo: () => {
  10946. const heroId = this.getHeroIdTitanGift();
  10947. return heroId;
  10948. },
  10949. },
  10950. 10024: {
  10951. description: 'Повысь уровень любого артефакта один раз', // Готово
  10952. doItCall: () => {
  10953. const upArtifact = this.getUpgradeArtifact();
  10954. return [
  10955. {
  10956. name: 'heroArtifactLevelUp',
  10957. args: {
  10958. heroId: upArtifact.heroId,
  10959. slotId: upArtifact.slotId,
  10960. },
  10961. ident: `heroArtifactLevelUp`,
  10962. },
  10963. ];
  10964. },
  10965. isWeCanDo: () => {
  10966. const upgradeArtifact = this.getUpgradeArtifact();
  10967. return upgradeArtifact.heroId;
  10968. },
  10969. },
  10970. 10025: {
  10971. description: 'Начни 1 Экспедицию',
  10972. doItFunc: checkExpedition,
  10973. isWeCanDo: () => false,
  10974. },
  10975. 10026: {
  10976. description: 'Начни 4 Экспедиции', // --------------
  10977. doItFunc: checkExpedition,
  10978. isWeCanDo: () => false,
  10979. },
  10980. 10027: {
  10981. description: 'Победи в 1 бою Турнира Стихий',
  10982. doItFunc: testTitanArena,
  10983. isWeCanDo: () => false,
  10984. },
  10985. 10028: {
  10986. description: 'Повысь уровень любого артефакта титанов', // Готово
  10987. doItCall: () => {
  10988. const upTitanArtifact = this.getUpgradeTitanArtifact();
  10989. return [
  10990. {
  10991. name: 'titanArtifactLevelUp',
  10992. args: {
  10993. titanId: upTitanArtifact.titanId,
  10994. slotId: upTitanArtifact.slotId,
  10995. },
  10996. ident: `titanArtifactLevelUp`,
  10997. },
  10998. ];
  10999. },
  11000. isWeCanDo: () => {
  11001. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  11002. return upgradeTitanArtifact.titanId;
  11003. },
  11004. },
  11005. 10029: {
  11006. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  11007. doItCall: () => [{ name: 'titanArtifactChestOpen', args: { amount: 1, free: true }, ident: 'titanArtifactChestOpen' }],
  11008. isWeCanDo: () => {
  11009. return this.questInfo['inventoryGet']?.consumable[55] > 0;
  11010. },
  11011. },
  11012. 10030: {
  11013. description: 'Улучши облик любого героя 1 раз', // Готово
  11014. doItCall: () => {
  11015. const upSkin = this.getUpgradeSkin();
  11016. return [
  11017. {
  11018. name: 'heroSkinUpgrade',
  11019. args: {
  11020. heroId: upSkin.heroId,
  11021. skinId: upSkin.skinId,
  11022. },
  11023. ident: `heroSkinUpgrade`,
  11024. },
  11025. ];
  11026. },
  11027. isWeCanDo: () => {
  11028. const upgradeSkin = this.getUpgradeSkin();
  11029. return upgradeSkin.heroId;
  11030. },
  11031. },
  11032. 10031: {
  11033. description: 'Победи в 6 боях Турнира Стихий', // --------------
  11034. doItFunc: testTitanArena,
  11035. isWeCanDo: () => false,
  11036. },
  11037. 10043: {
  11038. description: 'Начни или присоеденись к Приключению', // --------------
  11039. isWeCanDo: () => false,
  11040. },
  11041. 10044: {
  11042. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  11043. doItCall: () => [{ name: 'pet_chestOpen', args: { amount: 1, paid: false }, ident: 'pet_chestOpen' }],
  11044. isWeCanDo: () => {
  11045. return this.questInfo['inventoryGet']?.consumable[90] > 0;
  11046. },
  11047. },
  11048. 10046: {
  11049. /**
  11050. * TODO: Watch Adventure
  11051. * TODO: Смотреть приключение
  11052. */
  11053. description: 'Открой 3 сундука в Приключениях',
  11054. isWeCanDo: () => false,
  11055. },
  11056. 10047: {
  11057. description: 'Набери 150 очков активности в Гильдии', // Готово
  11058. doItCall: () => {
  11059. const enchantRune = this.getEnchantRune();
  11060. return [
  11061. {
  11062. name: 'heroEnchantRune',
  11063. args: {
  11064. heroId: enchantRune.heroId,
  11065. tier: enchantRune.tier,
  11066. items: {
  11067. consumable: { [enchantRune.itemId]: 1 },
  11068. },
  11069. },
  11070. ident: `heroEnchantRune`,
  11071. },
  11072. ];
  11073. },
  11074. isWeCanDo: () => {
  11075. const userInfo = this.questInfo['userGetInfo'];
  11076. const enchantRune = this.getEnchantRune();
  11077. return enchantRune.heroId && userInfo.gold > 1e3;
  11078. },
  11079. },
  11080. };
  11081.  
  11082. constructor(resolve, reject, questInfo) {
  11083. this.resolve = resolve;
  11084. this.reject = reject;
  11085. }
  11086.  
  11087. init(questInfo) {
  11088. this.questInfo = questInfo;
  11089. this.isAuto = false;
  11090. }
  11091.  
  11092. async autoInit(isAuto) {
  11093. this.isAuto = isAuto || false;
  11094. const quests = {};
  11095. const calls = this.callsList.map((name) => ({
  11096. name,
  11097. args: {},
  11098. ident: name,
  11099. }));
  11100. const result = await Send(JSON.stringify({ calls })).then((e) => e.results);
  11101. for (const call of result) {
  11102. quests[call.ident] = call.result.response;
  11103. }
  11104. this.questInfo = quests;
  11105. }
  11106.  
  11107. async start() {
  11108. const weCanDo = [];
  11109. const selectedActions = getSaveVal('selectedActions', {});
  11110. for (let quest of this.questInfo['questGetAll']) {
  11111. if (quest.id in this.dataQuests && quest.state == 1) {
  11112. if (!selectedActions[quest.id]) {
  11113. selectedActions[quest.id] = {
  11114. checked: false,
  11115. };
  11116. }
  11117. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  11118. if (!isWeCanDo.call(this)) {
  11119. continue;
  11120. }
  11121. weCanDo.push({
  11122. name: quest.id,
  11123. label: I18N(`QUEST_${quest.id}`),
  11124. checked: selectedActions[quest.id].checked,
  11125. });
  11126. }
  11127. }
  11128.  
  11129. if (!weCanDo.length) {
  11130. this.end(I18N('NOTHING_TO_DO'));
  11131. return;
  11132. }
  11133.  
  11134. console.log(weCanDo);
  11135. let taskList = [];
  11136. if (this.isAuto) {
  11137. taskList = weCanDo;
  11138. } else {
  11139. const answer = await popup.confirm(
  11140. `${I18N('YOU_CAN_COMPLETE')}:`,
  11141. [
  11142. { msg: I18N('BTN_DO_IT'), result: true },
  11143. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11144. ],
  11145. weCanDo
  11146. );
  11147. if (!answer) {
  11148. this.end('');
  11149. return;
  11150. }
  11151. taskList = popup.getCheckBoxes();
  11152. taskList.forEach((e) => {
  11153. selectedActions[e.name].checked = e.checked;
  11154. });
  11155. setSaveVal('selectedActions', selectedActions);
  11156. }
  11157.  
  11158. const calls = [];
  11159. let countChecked = 0;
  11160. for (const task of taskList) {
  11161. if (task.checked) {
  11162. countChecked++;
  11163. const quest = this.dataQuests[task.name];
  11164. console.log(quest.description);
  11165.  
  11166. if (quest.doItCall) {
  11167. const doItCall = quest.doItCall.call(this);
  11168. calls.push(...doItCall);
  11169. }
  11170. }
  11171. }
  11172.  
  11173. if (!countChecked) {
  11174. this.end(I18N('NOT_QUEST_COMPLETED'));
  11175. return;
  11176. }
  11177.  
  11178. const result = await Send(JSON.stringify({ calls }));
  11179. if (result.error) {
  11180. console.error(result.error, result.error.call);
  11181. }
  11182. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  11183. }
  11184.  
  11185. errorHandling(error) {
  11186. //console.error(error);
  11187. let errorInfo = error.toString() + '\n';
  11188. try {
  11189. const errorStack = error.stack.split('\n');
  11190. const endStack = errorStack.map((e) => e.split('@')[0]).indexOf('testDoYourBest');
  11191. errorInfo += errorStack.slice(0, endStack).join('\n');
  11192. } catch (e) {
  11193. errorInfo += error.stack;
  11194. }
  11195. copyText(errorInfo);
  11196. }
  11197.  
  11198. skillCost(lvl) {
  11199. return 573 * lvl ** 0.9 + lvl ** 2.379;
  11200. }
  11201.  
  11202. getUpgradeSkills() {
  11203. const heroes = Object.values(this.questInfo['heroGetAll']);
  11204. const upgradeSkills = [
  11205. { heroId: 0, slotId: 0, value: 130 },
  11206. { heroId: 0, slotId: 0, value: 130 },
  11207. { heroId: 0, slotId: 0, value: 130 },
  11208. ];
  11209. const skillLib = lib.getData('skill');
  11210. /**
  11211. * color - 1 (белый) открывает 1 навык
  11212. * color - 2 (зеленый) открывает 2 навык
  11213. * color - 4 (синий) открывает 3 навык
  11214. * color - 7 (фиолетовый) открывает 4 навык
  11215. */
  11216. const colors = [1, 2, 4, 7];
  11217. for (const hero of heroes) {
  11218. const level = hero.level;
  11219. const color = hero.color;
  11220. for (let skillId in hero.skills) {
  11221. const tier = skillLib[skillId].tier;
  11222. const sVal = hero.skills[skillId];
  11223. if (color < colors[tier] || tier < 1 || tier > 4) {
  11224. continue;
  11225. }
  11226. for (let upSkill of upgradeSkills) {
  11227. if (sVal < upSkill.value && sVal < level) {
  11228. upSkill.value = sVal;
  11229. upSkill.heroId = hero.id;
  11230. upSkill.skill = tier;
  11231. break;
  11232. }
  11233. }
  11234. }
  11235. }
  11236. return upgradeSkills;
  11237. }
  11238.  
  11239. getUpgradeArtifact() {
  11240. const heroes = Object.values(this.questInfo['heroGetAll']);
  11241. const inventory = this.questInfo['inventoryGet'];
  11242. const upArt = { heroId: 0, slotId: 0, level: 100 };
  11243.  
  11244. const heroLib = lib.getData('hero');
  11245. const artifactLib = lib.getData('artifact');
  11246.  
  11247. for (const hero of heroes) {
  11248. const heroInfo = heroLib[hero.id];
  11249. const level = hero.level;
  11250. if (level < 20) {
  11251. continue;
  11252. }
  11253.  
  11254. for (let slotId in hero.artifacts) {
  11255. const art = hero.artifacts[slotId];
  11256. /* Текущая звезданость арта */
  11257. const star = art.star;
  11258. if (!star) {
  11259. continue;
  11260. }
  11261. /* Текущий уровень арта */
  11262. const level = art.level;
  11263. if (level >= 100) {
  11264. continue;
  11265. }
  11266. /* Идентификатор арта в библиотеке */
  11267. const artifactId = heroInfo.artifacts[slotId];
  11268. const artInfo = artifactLib.id[artifactId];
  11269. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  11270.  
  11271. const costCurrency = Object.keys(costNextLevel).pop();
  11272. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11273. const costId = costValues[0];
  11274. const costValue = +costValues[1];
  11275.  
  11276. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11277. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  11278. upArt.level = level;
  11279. upArt.heroId = hero.id;
  11280. upArt.slotId = slotId;
  11281. upArt.costCurrency = costCurrency;
  11282. upArt.costId = costId;
  11283. upArt.costValue = costValue;
  11284. }
  11285. }
  11286. }
  11287. return upArt;
  11288. }
  11289.  
  11290. getUpgradeSkin() {
  11291. const heroes = Object.values(this.questInfo['heroGetAll']);
  11292. const inventory = this.questInfo['inventoryGet'];
  11293. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  11294.  
  11295. const skinLib = lib.getData('skin');
  11296.  
  11297. for (const hero of heroes) {
  11298. const level = hero.level;
  11299. if (level < 20) {
  11300. continue;
  11301. }
  11302.  
  11303. for (let skinId in hero.skins) {
  11304. /* Текущий уровень скина */
  11305. const level = hero.skins[skinId];
  11306. if (level >= 60) {
  11307. continue;
  11308. }
  11309. /* Идентификатор скина в библиотеке */
  11310. const skinInfo = skinLib[skinId];
  11311. if (!skinInfo.statData.levels?.[level + 1]) {
  11312. continue;
  11313. }
  11314. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  11315.  
  11316. const costCurrency = Object.keys(costNextLevel).pop();
  11317. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  11318. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  11319.  
  11320. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11321. if (level < upSkin.level && costValue < upSkin.cost && inventory[costCurrency][costCurrencyId] >= costValue) {
  11322. upSkin.cost = costValue;
  11323. upSkin.level = level;
  11324. upSkin.heroId = hero.id;
  11325. upSkin.skinId = skinId;
  11326. upSkin.costCurrency = costCurrency;
  11327. upSkin.costCurrencyId = costCurrencyId;
  11328. }
  11329. }
  11330. }
  11331. return upSkin;
  11332. }
  11333.  
  11334. getUpgradeTitanArtifact() {
  11335. const titans = Object.values(this.questInfo['titanGetAll']);
  11336. const inventory = this.questInfo['inventoryGet'];
  11337. const userInfo = this.questInfo['userGetInfo'];
  11338. const upArt = { titanId: 0, slotId: 0, level: 120 };
  11339.  
  11340. const titanLib = lib.getData('titan');
  11341. const artTitanLib = lib.getData('titanArtifact');
  11342.  
  11343. for (const titan of titans) {
  11344. const titanInfo = titanLib[titan.id];
  11345. // const level = titan.level
  11346. // if (level < 20) {
  11347. // continue;
  11348. // }
  11349.  
  11350. for (let slotId in titan.artifacts) {
  11351. const art = titan.artifacts[slotId];
  11352. /* Текущая звезданость арта */
  11353. const star = art.star;
  11354. if (!star) {
  11355. continue;
  11356. }
  11357. /* Текущий уровень арта */
  11358. const level = art.level;
  11359. if (level >= 120) {
  11360. continue;
  11361. }
  11362. /* Идентификатор арта в библиотеке */
  11363. const artifactId = titanInfo.artifacts[slotId];
  11364. const artInfo = artTitanLib.id[artifactId];
  11365. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  11366.  
  11367. const costCurrency = Object.keys(costNextLevel).pop();
  11368. let costValue = 0;
  11369. let currentValue = 0;
  11370. if (costCurrency == 'gold') {
  11371. costValue = costNextLevel[costCurrency];
  11372. currentValue = userInfo.gold;
  11373. } else {
  11374. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  11375. const costId = costValues[0];
  11376. costValue = +costValues[1];
  11377. currentValue = inventory[costCurrency][costId];
  11378. }
  11379.  
  11380. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11381. if (level < upArt.level && currentValue >= costValue) {
  11382. upArt.level = level;
  11383. upArt.titanId = titan.id;
  11384. upArt.slotId = slotId;
  11385. break;
  11386. }
  11387. }
  11388. }
  11389. return upArt;
  11390. }
  11391.  
  11392. getEnchantRune() {
  11393. const heroes = Object.values(this.questInfo['heroGetAll']);
  11394. const inventory = this.questInfo['inventoryGet'];
  11395. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  11396. for (let i = 1; i <= 4; i++) {
  11397. if (inventory.consumable[i] > 0) {
  11398. enchRune.itemId = i;
  11399. break;
  11400. }
  11401. return enchRune;
  11402. }
  11403.  
  11404. const runeLib = lib.getData('rune');
  11405. const runeLvls = Object.values(runeLib.level);
  11406. /**
  11407. * color - 4 (синий) открывает 1 и 2 символ
  11408. * color - 7 (фиолетовый) открывает 3 символ
  11409. * color - 8 (фиолетовый +1) открывает 4 символ
  11410. * color - 9 (фиолетовый +2) открывает 5 символ
  11411. */
  11412. // TODO: кажется надо учесть уровень команды
  11413. const colors = [4, 4, 7, 8, 9];
  11414. for (const hero of heroes) {
  11415. const color = hero.color;
  11416.  
  11417.  
  11418. for (let runeTier in hero.runes) {
  11419. /* Проверка на доступность руны */
  11420. if (color < colors[runeTier]) {
  11421. continue;
  11422. }
  11423. /* Текущий опыт руны */
  11424. const exp = hero.runes[runeTier];
  11425. if (exp >= 43750) {
  11426. continue;
  11427. }
  11428.  
  11429. let level = 0;
  11430. if (exp) {
  11431. for (let lvl of runeLvls) {
  11432. if (exp >= lvl.enchantValue) {
  11433. level = lvl.level;
  11434. } else {
  11435. break;
  11436. }
  11437. }
  11438. }
  11439. /** Уровень героя необходимый для уровня руны */
  11440. const heroLevel = runeLib.level[level].heroLevel;
  11441. if (hero.level < heroLevel) {
  11442. continue;
  11443. }
  11444.  
  11445. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  11446. if (exp < enchRune.exp) {
  11447. enchRune.exp = exp;
  11448. enchRune.heroId = hero.id;
  11449. enchRune.tier = runeTier;
  11450. break;
  11451. }
  11452. }
  11453. }
  11454. return enchRune;
  11455. }
  11456.  
  11457. getOutlandChest() {
  11458. const bosses = this.questInfo['bossGetAll'];
  11459. const calls = [];
  11460. for (let boss of bosses) {
  11461. if (boss.mayRaid) {
  11462. calls.push({
  11463. name: 'bossRaid',
  11464. args: {
  11465. bossId: boss.id,
  11466. },
  11467. ident: 'bossRaid_' + boss.id,
  11468. });
  11469. calls.push({
  11470. name: 'bossOpenChest',
  11471. args: {
  11472. bossId: boss.id,
  11473. amount: 1,
  11474. starmoney: 0,
  11475. },
  11476. ident: 'bossOpenChest_' + boss.id,
  11477. });
  11478. } else if (boss.chestId == 1) {
  11479. calls.push({
  11480. name: 'bossOpenChest',
  11481. args: {
  11482. bossId: boss.id,
  11483. amount: 1,
  11484. starmoney: 0,
  11485. },
  11486. ident: 'bossOpenChest_' + boss.id,
  11487. });
  11488. }
  11489. }
  11490. return calls;
  11491. }
  11492.  
  11493. getExpHero() {
  11494. const heroes = Object.values(this.questInfo['heroGetAll']);
  11495. const inventory = this.questInfo['inventoryGet'];
  11496. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  11497. /** зелья опыта (consumable 9, 10, 11, 12) */
  11498. for (let i = 9; i <= 12; i++) {
  11499. if (inventory.consumable[i]) {
  11500. expHero.libId = i;
  11501. break;
  11502. }
  11503. }
  11504.  
  11505. for (const hero of heroes) {
  11506. const exp = hero.xp;
  11507. if (exp < expHero.exp) {
  11508. expHero.heroId = hero.id;
  11509. }
  11510. }
  11511. return expHero;
  11512. }
  11513.  
  11514. getHeroIdTitanGift() {
  11515. const heroes = Object.values(this.questInfo['heroGetAll']);
  11516. const inventory = this.questInfo['inventoryGet'];
  11517. const user = this.questInfo['userGetInfo'];
  11518. const titanGiftLib = lib.getData('titanGift');
  11519. /** Искры */
  11520. const titanGift = inventory.consumable[24];
  11521. let heroId = 0;
  11522. let minLevel = 30;
  11523.  
  11524. if (titanGift < 250 || user.gold < 7000) {
  11525. return 0;
  11526. }
  11527.  
  11528. for (const hero of heroes) {
  11529. if (hero.titanGiftLevel >= 30) {
  11530. continue;
  11531. }
  11532.  
  11533. if (!hero.titanGiftLevel) {
  11534. return hero.id;
  11535. }
  11536.  
  11537. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  11538. if (minLevel > hero.titanGiftLevel && titanGift >= cost.consumable[24] && user.gold >= cost.gold) {
  11539. minLevel = hero.titanGiftLevel;
  11540. heroId = hero.id;
  11541. }
  11542. }
  11543.  
  11544. return heroId;
  11545. }
  11546. getHeroicMissionId() {
  11547. // Получаем доступные миссии с 3 звездами
  11548. const availableMissionsToRaid = Object.values(this.questInfo.missionGetAll)
  11549. .filter((mission) => mission.stars === 3)
  11550. .map((mission) => mission.id);
  11551. // Получаем героев для улучшения, у которых меньше 6 звезд
  11552. const heroesToUpgrade = Object.values(this.questInfo.heroGetAll)
  11553. .filter((hero) => hero.star < 6)
  11554. .sort((a, b) => b.power - a.power)
  11555. .map((hero) => hero.id);
  11556. // Получаем героические миссии, которые доступны для рейдов
  11557. const heroicMissions = Object.values(lib.data.mission).filter((mission) => mission.isHeroic && availableMissionsToRaid.includes(mission.id));
  11558. // Собираем дропы из героических миссий
  11559. const drops = heroicMissions.map((mission) => {
  11560. const lastWave = mission.normalMode.waves[mission.normalMode.waves.length - 1];
  11561. const allRewards = lastWave.enemies[lastWave.enemies.length - 1]
  11562. .drop.map((drop) => drop.reward);
  11563. const heroId = +Object.keys(allRewards.find((reward) => reward.fragmentHero).fragmentHero).pop();
  11564. return { id: mission.id, heroId };
  11565. });
  11566. // Определяем, какие дропы подходят для героев, которых нужно улучшить
  11567. const heroDrops = heroesToUpgrade.map((heroId) => drops.find((drop) => drop.heroId == heroId)).filter((drop) => drop);
  11568. const firstMission = heroDrops[0];
  11569. // Выбираем миссию для рейда
  11570. const selectedMissionId = firstMission ? firstMission.id : 1;
  11571. const stamina = this.questInfo.userGetInfo.refillable.find((x) => x.id == 1).amount;
  11572. const costMissions = 3 * lib.data.mission[selectedMissionId].normalMode.teamExp;
  11573. if (stamina < costMissions) {
  11574. console.log('Энергии не достаточно');
  11575. return 0;
  11576. }
  11577. return selectedMissionId;
  11578. }
  11579.  
  11580. end(status) {
  11581. setProgress(status, true);
  11582. this.resolve();
  11583. }
  11584. }
  11585.  
  11586. this.questRun = dailyQuests;
  11587.  
  11588. function testDoYourBest() {
  11589. return new Promise((resolve, reject) => {
  11590. const doIt = new doYourBest(resolve, reject);
  11591. doIt.start();
  11592. });
  11593. }
  11594.  
  11595. /**
  11596. * Do everything button
  11597. *
  11598. * Кнопка сделать все
  11599. */
  11600. class doYourBest {
  11601.  
  11602. funcList = [
  11603. //собрать запределье
  11604. {
  11605. name: 'getOutland',
  11606. label: I18N('ASSEMBLE_OUTLAND'),
  11607. checked: false
  11608. },
  11609. //пройти башню
  11610. {
  11611. name: 'testTower',
  11612. label: I18N('PASS_THE_TOWER'),
  11613. checked: false
  11614. },
  11615. //экспедиции
  11616. {
  11617. name: 'checkExpedition',
  11618. label: I18N('CHECK_EXPEDITIONS'),
  11619. checked: false
  11620. },
  11621. //турнир стихий
  11622. {
  11623. name: 'testTitanArena',
  11624. label: I18N('COMPLETE_TOE'),
  11625. checked: false
  11626. },
  11627. //собрать почту
  11628. {
  11629. name: 'mailGetAll',
  11630. label: I18N('COLLECT_MAIL'),
  11631. checked: false
  11632. },
  11633. //Собрать всякую херню
  11634. {
  11635. name: 'collectAllStuff',
  11636. label: I18N('COLLECT_MISC'),
  11637. title: I18N('COLLECT_MISC_TITLE'),
  11638. checked: false
  11639. },
  11640. //ежедневная награда
  11641. {
  11642. name: 'getDailyBonus',
  11643. label: I18N('DAILY_BONUS'),
  11644. checked: false
  11645. },
  11646. //ежедневные квесты удалить наверно есть в настройках
  11647. {
  11648. name: 'dailyQuests',
  11649. label: I18N('DO_DAILY_QUESTS'),
  11650. checked: false
  11651. },
  11652. //Провидец
  11653. {
  11654. name: 'rollAscension',
  11655. label: I18N('SEER_TITLE'),
  11656. checked: false
  11657. },
  11658. //собрать награды за квесты
  11659. {
  11660. name: 'questAllFarm',
  11661. label: I18N('COLLECT_QUEST_REWARDS'),
  11662. checked: false
  11663. },
  11664. // тест отправь подарки согильдийцам
  11665. {
  11666. name: 'testclanSendDailyGifts',
  11667. label: I18N('QUEST_10016'),
  11668. checked: false
  11669. },
  11670. //получить подарки
  11671. /*{
  11672. name: 'getGift',
  11673. label: I18N('NY_GIFTS'),
  11674. checked: false
  11675. },*/
  11676. //собрать новогодние подарки
  11677. /*{
  11678. name: 'getGiftNewYear',
  11679. label: I18N('NY_GIFTS'),
  11680. checked: false
  11681. },*/
  11682. // тест сферу титанов
  11683. /*{
  11684. name: 'testtitanArtifactChestOpen',
  11685. label: I18N('QUEST_10029'),
  11686. checked: false
  11687. },
  11688. // тест призыв петов
  11689. {
  11690. name: 'testpet_chestOpen',
  11691. label: I18N('QUEST_10044'),
  11692. checked: false
  11693. },*/
  11694. //пройти подземелье обычное
  11695. {
  11696. name: 'testDungeon',
  11697. label: I18N('COMPLETE_DUNGEON'),
  11698. checked: false
  11699. },
  11700. //пройти подземелье для фуловых титанов
  11701. {
  11702. name: 'DungeonFull',
  11703. label: I18N('COMPLETE_DUNGEON_FULL'),
  11704. checked: false
  11705. },
  11706. //синхронизация
  11707. {
  11708. name: 'synchronization',
  11709. label: I18N('MAKE_A_SYNC'),
  11710. checked: false
  11711. },
  11712. //перезагрузка
  11713. {
  11714. name: 'reloadGame',
  11715. label: I18N('RELOAD_GAME'),
  11716. checked: false
  11717. },
  11718. ];
  11719.  
  11720. functions = {
  11721. getOutland,//собрать запределье
  11722. testTower,//прохождение башни
  11723. checkExpedition,//автоэкспедиции
  11724. testTitanArena,//Автопрохождение Турнира Стихий
  11725. mailGetAll,//Собрать всю почту, кроме писем с энергией и зарядами портала
  11726. //Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души
  11727. collectAllStuff: async () => {
  11728. await offerFarmAllReward();
  11729. 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"}]}');
  11730. },
  11731. //Выполнять ежедневные квесты
  11732. dailyQuests: async function () {
  11733. const quests = new dailyQuests(() => { }, () => { });
  11734. await quests.autoInit(true);
  11735. await quests.start();
  11736. },
  11737. rollAscension,//провидец
  11738. getDailyBonus,//ежедневная награда
  11739. questAllFarm,//Собрать все награды за задания
  11740. testclanSendDailyGifts, //отправить подарки
  11741. /*getGift: async () => {
  11742. const collector = new GiftCodeCollector();
  11743. const giftCodes = await collector.getGiftCodes();
  11744. console.log(giftCodes);
  11745.  
  11746. for (const key of giftCodes)
  11747. send({ calls: [{ name: "registration", args: { giftId:key, user: { referrer: {} } },
  11748. context: { actionTs: Math.floor(performance.now()), cookie: window?.NXAppInfo?.session_id || null }, ident: "body" }] });
  11749. },*/
  11750. getGiftNewYear,//собрать новогодние подарки
  11751. testtitanArtifactChestOpen, //открой сферу титанов
  11752. testpet_chestOpen, //Воспользуйся призывом питомцев 1 раз
  11753. testDungeon,//подземка обычная
  11754. DungeonFull,//подземка для фуловых титанов
  11755. synchronization: async () => {
  11756. cheats.refreshGame();
  11757. },
  11758. reloadGame: async () => {
  11759. location.reload();
  11760. },
  11761. }
  11762.  
  11763. constructor(resolve, reject, questInfo) {
  11764. this.resolve = resolve;
  11765. this.reject = reject;
  11766. this.questInfo = questInfo
  11767. }
  11768.  
  11769. async start() {
  11770. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11771.  
  11772. this.funcList.forEach(task => {
  11773. if (!selectedDoIt[task.name]) {
  11774. selectedDoIt[task.name] = {
  11775. checked: task.checked
  11776. }
  11777. } else {
  11778. task.checked = selectedDoIt[task.name].checked
  11779. }
  11780. });
  11781.  
  11782. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11783. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11784. { msg: I18N('BTN_GO'), result: true },
  11785. ], this.funcList);
  11786.  
  11787. if (!answer) {
  11788. this.end('');
  11789. return;
  11790. }
  11791.  
  11792. const taskList = popup.getCheckBoxes();
  11793. taskList.forEach(task => {
  11794. selectedDoIt[task.name].checked = task.checked;
  11795. });
  11796. setSaveVal('selectedDoIt', selectedDoIt);
  11797. for (const task of popup.getCheckBoxes()) {
  11798. if (task.checked) {
  11799. try {
  11800. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11801. await this.functions[task.name]();
  11802. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11803. } catch (error) {
  11804. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11805. { msg: I18N('BTN_NO'), result: false },
  11806. { msg: I18N('BTN_YES'), result: true },
  11807. ])) {
  11808. this.errorHandling(error);
  11809. }
  11810. }
  11811. }
  11812. }
  11813. setTimeout((msg) => {
  11814. this.end(msg);
  11815. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11816. return;
  11817. }
  11818.  
  11819. errorHandling(error) {
  11820. //console.error(error);
  11821. let errorInfo = error.toString() + '\n';
  11822. try {
  11823. const errorStack = error.stack.split('\n');
  11824. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11825. errorInfo += errorStack.slice(0, endStack).join('\n');
  11826. } catch (e) {
  11827. errorInfo += error.stack;
  11828. }
  11829. copyText(errorInfo);
  11830. }
  11831.  
  11832. end(status) {
  11833. setProgress(status, true);
  11834. this.resolve();
  11835. }
  11836. }
  11837.  
  11838. /**
  11839. * Passing the adventure along the specified route
  11840. *
  11841. * Прохождение приключения по указанному маршруту
  11842. */
  11843. function testAdventure(type) {
  11844. return new Promise((resolve, reject) => {
  11845. const bossBattle = new executeAdventure(resolve, reject);
  11846. bossBattle.start(type);
  11847. });
  11848. }
  11849.  
  11850. //Буря
  11851. function testAdventure2(solo) {
  11852. return new Promise((resolve, reject) => {
  11853. const bossBattle = new executeAdventure2(resolve, reject);
  11854. bossBattle.start(solo);
  11855. });
  11856. }
  11857.  
  11858. /**
  11859. * Passing the adventure along the specified route
  11860. *
  11861. * Прохождение приключения по указанному маршруту
  11862. */
  11863. class executeAdventure {
  11864.  
  11865. type = 'default';
  11866.  
  11867. actions = {
  11868. default: {
  11869. getInfo: "adventure_getInfo",
  11870. startBattle: 'adventure_turnStartBattle',
  11871. endBattle: 'adventure_endBattle',
  11872. collectBuff: 'adventure_turnCollectBuff'
  11873. },
  11874. solo: {
  11875. getInfo: "adventureSolo_getInfo",
  11876. startBattle: 'adventureSolo_turnStartBattle',
  11877. endBattle: 'adventureSolo_endBattle',
  11878. collectBuff: 'adventureSolo_turnCollectBuff'
  11879. }
  11880. }
  11881.  
  11882. terminatеReason = I18N('UNKNOWN');
  11883. callAdventureInfo = {
  11884. name: "adventure_getInfo",
  11885. args: {},
  11886. ident: "adventure_getInfo"
  11887. }
  11888. callTeamGetAll = {
  11889. name: "teamGetAll",
  11890. args: {},
  11891. ident: "teamGetAll"
  11892. }
  11893. callTeamGetFavor = {
  11894. name: "teamGetFavor",
  11895. args: {},
  11896. ident: "teamGetFavor"
  11897. }
  11898. //тест прикла
  11899. defaultWays = {
  11900. //Галахад, 1-я
  11901. "adv_strongford_2pl_easy": {
  11902. first: '1,2,3,5,6',
  11903. second: '1,2,4,7,6',
  11904. third: '1,2,3,5,6'
  11905. },
  11906. //Джинджер, 2-я
  11907. "adv_valley_3pl_easy": {
  11908. first: '1,2,5,8,9,11',
  11909. second: '1,3,6,9,11',
  11910. third: '1,4,7,10,9,11'
  11911. },
  11912. //Орион, 3-я
  11913. "adv_ghirwil_3pl_easy": {
  11914. first: '1,5,6,9,11',
  11915. second: '1,4,12,13,11',
  11916. third: '1,2,3,7,10,11'
  11917. },
  11918. //Тесак, 4-я
  11919. "adv_angels_3pl_easy_fire": {
  11920. first: '1,2,4,7,18,8,12,19,22,23',
  11921. second: '1,3,6,11,17,10,16,21,22,23',
  11922. third: '1,5,24,25,9,14,15,20,22,23'
  11923. },
  11924. //Галахад, 5-я
  11925. "adv_strongford_3pl_normal_2": {
  11926. first: '1,2,7,8,12,16,23,26,25,21,24',
  11927. second: '1,4,6,10,11,15,22,15,19,18,24',
  11928. third: '1,5,9,10,14,17,20,27,25,21,24'
  11929. },
  11930. //Джинджер, 6-я
  11931. "adv_valley_3pl_normal": {
  11932. first: '1,2,4,7,10,13,16,19,24,22,25',
  11933. second: '1,3,6,9,12,15,18,21,26,23,25',
  11934. third: '1,5,7,8,11,14,17,20,22,25'
  11935. },
  11936. //Орион, 7-я
  11937. "adv_ghirwil_3pl_normal_2": {
  11938. first: '1,11,10,11,12,15,12,11,21,25,27',
  11939. second: '1,7,3,4,3,6,13,19,20,24,27',
  11940. third: '1,8,5,9,16,23,22,26,27'
  11941. },
  11942. //Тесак, 8-я
  11943. "adv_angels_3pl_normal": {
  11944. first: '1,3,4,8,7,9,10,13,17,16,20,22,23,31,32',
  11945. second: '1,3,5,7,8,11,14,18,20,22,24,27,30,26,32',
  11946. third: '1,3,2,6,7,9,11,15,19,20,22,21,28,29,25'
  11947. },
  11948. //Галахад, 9-я
  11949. "adv_strongford_3pl_hard_2": {
  11950. first: '1,2,6,10,15,7,16,17,23,22,27,32,35,37,40,45',
  11951. second: '1,3,8,12,11,18,19,28,34,33,38,41,43,46,45',
  11952. third: '1,2,5,9,14,20,26,21,30,36,39,42,44,45'
  11953. },
  11954. //Джинджер, 10-я
  11955. "adv_valley_3pl_hard": {
  11956. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  11957. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  11958. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  11959. },
  11960. //Орион, 11-я
  11961. "adv_ghirwil_3pl_hard": {
  11962. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  11963. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  11964. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  11965. },
  11966. //Тесак, 12-я
  11967. "adv_angels_3pl_hard": {
  11968. first: '1,2,8,11,7,4,7,16,23,32,33,25,34,29,35,36',
  11969. second: '1,3,9,13,10,6,10,22,31,30,21,30,15,28,20,27',
  11970. third: '1,5,12,14,24,17,24,25,26,18,19,20,27'
  11971. },
  11972. //Тесак, 13-я
  11973. "adv_angels_3pl_hell": {
  11974. first: '1,2,4,6,16,23,33,34,25,32,29,28,20,27',
  11975. second: '1,7,11,17,24,14,26,18,19,20,27,20,12,8',
  11976. third: '1,9,3,5,10,22,31,36,31,30,15,28,29,30,21,13'
  11977. },
  11978. //Галахад, 13-я
  11979. "adv_strongford_3pl_hell": {
  11980. first: '1,2,5,11,14,20,26,21,30,35,38,41,43,44',
  11981. second: '1,2,6,12,15,7,16,17,23,22,27,42,34,36,39,44',
  11982. third: '1,3,8,9,13,18,19,28,0,33,37,40,32,45,44'
  11983. },
  11984. //Орион, 13-я
  11985. "adv_ghirwil_3pl_hell": {
  11986. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  11987. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  11988. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  11989. },
  11990. //Джинджер, 13-я
  11991. "adv_valley_3pl_hell": {
  11992. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  11993. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  11994. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  11995. }
  11996. }
  11997. callStartBattle = {
  11998. name: "adventure_turnStartBattle",
  11999. args: {},
  12000. ident: "body"
  12001. }
  12002. callEndBattle = {
  12003. name: "adventure_endBattle",
  12004. args: {
  12005. result: {},
  12006. progress: {},
  12007. },
  12008. ident: "body"
  12009. }
  12010. callCollectBuff = {
  12011. name: "adventure_turnCollectBuff",
  12012. args: {},
  12013. ident: "body"
  12014. }
  12015.  
  12016. constructor(resolve, reject) {
  12017. this.resolve = resolve;
  12018. this.reject = reject;
  12019. }
  12020.  
  12021. async start(type) {
  12022. //this.type = type || this.type;
  12023. //this.callAdventureInfo.name = this.actions[this.type].getInfo;
  12024. const data = await Send(JSON.stringify({
  12025. calls: [
  12026. this.callAdventureInfo,
  12027. this.callTeamGetAll,
  12028. this.callTeamGetFavor
  12029. ]
  12030. }));
  12031. //тест прикла1
  12032. this.path = await this.getPath(data.results[0].result.response.mapIdent);
  12033. if (!this.path) {
  12034. this.end();
  12035. return;
  12036. }
  12037. return this.checkAdventureInfo(data.results);
  12038. }
  12039.  
  12040. async getPath(mapId) {
  12041. //const oldVal = getSaveVal('adventurePath', '');
  12042. //const keyPath = `adventurePath:${this.mapIdent}`;
  12043. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  12044. {
  12045. msg: I18N('START_ADVENTURE'),
  12046. placeholder: '1,2,3,4,5,6',
  12047. isInput: true,
  12048. //default: getSaveVal(keyPath, oldVal)
  12049. default: getSaveVal('adventurePath', '')
  12050. },
  12051. {
  12052. msg: ' Начать по пути №1! ',
  12053. placeholder: '1,2,3',
  12054. isInput: true,
  12055. default: this.defaultWays[mapId]?.first
  12056. },
  12057. {
  12058. msg: ' Начать по пути №2! ',
  12059. placeholder: '1,2,3',
  12060. isInput: true,
  12061. default: this.defaultWays[mapId]?.second
  12062. },
  12063. {
  12064. msg: ' Начать по пути №3! ',
  12065. placeholder: '1,2,3',
  12066. isInput: true,
  12067. default: this.defaultWays[mapId]?.third
  12068. },
  12069. {
  12070. msg: I18N('BTN_CANCEL'),
  12071. result: false,
  12072. isCancel: true
  12073. },
  12074. ]);
  12075. if (!answer) {
  12076. this.terminatеReason = I18N('BTN_CANCELED');
  12077. return false;
  12078. }
  12079.  
  12080. let path = answer.split(',');
  12081. if (path.length < 2) {
  12082. path = answer.split('-');
  12083. }
  12084. if (path.length < 2) {
  12085. this.terminatеReason = I18N('MUST_TWO_POINTS');
  12086. return false;
  12087. }
  12088.  
  12089. for (let p in path) {
  12090. path[p] = +path[p].trim()
  12091. if (Number.isNaN(path[p])) {
  12092. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12093. return false;
  12094. }
  12095. }
  12096.  
  12097. /*if (!this.checkPath(path)) {
  12098. return false;
  12099. }*/
  12100. //setSaveVal(keyPath, answer);
  12101. setSaveVal('adventurePath', answer);
  12102. return path;
  12103. }
  12104. /*
  12105. checkPath(path) {
  12106. for (let i = 0; i < path.length - 1; i++) {
  12107. const currentPoint = path[i];
  12108. const nextPoint = path[i + 1];
  12109.  
  12110. const isValidPath = this.paths.some(p =>
  12111. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12112. (p.from_id === nextPoint && p.to_id === currentPoint)
  12113. );
  12114.  
  12115. if (!isValidPath) {
  12116. this.terminatеReason = I18N('INCORRECT_WAY', {
  12117. from: currentPoint,
  12118. to: nextPoint,
  12119. });
  12120. return false;
  12121. }
  12122. }
  12123.  
  12124. return true;
  12125. }
  12126. */
  12127. async checkAdventureInfo(data) {
  12128. this.advInfo = data[0].result.response;
  12129. if (!this.advInfo) {
  12130. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12131. return this.end();
  12132. }
  12133. const heroesTeam = data[1].result.response.adventure_hero;
  12134. const favor = data[2]?.result.response.adventure_hero;
  12135. const heroes = heroesTeam.slice(0, 5);
  12136. const pet = heroesTeam[5];
  12137. this.args = {
  12138. pet,
  12139. heroes,
  12140. favor,
  12141. path: [],
  12142. broadcast: false
  12143. }
  12144. const advUserInfo = this.advInfo.users[userInfo.id];
  12145. this.turnsLeft = advUserInfo.turnsLeft;
  12146. this.currentNode = advUserInfo.currentNode;
  12147. this.nodes = this.advInfo.nodes;
  12148. //this.paths = this.advInfo.paths;
  12149. //this.mapIdent = this.advInfo.mapIdent;
  12150.  
  12151. /*this.path = await this.getPath();
  12152. if (!this.path) {
  12153. return this.end();
  12154. }*/
  12155.  
  12156. if (this.currentNode == 1 && this.path[0] != 1) {
  12157. this.path.unshift(1);
  12158. }
  12159.  
  12160. return this.loop();
  12161. }
  12162.  
  12163. async loop() {
  12164. const position = this.path.indexOf(+this.currentNode);
  12165. if (!(~position)) {
  12166. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12167. return this.end();
  12168. }
  12169. this.path = this.path.slice(position);
  12170. if ((this.path.length - 1) > this.turnsLeft &&
  12171. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12172. { msg: I18N('YES_CONTINUE'), result: false },
  12173. { msg: I18N('BTN_NO'), result: true },
  12174. ])) {
  12175. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12176. return this.end();
  12177. }
  12178. const toPath = [];
  12179. for (const nodeId of this.path) {
  12180. if (!this.turnsLeft) {
  12181. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12182. return this.end();
  12183. }
  12184. toPath.push(nodeId);
  12185. console.log(toPath);
  12186. if (toPath.length > 1) {
  12187. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12188. }
  12189. if (nodeId == this.currentNode) {
  12190. continue;
  12191. }
  12192.  
  12193. const nodeInfo = this.getNodeInfo(nodeId);
  12194. if (nodeInfo.type == 'TYPE_COMBAT') {
  12195. if (nodeInfo.state == 'empty') {
  12196. this.turnsLeft--;
  12197. continue;
  12198. }
  12199.  
  12200. /**
  12201. * Disable regular battle cancellation
  12202. *
  12203. * Отключаем штатную отменую боя
  12204. */
  12205. isCancalBattle = false;
  12206. if (await this.battle(toPath)) {
  12207. this.turnsLeft--;
  12208. toPath.splice(0, toPath.indexOf(nodeId));
  12209. nodeInfo.state = 'empty';
  12210. isCancalBattle = true;
  12211. continue;
  12212. }
  12213. isCancalBattle = true;
  12214. return this.end()
  12215. }
  12216.  
  12217. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12218. const buff = this.checkBuff(nodeInfo);
  12219. if (buff == null) {
  12220. continue;
  12221. }
  12222.  
  12223. if (await this.collectBuff(buff, toPath)) {
  12224. this.turnsLeft--;
  12225. toPath.splice(0, toPath.indexOf(nodeId));
  12226. continue;
  12227. }
  12228. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12229. return this.end();
  12230. }
  12231. }
  12232. this.terminatеReason = I18N('SUCCESS');
  12233. return this.end();
  12234. }
  12235.  
  12236. /**
  12237. * Carrying out a fight
  12238. *
  12239. * Проведение боя
  12240. */
  12241. async battle(path, preCalc = true) {
  12242. const data = await this.startBattle(path);
  12243. try {
  12244. const battle = data.results[0].result.response.battle;
  12245. const result = await Calc(battle);
  12246. if (result.result.win) {
  12247. const info = await this.endBattle(result);
  12248. if (info.results[0].result.response?.error) {
  12249. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12250. return false;
  12251. }
  12252. } else {
  12253. await this.cancelBattle(result);
  12254.  
  12255. if (preCalc && await this.preCalcBattle(battle)) {
  12256. path = path.slice(-2);
  12257. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12258. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12259. const result = await this.battle(path, false);
  12260. if (result) {
  12261. setProgress(I18N('VICTORY'));
  12262. return true;
  12263. }
  12264. }
  12265. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12266. return false;
  12267. }
  12268. return false;
  12269. }
  12270. } catch (error) {
  12271. console.error(error);
  12272. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12273. { msg: I18N('BTN_NO'), result: false },
  12274. { msg: I18N('BTN_YES'), result: true },
  12275. ])) {
  12276. this.errorHandling(error, data);
  12277. }
  12278. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12279. return false;
  12280. }
  12281. return true;
  12282. }
  12283.  
  12284. /**
  12285. * Recalculate battles
  12286. *
  12287. * Прерасчтет битвы
  12288. */
  12289. async preCalcBattle(battle) {
  12290. const countTestBattle = getInput('countTestBattle');
  12291. for (let i = 0; i < countTestBattle; i++) {
  12292. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12293. const result = await Calc(battle);
  12294. if (result.result.win) {
  12295. console.log(i, countTestBattle);
  12296. return true;
  12297. }
  12298. }
  12299. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12300. return false;
  12301. }
  12302.  
  12303. /**
  12304. * Starts a fight
  12305. *
  12306. * Начинает бой
  12307. */
  12308. startBattle(path) {
  12309. this.args.path = path;
  12310. this.callStartBattle.name = this.actions[this.type].startBattle;
  12311. this.callStartBattle.args = this.args
  12312. const calls = [this.callStartBattle];
  12313. return Send(JSON.stringify({ calls }));
  12314. }
  12315.  
  12316. cancelBattle(battle) {
  12317. const fixBattle = function (heroes) {
  12318. for (const ids in heroes) {
  12319. const hero = heroes[ids];
  12320. hero.energy = random(1, 999);
  12321. if (hero.hp > 0) {
  12322. hero.hp = random(1, hero.hp);
  12323. }
  12324. }
  12325. }
  12326. fixBattle(battle.progress[0].attackers.heroes);
  12327. fixBattle(battle.progress[0].defenders.heroes);
  12328. return this.endBattle(battle);
  12329. }
  12330.  
  12331. /**
  12332. * Ends the fight
  12333. *
  12334. * Заканчивает бой
  12335. */
  12336. endBattle(battle) {
  12337. this.callEndBattle.name = this.actions[this.type].endBattle;
  12338. this.callEndBattle.args.result = battle.result
  12339. this.callEndBattle.args.progress = battle.progress
  12340. const calls = [this.callEndBattle];
  12341. return Send(JSON.stringify({ calls }));
  12342. }
  12343.  
  12344. /**
  12345. * Checks if you can get a buff
  12346. *
  12347. * Проверяет можно ли получить баф
  12348. */
  12349. checkBuff(nodeInfo) {
  12350. let id = null;
  12351. let value = 0;
  12352. for (const buffId in nodeInfo.buffs) {
  12353. const buff = nodeInfo.buffs[buffId];
  12354. if (buff.owner == null && buff.value > value) {
  12355. id = buffId;
  12356. value = buff.value;
  12357. }
  12358. }
  12359. nodeInfo.buffs[id].owner = 'Я';
  12360. return id;
  12361. }
  12362.  
  12363. /**
  12364. * Collects a buff
  12365. *
  12366. * Собирает баф
  12367. */
  12368. async collectBuff(buff, path) {
  12369. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12370. this.callCollectBuff.args = { buff, path };
  12371. const calls = [this.callCollectBuff];
  12372. return Send(JSON.stringify({ calls }));
  12373. }
  12374.  
  12375. getNodeInfo(nodeId) {
  12376. return this.nodes.find(node => node.id == nodeId);
  12377. }
  12378.  
  12379. errorHandling(error, data) {
  12380. //console.error(error);
  12381. let errorInfo = error.toString() + '\n';
  12382. try {
  12383. const errorStack = error.stack.split('\n');
  12384. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12385. errorInfo += errorStack.slice(0, endStack).join('\n');
  12386. } catch (e) {
  12387. errorInfo += error.stack;
  12388. }
  12389. if (data) {
  12390. errorInfo += '\nData: ' + JSON.stringify(data);
  12391. }
  12392. copyText(errorInfo);
  12393. }
  12394.  
  12395. end() {
  12396. isCancalBattle = true;
  12397. setProgress(this.terminatеReason, true);
  12398. console.log(this.terminatеReason);
  12399. this.resolve();
  12400. }
  12401. }
  12402. class executeAdventure2 {
  12403.  
  12404. type = 'default';
  12405.  
  12406. actions = {
  12407. default: {
  12408. getInfo: "adventure_getInfo",
  12409. startBattle: 'adventure_turnStartBattle',
  12410. endBattle: 'adventure_endBattle',
  12411. collectBuff: 'adventure_turnCollectBuff'
  12412. },
  12413. solo: {
  12414. getInfo: "adventureSolo_getInfo",
  12415. startBattle: 'adventureSolo_turnStartBattle',
  12416. endBattle: 'adventureSolo_endBattle',
  12417. collectBuff: 'adventureSolo_turnCollectBuff'
  12418. }
  12419. }
  12420.  
  12421. terminatеReason = I18N('UNKNOWN');
  12422. callAdventureInfo = {
  12423. name: "adventure_getInfo",
  12424. args: {},
  12425. ident: "adventure_getInfo"
  12426. }
  12427. callTeamGetAll = {
  12428. name: "teamGetAll",
  12429. args: {},
  12430. ident: "teamGetAll"
  12431. }
  12432. callTeamGetFavor = {
  12433. name: "teamGetFavor",
  12434. args: {},
  12435. ident: "teamGetFavor"
  12436. }
  12437. callStartBattle = {
  12438. name: "adventure_turnStartBattle",
  12439. args: {},
  12440. ident: "body"
  12441. }
  12442. callEndBattle = {
  12443. name: "adventure_endBattle",
  12444. args: {
  12445. result: {},
  12446. progress: {},
  12447. },
  12448. ident: "body"
  12449. }
  12450. callCollectBuff = {
  12451. name: "adventure_turnCollectBuff",
  12452. args: {},
  12453. ident: "body"
  12454. }
  12455.  
  12456. constructor(resolve, reject) {
  12457. this.resolve = resolve;
  12458. this.reject = reject;
  12459. }
  12460.  
  12461. async start(type) {
  12462. this.type = type || this.type;
  12463. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  12464. const data = await Send(JSON.stringify({
  12465. calls: [
  12466. this.callAdventureInfo,
  12467. this.callTeamGetAll,
  12468. this.callTeamGetFavor
  12469. ]
  12470. }));
  12471. return this.checkAdventureInfo(data.results);
  12472. }
  12473.  
  12474. async getPath() {
  12475. const oldVal = getSaveVal('adventurePath', '');
  12476. const keyPath = `adventurePath:${this.mapIdent}`;
  12477. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  12478. {
  12479. msg: I18N('START_ADVENTURE'),
  12480. placeholder: '1,2,3,4,5,6',
  12481. isInput: true,
  12482. default: getSaveVal(keyPath, oldVal)
  12483. },
  12484. {
  12485. msg: I18N('BTN_CANCEL'),
  12486. result: false,
  12487. isCancel: true
  12488. },
  12489. ]);
  12490. if (!answer) {
  12491. this.terminatеReason = I18N('BTN_CANCELED');
  12492. return false;
  12493. }
  12494.  
  12495. let path = answer.split(',');
  12496. if (path.length < 2) {
  12497. path = answer.split('-');
  12498. }
  12499. if (path.length < 2) {
  12500. this.terminatеReason = I18N('MUST_TWO_POINTS');
  12501. return false;
  12502. }
  12503.  
  12504. for (let p in path) {
  12505. path[p] = +path[p].trim()
  12506. if (Number.isNaN(path[p])) {
  12507. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  12508. return false;
  12509. }
  12510. }
  12511. if (!this.checkPath(path)) {
  12512. return false;
  12513. }
  12514. setSaveVal(keyPath, answer);
  12515. return path;
  12516. }
  12517.  
  12518. checkPath(path) {
  12519. for (let i = 0; i < path.length - 1; i++) {
  12520. const currentPoint = path[i];
  12521. const nextPoint = path[i + 1];
  12522.  
  12523. const isValidPath = this.paths.some(p =>
  12524. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  12525. (p.from_id === nextPoint && p.to_id === currentPoint)
  12526. );
  12527.  
  12528. if (!isValidPath) {
  12529. this.terminatеReason = I18N('INCORRECT_WAY', {
  12530. from: currentPoint,
  12531. to: nextPoint,
  12532. });
  12533. return false;
  12534. }
  12535. }
  12536.  
  12537. return true;
  12538. }
  12539.  
  12540. async checkAdventureInfo(data) {
  12541. this.advInfo = data[0].result.response;
  12542. if (!this.advInfo) {
  12543. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  12544. return this.end();
  12545. }
  12546. const heroesTeam = data[1].result.response.adventure_hero;
  12547. const favor = data[2]?.result.response.adventure_hero;
  12548. const heroes = heroesTeam.slice(0, 5);
  12549. const pet = heroesTeam[5];
  12550. this.args = {
  12551. pet,
  12552. heroes,
  12553. favor,
  12554. path: [],
  12555. broadcast: false
  12556. }
  12557. const advUserInfo = this.advInfo.users[userInfo.id];
  12558. this.turnsLeft = advUserInfo.turnsLeft;
  12559. this.currentNode = advUserInfo.currentNode;
  12560. this.nodes = this.advInfo.nodes;
  12561. this.paths = this.advInfo.paths;
  12562. this.mapIdent = this.advInfo.mapIdent;
  12563.  
  12564. this.path = await this.getPath();
  12565. if (!this.path) {
  12566. return this.end();
  12567. }
  12568.  
  12569. if (this.currentNode == 1 && this.path[0] != 1) {
  12570. this.path.unshift(1);
  12571. }
  12572.  
  12573. return this.loop();
  12574. }
  12575.  
  12576. async loop() {
  12577. const position = this.path.indexOf(+this.currentNode);
  12578. if (!(~position)) {
  12579. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  12580. return this.end();
  12581. }
  12582. this.path = this.path.slice(position);
  12583. if ((this.path.length - 1) > this.turnsLeft &&
  12584. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  12585. { msg: I18N('YES_CONTINUE'), result: false },
  12586. { msg: I18N('BTN_NO'), result: true },
  12587. ])) {
  12588. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  12589. return this.end();
  12590. }
  12591. const toPath = [];
  12592. for (const nodeId of this.path) {
  12593. if (!this.turnsLeft) {
  12594. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  12595. return this.end();
  12596. }
  12597. toPath.push(nodeId);
  12598. console.log(toPath);
  12599. if (toPath.length > 1) {
  12600. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  12601. }
  12602. if (nodeId == this.currentNode) {
  12603. continue;
  12604. }
  12605.  
  12606. const nodeInfo = this.getNodeInfo(nodeId);
  12607. if (nodeInfo.type == 'TYPE_COMBAT') {
  12608. if (nodeInfo.state == 'empty') {
  12609. this.turnsLeft--;
  12610. continue;
  12611. }
  12612.  
  12613. /**
  12614. * Disable regular battle cancellation
  12615. *
  12616. * Отключаем штатную отменую боя
  12617. */
  12618. isCancalBattle = false;
  12619. if (await this.battle(toPath)) {
  12620. this.turnsLeft--;
  12621. toPath.splice(0, toPath.indexOf(nodeId));
  12622. nodeInfo.state = 'empty';
  12623. isCancalBattle = true;
  12624. continue;
  12625. }
  12626. isCancalBattle = true;
  12627. return this.end()
  12628. }
  12629.  
  12630. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  12631. const buff = this.checkBuff(nodeInfo);
  12632. if (buff == null) {
  12633. continue;
  12634. }
  12635.  
  12636. if (await this.collectBuff(buff, toPath)) {
  12637. this.turnsLeft--;
  12638. toPath.splice(0, toPath.indexOf(nodeId));
  12639. continue;
  12640. }
  12641. this.terminatеReason = I18N('BUFF_GET_ERROR');
  12642. return this.end();
  12643. }
  12644. }
  12645. this.terminatеReason = I18N('SUCCESS');
  12646. return this.end();
  12647. }
  12648.  
  12649. /**
  12650. * Carrying out a fight
  12651. *
  12652. * Проведение боя
  12653. */
  12654. async battle(path, preCalc = true) {
  12655. const data = await this.startBattle(path);
  12656. try {
  12657. const battle = data.results[0].result.response.battle;
  12658. const result = await Calc(battle);
  12659. if (result.result.win) {
  12660. const info = await this.endBattle(result);
  12661. if (info.results[0].result.response?.error) {
  12662. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12663. return false;
  12664. }
  12665. } else {
  12666. await this.cancelBattle(result);
  12667.  
  12668. if (preCalc && await this.preCalcBattle(battle)) {
  12669. path = path.slice(-2);
  12670. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12671. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12672. const result = await this.battle(path, false);
  12673. if (result) {
  12674. setProgress(I18N('VICTORY'));
  12675. return true;
  12676. }
  12677. }
  12678. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12679. return false;
  12680. }
  12681. return false;
  12682. }
  12683. } catch (error) {
  12684. console.error(error);
  12685. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12686. { msg: I18N('BTN_NO'), result: false },
  12687. { msg: I18N('BTN_YES'), result: true },
  12688. ])) {
  12689. this.errorHandling(error, data);
  12690. }
  12691. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12692. return false;
  12693. }
  12694. return true;
  12695. }
  12696.  
  12697. /**
  12698. * Recalculate battles
  12699. *
  12700. * Прерасчтет битвы
  12701. */
  12702. async preCalcBattle(battle) {
  12703. const countTestBattle = getInput('countTestBattle');
  12704. for (let i = 0; i < countTestBattle; i++) {
  12705. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12706. const result = await Calc(battle);
  12707. if (result.result.win) {
  12708. console.log(i, countTestBattle);
  12709. return true;
  12710. }
  12711. }
  12712. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12713. return false;
  12714. }
  12715.  
  12716. /**
  12717. * Starts a fight
  12718. *
  12719. * Начинает бой
  12720. */
  12721. startBattle(path) {
  12722. this.args.path = path;
  12723. this.callStartBattle.name = this.actions[this.type].startBattle;
  12724. this.callStartBattle.args = this.args
  12725. const calls = [this.callStartBattle];
  12726. return Send(JSON.stringify({ calls }));
  12727. }
  12728.  
  12729. cancelBattle(battle) {
  12730. const fixBattle = function (heroes) {
  12731. for (const ids in heroes) {
  12732. const hero = heroes[ids];
  12733. hero.energy = random(1, 999);
  12734. if (hero.hp > 0) {
  12735. hero.hp = random(1, hero.hp);
  12736. }
  12737. }
  12738. }
  12739. fixBattle(battle.progress[0].attackers.heroes);
  12740. fixBattle(battle.progress[0].defenders.heroes);
  12741. return this.endBattle(battle);
  12742. }
  12743.  
  12744. /**
  12745. * Ends the fight
  12746. *
  12747. * Заканчивает бой
  12748. */
  12749. endBattle(battle) {
  12750. this.callEndBattle.name = this.actions[this.type].endBattle;
  12751. this.callEndBattle.args.result = battle.result
  12752. this.callEndBattle.args.progress = battle.progress
  12753. const calls = [this.callEndBattle];
  12754. return Send(JSON.stringify({ calls }));
  12755. }
  12756.  
  12757. /**
  12758. * Checks if you can get a buff
  12759. *
  12760. * Проверяет можно ли получить баф
  12761. */
  12762. checkBuff(nodeInfo) {
  12763. let id = null;
  12764. let value = 0;
  12765. for (const buffId in nodeInfo.buffs) {
  12766. const buff = nodeInfo.buffs[buffId];
  12767. if (buff.owner == null && buff.value > value) {
  12768. id = buffId;
  12769. value = buff.value;
  12770. }
  12771. }
  12772. nodeInfo.buffs[id].owner = 'Я';
  12773. return id;
  12774. }
  12775.  
  12776. /**
  12777. * Collects a buff
  12778. *
  12779. * Собирает баф
  12780. */
  12781. async collectBuff(buff, path) {
  12782. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12783. this.callCollectBuff.args = { buff, path };
  12784. const calls = [this.callCollectBuff];
  12785. return Send(JSON.stringify({ calls }));
  12786. }
  12787.  
  12788. getNodeInfo(nodeId) {
  12789. return this.nodes.find(node => node.id == nodeId);
  12790. }
  12791.  
  12792. errorHandling(error, data) {
  12793. //console.error(error);
  12794. let errorInfo = error.toString() + '\n';
  12795. try {
  12796. const errorStack = error.stack.split('\n');
  12797. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12798. errorInfo += errorStack.slice(0, endStack).join('\n');
  12799. } catch (e) {
  12800. errorInfo += error.stack;
  12801. }
  12802. if (data) {
  12803. errorInfo += '\nData: ' + JSON.stringify(data);
  12804. }
  12805. copyText(errorInfo);
  12806. }
  12807.  
  12808. end() {
  12809. isCancalBattle = true;
  12810. setProgress(this.terminatеReason, true);
  12811. console.log(this.terminatеReason);
  12812. this.resolve();
  12813. }
  12814. }
  12815. /**
  12816. * Passage of brawls
  12817. *
  12818. * Прохождение потасовок
  12819. */
  12820. function testBrawls(isAuto) {
  12821. return new Promise((resolve, reject) => {
  12822. const brawls = new executeBrawls(resolve, reject);
  12823. brawls.start(brawlsPack, isAuto);
  12824. });
  12825. }
  12826. /**
  12827. * Passage of brawls
  12828. *
  12829. * Прохождение потасовок
  12830. */
  12831. class executeBrawls {
  12832. callBrawlQuestGetInfo = {
  12833. name: "brawl_questGetInfo",
  12834. args: {},
  12835. ident: "brawl_questGetInfo"
  12836. }
  12837. callBrawlFindEnemies = {
  12838. name: "brawl_findEnemies",
  12839. args: {},
  12840. ident: "brawl_findEnemies"
  12841. }
  12842. callBrawlQuestFarm = {
  12843. name: "brawl_questFarm",
  12844. args: {},
  12845. ident: "brawl_questFarm"
  12846. }
  12847. callUserGetInfo = {
  12848. name: "userGetInfo",
  12849. args: {},
  12850. ident: "userGetInfo"
  12851. }
  12852. callTeamGetMaxUpgrade = {
  12853. name: "teamGetMaxUpgrade",
  12854. args: {},
  12855. ident: "teamGetMaxUpgrade"
  12856. }
  12857. callBrawlGetInfo = {
  12858. name: "brawl_getInfo",
  12859. args: {},
  12860. ident: "brawl_getInfo"
  12861. }
  12862.  
  12863. stats = {
  12864. win: 0,
  12865. loss: 0,
  12866. count: 0,
  12867. }
  12868.  
  12869. stage = {
  12870. '3': 1,
  12871. '7': 2,
  12872. '12': 3,
  12873. }
  12874.  
  12875. attempts = 0;
  12876.  
  12877. constructor(resolve, reject) {
  12878. this.resolve = resolve;
  12879. this.reject = reject;
  12880. const allHeroIds = Object.keys(lib.getData('hero'));
  12881. this.callTeamGetMaxUpgrade.args.units = {
  12882. hero: allHeroIds.filter((id) => +id < 1000),
  12883. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12884. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12885. };
  12886. }
  12887.  
  12888. async start(args, isAuto) {
  12889. this.isAuto = isAuto;
  12890. this.args = args;
  12891. isCancalBattle = false;
  12892. this.brawlInfo = await this.getBrawlInfo();
  12893. this.attempts = this.brawlInfo.attempts;
  12894.  
  12895. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12896. this.end(I18N('DONT_HAVE_LIVES'));
  12897. return;
  12898. }
  12899.  
  12900. while (1) {
  12901. if (!isBrawlsAutoStart) {
  12902. this.end(I18N('BTN_CANCELED'));
  12903. return;
  12904. }
  12905.  
  12906. const maxStage = this.brawlInfo.questInfo.stage;
  12907. const stage = this.stage[maxStage];
  12908. const progress = this.brawlInfo.questInfo.progress;
  12909.  
  12910. setProgress(
  12911. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12912. this.stats.win
  12913. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12914. false,
  12915. function () {
  12916. isBrawlsAutoStart = false;
  12917. }
  12918. );
  12919.  
  12920. if (this.brawlInfo.questInfo.canFarm) {
  12921. const result = await this.questFarm();
  12922. console.log(result);
  12923. }
  12924.  
  12925. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12926. if (
  12927. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12928. { msg: I18N('BTN_NO'), result: true },
  12929. { msg: I18N('BTN_YES'), result: false },
  12930. ])
  12931. ) {
  12932. this.end(I18N('SUCCESS'));
  12933. return;
  12934. } else {
  12935. this.continueAttack = true;
  12936. }
  12937. }
  12938.  
  12939. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12940. this.end(I18N('DONT_HAVE_LIVES'))
  12941. return;
  12942. }
  12943.  
  12944. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12945.  
  12946. // Автоматический подбор пачки
  12947. if (this.isAuto) {
  12948. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12949. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12950. return;
  12951. }
  12952. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12953. this.args = await this.updateTitanPack(enemie.heroes);
  12954. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12955. this.args = await this.updateHeroesPack(enemie.heroes);
  12956. }
  12957. }
  12958.  
  12959. const result = await this.battle(enemie.userId);
  12960. this.brawlInfo = {
  12961. questInfo: result[1].result.response,
  12962. findEnemies: result[2].result.response,
  12963. };
  12964. }
  12965. }
  12966.  
  12967. async updateTitanPack(enemieHeroes) {
  12968. const packs = [
  12969. [4033, 4040, 4041, 4042, 4043],
  12970. [4032, 4040, 4041, 4042, 4043],
  12971. [4031, 4040, 4041, 4042, 4043],
  12972. [4030, 4040, 4041, 4042, 4043],
  12973. [4032, 4033, 4040, 4042, 4043],
  12974. [4030, 4033, 4041, 4042, 4043],
  12975. [4031, 4033, 4040, 4042, 4043],
  12976. [4032, 4033, 4040, 4041, 4043],
  12977. [4023, 4040, 4041, 4042, 4043],
  12978. [4030, 4033, 4040, 4042, 4043],
  12979. [4031, 4033, 4040, 4041, 4043],
  12980. [4022, 4040, 4041, 4042, 4043],
  12981. [4030, 4033, 4040, 4041, 4043],
  12982. [4021, 4040, 4041, 4042, 4043],
  12983. [4020, 4040, 4041, 4042, 4043],
  12984. [4023, 4033, 4040, 4042, 4043],
  12985. [4030, 4032, 4033, 4042, 4043],
  12986. [4023, 4033, 4040, 4041, 4043],
  12987. [4031, 4032, 4033, 4040, 4043],
  12988. [4030, 4032, 4033, 4041, 4043],
  12989. [4030, 4031, 4033, 4042, 4043],
  12990. [4013, 4040, 4041, 4042, 4043],
  12991. [4030, 4032, 4033, 4040, 4043],
  12992. [4030, 4031, 4033, 4041, 4043],
  12993. [4012, 4040, 4041, 4042, 4043],
  12994. [4030, 4031, 4033, 4040, 4043],
  12995. [4011, 4040, 4041, 4042, 4043],
  12996. [4010, 4040, 4041, 4042, 4043],
  12997. [4023, 4032, 4033, 4042, 4043],
  12998. [4022, 4032, 4033, 4042, 4043],
  12999. [4023, 4032, 4033, 4041, 4043],
  13000. [4021, 4032, 4033, 4042, 4043],
  13001. [4022, 4032, 4033, 4041, 4043],
  13002. [4023, 4030, 4033, 4042, 4043],
  13003. [4023, 4032, 4033, 4040, 4043],
  13004. [4013, 4033, 4040, 4042, 4043],
  13005. [4020, 4032, 4033, 4042, 4043],
  13006. [4021, 4032, 4033, 4041, 4043],
  13007. [4022, 4030, 4033, 4042, 4043],
  13008. [4022, 4032, 4033, 4040, 4043],
  13009. [4023, 4030, 4033, 4041, 4043],
  13010. [4023, 4031, 4033, 4040, 4043],
  13011. [4013, 4033, 4040, 4041, 4043],
  13012. [4020, 4031, 4033, 4042, 4043],
  13013. [4020, 4032, 4033, 4041, 4043],
  13014. [4021, 4030, 4033, 4042, 4043],
  13015. [4021, 4032, 4033, 4040, 4043],
  13016. [4022, 4030, 4033, 4041, 4043],
  13017. [4022, 4031, 4033, 4040, 4043],
  13018. [4023, 4030, 4033, 4040, 4043],
  13019. [4030, 4031, 4032, 4033, 4043],
  13020. [4003, 4040, 4041, 4042, 4043],
  13021. [4020, 4030, 4033, 4042, 4043],
  13022. [4020, 4031, 4033, 4041, 4043],
  13023. [4020, 4032, 4033, 4040, 4043],
  13024. [4021, 4030, 4033, 4041, 4043],
  13025. [4021, 4031, 4033, 4040, 4043],
  13026. [4022, 4030, 4033, 4040, 4043],
  13027. [4030, 4031, 4032, 4033, 4042],
  13028. [4002, 4040, 4041, 4042, 4043],
  13029. [4020, 4030, 4033, 4041, 4043],
  13030. [4020, 4031, 4033, 4040, 4043],
  13031. [4021, 4030, 4033, 4040, 4043],
  13032. [4030, 4031, 4032, 4033, 4041],
  13033. [4001, 4040, 4041, 4042, 4043],
  13034. [4030, 4031, 4032, 4033, 4040],
  13035. [4000, 4040, 4041, 4042, 4043],
  13036. [4013, 4032, 4033, 4042, 4043],
  13037. [4012, 4032, 4033, 4042, 4043],
  13038. [4013, 4032, 4033, 4041, 4043],
  13039. [4023, 4031, 4032, 4033, 4043],
  13040. [4011, 4032, 4033, 4042, 4043],
  13041. [4012, 4032, 4033, 4041, 4043],
  13042. [4013, 4030, 4033, 4042, 4043],
  13043. [4013, 4032, 4033, 4040, 4043],
  13044. [4023, 4030, 4032, 4033, 4043],
  13045. [4003, 4033, 4040, 4042, 4043],
  13046. [4013, 4023, 4040, 4042, 4043],
  13047. [4010, 4032, 4033, 4042, 4043],
  13048. [4011, 4032, 4033, 4041, 4043],
  13049. [4012, 4030, 4033, 4042, 4043],
  13050. [4012, 4032, 4033, 4040, 4043],
  13051. [4013, 4030, 4033, 4041, 4043],
  13052. [4013, 4031, 4033, 4040, 4043],
  13053. [4023, 4030, 4031, 4033, 4043],
  13054. [4003, 4033, 4040, 4041, 4043],
  13055. [4013, 4023, 4040, 4041, 4043],
  13056. [4010, 4031, 4033, 4042, 4043],
  13057. [4010, 4032, 4033, 4041, 4043],
  13058. [4011, 4030, 4033, 4042, 4043],
  13059. [4011, 4032, 4033, 4040, 4043],
  13060. [4012, 4030, 4033, 4041, 4043],
  13061. [4012, 4031, 4033, 4040, 4043],
  13062. [4013, 4030, 4033, 4040, 4043],
  13063. [4010, 4030, 4033, 4042, 4043],
  13064. [4010, 4031, 4033, 4041, 4043],
  13065. [4010, 4032, 4033, 4040, 4043],
  13066. [4011, 4030, 4033, 4041, 4043],
  13067. [4011, 4031, 4033, 4040, 4043],
  13068. [4012, 4030, 4033, 4040, 4043],
  13069. [4010, 4030, 4033, 4041, 4043],
  13070. [4010, 4031, 4033, 4040, 4043],
  13071. [4011, 4030, 4033, 4040, 4043],
  13072. [4003, 4032, 4033, 4042, 4043],
  13073. [4002, 4032, 4033, 4042, 4043],
  13074. [4003, 4032, 4033, 4041, 4043],
  13075. [4013, 4031, 4032, 4033, 4043],
  13076. [4001, 4032, 4033, 4042, 4043],
  13077. [4002, 4032, 4033, 4041, 4043],
  13078. [4003, 4030, 4033, 4042, 4043],
  13079. [4003, 4032, 4033, 4040, 4043],
  13080. [4013, 4030, 4032, 4033, 4043],
  13081. [4003, 4023, 4040, 4042, 4043],
  13082. [4000, 4032, 4033, 4042, 4043],
  13083. [4001, 4032, 4033, 4041, 4043],
  13084. [4002, 4030, 4033, 4042, 4043],
  13085. [4002, 4032, 4033, 4040, 4043],
  13086. [4003, 4030, 4033, 4041, 4043],
  13087. [4003, 4031, 4033, 4040, 4043],
  13088. [4020, 4022, 4023, 4042, 4043],
  13089. [4013, 4030, 4031, 4033, 4043],
  13090. [4003, 4023, 4040, 4041, 4043],
  13091. [4000, 4031, 4033, 4042, 4043],
  13092. [4000, 4032, 4033, 4041, 4043],
  13093. [4001, 4030, 4033, 4042, 4043],
  13094. [4001, 4032, 4033, 4040, 4043],
  13095. [4002, 4030, 4033, 4041, 4043],
  13096. [4002, 4031, 4033, 4040, 4043],
  13097. [4003, 4030, 4033, 4040, 4043],
  13098. [4021, 4022, 4023, 4040, 4043],
  13099. [4020, 4022, 4023, 4041, 4043],
  13100. [4020, 4021, 4023, 4042, 4043],
  13101. [4023, 4030, 4031, 4032, 4033],
  13102. [4000, 4030, 4033, 4042, 4043],
  13103. [4000, 4031, 4033, 4041, 4043],
  13104. [4000, 4032, 4033, 4040, 4043],
  13105. [4001, 4030, 4033, 4041, 4043],
  13106. [4001, 4031, 4033, 4040, 4043],
  13107. [4002, 4030, 4033, 4040, 4043],
  13108. [4020, 4022, 4023, 4040, 4043],
  13109. [4020, 4021, 4023, 4041, 4043],
  13110. [4022, 4030, 4031, 4032, 4033],
  13111. [4000, 4030, 4033, 4041, 4043],
  13112. [4000, 4031, 4033, 4040, 4043],
  13113. [4001, 4030, 4033, 4040, 4043],
  13114. [4020, 4021, 4023, 4040, 4043],
  13115. [4021, 4030, 4031, 4032, 4033],
  13116. [4020, 4030, 4031, 4032, 4033],
  13117. [4003, 4031, 4032, 4033, 4043],
  13118. [4020, 4022, 4023, 4033, 4043],
  13119. [4003, 4030, 4032, 4033, 4043],
  13120. [4003, 4013, 4040, 4042, 4043],
  13121. [4020, 4021, 4023, 4033, 4043],
  13122. [4003, 4030, 4031, 4033, 4043],
  13123. [4003, 4013, 4040, 4041, 4043],
  13124. [4013, 4030, 4031, 4032, 4033],
  13125. [4012, 4030, 4031, 4032, 4033],
  13126. [4011, 4030, 4031, 4032, 4033],
  13127. [4010, 4030, 4031, 4032, 4033],
  13128. [4013, 4023, 4031, 4032, 4033],
  13129. [4013, 4023, 4030, 4032, 4033],
  13130. [4020, 4022, 4023, 4032, 4033],
  13131. [4013, 4023, 4030, 4031, 4033],
  13132. [4021, 4022, 4023, 4030, 4033],
  13133. [4020, 4022, 4023, 4031, 4033],
  13134. [4020, 4021, 4023, 4032, 4033],
  13135. [4020, 4021, 4022, 4023, 4043],
  13136. [4003, 4030, 4031, 4032, 4033],
  13137. [4020, 4022, 4023, 4030, 4033],
  13138. [4020, 4021, 4023, 4031, 4033],
  13139. [4020, 4021, 4022, 4023, 4042],
  13140. [4002, 4030, 4031, 4032, 4033],
  13141. [4020, 4021, 4023, 4030, 4033],
  13142. [4020, 4021, 4022, 4023, 4041],
  13143. [4001, 4030, 4031, 4032, 4033],
  13144. [4020, 4021, 4022, 4023, 4040],
  13145. [4000, 4030, 4031, 4032, 4033],
  13146. [4003, 4023, 4031, 4032, 4033],
  13147. [4013, 4020, 4022, 4023, 4043],
  13148. [4003, 4023, 4030, 4032, 4033],
  13149. [4010, 4012, 4013, 4042, 4043],
  13150. [4013, 4020, 4021, 4023, 4043],
  13151. [4003, 4023, 4030, 4031, 4033],
  13152. [4011, 4012, 4013, 4040, 4043],
  13153. [4010, 4012, 4013, 4041, 4043],
  13154. [4010, 4011, 4013, 4042, 4043],
  13155. [4020, 4021, 4022, 4023, 4033],
  13156. [4010, 4012, 4013, 4040, 4043],
  13157. [4010, 4011, 4013, 4041, 4043],
  13158. [4020, 4021, 4022, 4023, 4032],
  13159. [4010, 4011, 4013, 4040, 4043],
  13160. [4020, 4021, 4022, 4023, 4031],
  13161. [4020, 4021, 4022, 4023, 4030],
  13162. [4003, 4013, 4031, 4032, 4033],
  13163. [4010, 4012, 4013, 4033, 4043],
  13164. [4003, 4020, 4022, 4023, 4043],
  13165. [4013, 4020, 4022, 4023, 4033],
  13166. [4003, 4013, 4030, 4032, 4033],
  13167. [4010, 4011, 4013, 4033, 4043],
  13168. [4003, 4020, 4021, 4023, 4043],
  13169. [4013, 4020, 4021, 4023, 4033],
  13170. [4003, 4013, 4030, 4031, 4033],
  13171. [4010, 4012, 4013, 4023, 4043],
  13172. [4003, 4020, 4022, 4023, 4033],
  13173. [4010, 4012, 4013, 4032, 4033],
  13174. [4010, 4011, 4013, 4023, 4043],
  13175. [4003, 4020, 4021, 4023, 4033],
  13176. [4011, 4012, 4013, 4030, 4033],
  13177. [4010, 4012, 4013, 4031, 4033],
  13178. [4010, 4011, 4013, 4032, 4033],
  13179. [4013, 4020, 4021, 4022, 4023],
  13180. [4010, 4012, 4013, 4030, 4033],
  13181. [4010, 4011, 4013, 4031, 4033],
  13182. [4012, 4020, 4021, 4022, 4023],
  13183. [4010, 4011, 4013, 4030, 4033],
  13184. [4011, 4020, 4021, 4022, 4023],
  13185. [4010, 4020, 4021, 4022, 4023],
  13186. [4010, 4012, 4013, 4023, 4033],
  13187. [4000, 4002, 4003, 4042, 4043],
  13188. [4010, 4011, 4013, 4023, 4033],
  13189. [4001, 4002, 4003, 4040, 4043],
  13190. [4000, 4002, 4003, 4041, 4043],
  13191. [4000, 4001, 4003, 4042, 4043],
  13192. [4010, 4011, 4012, 4013, 4043],
  13193. [4003, 4020, 4021, 4022, 4023],
  13194. [4000, 4002, 4003, 4040, 4043],
  13195. [4000, 4001, 4003, 4041, 4043],
  13196. [4010, 4011, 4012, 4013, 4042],
  13197. [4002, 4020, 4021, 4022, 4023],
  13198. [4000, 4001, 4003, 4040, 4043],
  13199. [4010, 4011, 4012, 4013, 4041],
  13200. [4001, 4020, 4021, 4022, 4023],
  13201. [4010, 4011, 4012, 4013, 4040],
  13202. [4000, 4020, 4021, 4022, 4023],
  13203. [4001, 4002, 4003, 4033, 4043],
  13204. [4000, 4002, 4003, 4033, 4043],
  13205. [4003, 4010, 4012, 4013, 4043],
  13206. [4003, 4013, 4020, 4022, 4023],
  13207. [4000, 4001, 4003, 4033, 4043],
  13208. [4003, 4010, 4011, 4013, 4043],
  13209. [4003, 4013, 4020, 4021, 4023],
  13210. [4010, 4011, 4012, 4013, 4033],
  13211. [4010, 4011, 4012, 4013, 4032],
  13212. [4010, 4011, 4012, 4013, 4031],
  13213. [4010, 4011, 4012, 4013, 4030],
  13214. [4001, 4002, 4003, 4023, 4043],
  13215. [4000, 4002, 4003, 4023, 4043],
  13216. [4003, 4010, 4012, 4013, 4033],
  13217. [4000, 4002, 4003, 4032, 4033],
  13218. [4000, 4001, 4003, 4023, 4043],
  13219. [4003, 4010, 4011, 4013, 4033],
  13220. [4001, 4002, 4003, 4030, 4033],
  13221. [4000, 4002, 4003, 4031, 4033],
  13222. [4000, 4001, 4003, 4032, 4033],
  13223. [4010, 4011, 4012, 4013, 4023],
  13224. [4000, 4002, 4003, 4030, 4033],
  13225. [4000, 4001, 4003, 4031, 4033],
  13226. [4010, 4011, 4012, 4013, 4022],
  13227. [4000, 4001, 4003, 4030, 4033],
  13228. [4010, 4011, 4012, 4013, 4021],
  13229. [4010, 4011, 4012, 4013, 4020],
  13230. [4001, 4002, 4003, 4013, 4043],
  13231. [4001, 4002, 4003, 4023, 4033],
  13232. [4000, 4002, 4003, 4013, 4043],
  13233. [4000, 4002, 4003, 4023, 4033],
  13234. [4003, 4010, 4012, 4013, 4023],
  13235. [4000, 4001, 4003, 4013, 4043],
  13236. [4000, 4001, 4003, 4023, 4033],
  13237. [4003, 4010, 4011, 4013, 4023],
  13238. [4001, 4002, 4003, 4013, 4033],
  13239. [4000, 4002, 4003, 4013, 4033],
  13240. [4000, 4001, 4003, 4013, 4033],
  13241. [4000, 4001, 4002, 4003, 4043],
  13242. [4003, 4010, 4011, 4012, 4013],
  13243. [4000, 4001, 4002, 4003, 4042],
  13244. [4002, 4010, 4011, 4012, 4013],
  13245. [4000, 4001, 4002, 4003, 4041],
  13246. [4001, 4010, 4011, 4012, 4013],
  13247. [4000, 4001, 4002, 4003, 4040],
  13248. [4000, 4010, 4011, 4012, 4013],
  13249. [4001, 4002, 4003, 4013, 4023],
  13250. [4000, 4002, 4003, 4013, 4023],
  13251. [4000, 4001, 4003, 4013, 4023],
  13252. [4000, 4001, 4002, 4003, 4033],
  13253. [4000, 4001, 4002, 4003, 4032],
  13254. [4000, 4001, 4002, 4003, 4031],
  13255. [4000, 4001, 4002, 4003, 4030],
  13256. [4000, 4001, 4002, 4003, 4023],
  13257. [4000, 4001, 4002, 4003, 4022],
  13258. [4000, 4001, 4002, 4003, 4021],
  13259. [4000, 4001, 4002, 4003, 4020],
  13260. [4000, 4001, 4002, 4003, 4013],
  13261. [4000, 4001, 4002, 4003, 4012],
  13262. [4000, 4001, 4002, 4003, 4011],
  13263. [4000, 4001, 4002, 4003, 4010],
  13264. ].filter((p) => p.includes(this.mandatoryId));
  13265. const bestPack = {
  13266. pack: packs[0],
  13267. winRate: 0,
  13268. countBattle: 0,
  13269. id: 0,
  13270. };
  13271. for (const id in packs) {
  13272. const pack = packs[id];
  13273. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  13274. const battle = {
  13275. attackers,
  13276. defenders: [enemieHeroes],
  13277. type: 'brawl_titan',
  13278. };
  13279. const isRandom = this.isRandomBattle(battle);
  13280. const stat = {
  13281. count: 0,
  13282. win: 0,
  13283. winRate: 0,
  13284. };
  13285. for (let i = 1; i <= 20; i++) {
  13286. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13287. const result = await Calc(battle);
  13288. stat.win += result.result.win;
  13289. stat.count += 1;
  13290. stat.winRate = stat.win / stat.count;
  13291. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  13292. break;
  13293. }
  13294. }
  13295. if (!isRandom && stat.win) {
  13296. return {
  13297. favor: {},
  13298. heroes: pack,
  13299. };
  13300. }
  13301. if (stat.winRate > 0.85) {
  13302. return {
  13303. favor: {},
  13304. heroes: pack,
  13305. };
  13306. }
  13307. if (stat.winRate > bestPack.winRate) {
  13308. bestPack.countBattle = stat.count;
  13309. bestPack.winRate = stat.winRate;
  13310. bestPack.pack = pack;
  13311. bestPack.id = id;
  13312. }
  13313. }
  13314. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  13315. return {
  13316. favor: {},
  13317. heroes: bestPack.pack,
  13318. };
  13319. }
  13320. isRandomPack(pack) {
  13321. const ids = Object.keys(pack);
  13322. return ids.includes('4023') || ids.includes('4021');
  13323. }
  13324. isRandomBattle(battle) {
  13325. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  13326. }
  13327. async updateHeroesPack(enemieHeroes) {
  13328. 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}}}];
  13329. const bestPack = {
  13330. pack: packs[0],
  13331. countWin: 0,
  13332. }
  13333. for (const pack of packs) {
  13334. const attackers = pack.attackers;
  13335. const battle = {
  13336. attackers,
  13337. defenders: [enemieHeroes],
  13338. type: 'brawl',
  13339. };
  13340. let countWinBattles = 0;
  13341. let countTestBattle = 10;
  13342. for (let i = 0; i < countTestBattle; i++) {
  13343. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  13344. const result = await Calc(battle);
  13345. if (result.result.win) {
  13346. countWinBattles++;
  13347. }
  13348. if (countWinBattles > 7) {
  13349. console.log(pack)
  13350. return pack.args;
  13351. }
  13352. }
  13353. if (countWinBattles > bestPack.countWin) {
  13354. bestPack.countWin = countWinBattles;
  13355. bestPack.pack = pack.args;
  13356. }
  13357. }
  13358. console.log(bestPack);
  13359. return bestPack.pack;
  13360. }
  13361. async questFarm() {
  13362. const calls = [this.callBrawlQuestFarm];
  13363. const result = await Send(JSON.stringify({ calls }));
  13364. return result.results[0].result.response;
  13365. }
  13366. async getBrawlInfo() {
  13367. const data = await Send(JSON.stringify({
  13368. calls: [
  13369. this.callUserGetInfo,
  13370. this.callBrawlQuestGetInfo,
  13371. this.callBrawlFindEnemies,
  13372. this.callTeamGetMaxUpgrade,
  13373. this.callBrawlGetInfo,
  13374. ]
  13375. }));
  13376. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  13377. const maxUpgrade = data.results[3].result.response;
  13378. const maxHero = Object.values(maxUpgrade.hero);
  13379. const maxTitan = Object.values(maxUpgrade.titan);
  13380. const maxPet = Object.values(maxUpgrade.pet);
  13381. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  13382. this.info = data.results[4].result.response;
  13383. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  13384. return {
  13385. attempts: attempts.amount,
  13386. questInfo: data.results[1].result.response,
  13387. findEnemies: data.results[2].result.response,
  13388. }
  13389. }
  13390.  
  13391. /**
  13392. * Carrying out a fight
  13393. *
  13394. * Проведение боя
  13395. */
  13396. async battle(userId) {
  13397. this.stats.count++;
  13398. const battle = await this.startBattle(userId, this.args);
  13399. const result = await Calc(battle);
  13400. console.log(result.result);
  13401. if (result.result.win) {
  13402. this.stats.win++;
  13403. } else {
  13404. this.stats.loss++;
  13405. if (!this.info.boughtEndlessLivesToday) {
  13406. this.attempts--;
  13407. }
  13408. }
  13409. return await this.endBattle(result);
  13410. // return await this.cancelBattle(result);
  13411. }
  13412.  
  13413. /**
  13414. * Starts a fight
  13415. *
  13416. * Начинает бой
  13417. */
  13418. async startBattle(userId, args) {
  13419. const call = {
  13420. name: "brawl_startBattle",
  13421. args,
  13422. ident: "brawl_startBattle"
  13423. }
  13424. call.args.userId = userId;
  13425. const calls = [call];
  13426. const result = await Send(JSON.stringify({ calls }));
  13427. return result.results[0].result.response;
  13428. }
  13429.  
  13430. cancelBattle(battle) {
  13431. const fixBattle = function (heroes) {
  13432. for (const ids in heroes) {
  13433. const hero = heroes[ids];
  13434. hero.energy = random(1, 999);
  13435. if (hero.hp > 0) {
  13436. hero.hp = random(1, hero.hp);
  13437. }
  13438. }
  13439. }
  13440. fixBattle(battle.progress[0].attackers.heroes);
  13441. fixBattle(battle.progress[0].defenders.heroes);
  13442. return this.endBattle(battle);
  13443. }
  13444.  
  13445. /**
  13446. * Ends the fight
  13447. *
  13448. * Заканчивает бой
  13449. */
  13450. async endBattle(battle) {
  13451. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  13452. const calls = [{
  13453. name: "brawl_endBattle",
  13454. args: {
  13455. result: battle.result,
  13456. progress: battle.progress
  13457. },
  13458. ident: "brawl_endBattle"
  13459. },
  13460. this.callBrawlQuestGetInfo,
  13461. this.callBrawlFindEnemies,
  13462. ];
  13463. const result = await Send(JSON.stringify({ calls }));
  13464. return result.results;
  13465. }
  13466.  
  13467. end(endReason) {
  13468. isCancalBattle = true;
  13469. isBrawlsAutoStart = false;
  13470. setProgress(endReason, true);
  13471. console.log(endReason);
  13472. this.resolve();
  13473. }
  13474. }
  13475.  
  13476. // подземку вконце впихнул
  13477. function DungeonFull() {
  13478. return new Promise((resolve, reject) => {
  13479. const dung = new executeDungeon2(resolve, reject);
  13480. const titanit = getInput('countTitanit');
  13481. dung.start(titanit);
  13482. });
  13483. }
  13484. /** Прохождение подземелья */
  13485. function executeDungeon2(resolve, reject) {
  13486. let dungeonActivity = 0;
  13487. let startDungeonActivity = 0;
  13488. let maxDungeonActivity = 150;
  13489. let limitDungeonActivity = 30180;
  13490. let countShowStats = 1;
  13491. //let fastMode = isChecked('fastMode');
  13492. let end = false;
  13493.  
  13494. let countTeam = [];
  13495. let timeDungeon = {
  13496. all: new Date().getTime(),
  13497. findAttack: 0,
  13498. attackNeutral: 0,
  13499. attackEarthOrFire: 0
  13500. }
  13501. let titansStates = {};
  13502. let bestBattle = {};
  13503.  
  13504. let teams = {
  13505. neutral: [],
  13506. water: [],
  13507. earth: [],
  13508. fire: [],
  13509. hero: []
  13510. }
  13511.  
  13512. //тест
  13513. let talentMsg = '';
  13514. let talentMsgReward = ''
  13515.  
  13516. let callsExecuteDungeon = {
  13517. calls: [{
  13518. name: "dungeonGetInfo",
  13519. args: {},
  13520. ident: "dungeonGetInfo"
  13521. }, {
  13522. name: "teamGetAll",
  13523. args: {},
  13524. ident: "teamGetAll"
  13525. }, {
  13526. name: "teamGetFavor",
  13527. args: {},
  13528. ident: "teamGetFavor"
  13529. }, {
  13530. name: "clanGetInfo",
  13531. args: {},
  13532. ident: "clanGetInfo"
  13533. }]
  13534. }
  13535.  
  13536. this.start = async function(titanit) {
  13537. //maxDungeonActivity = titanit > limitDungeonActivity ? limitDungeonActivity : titanit;
  13538. maxDungeonActivity = titanit || getInput('countTitanit');
  13539. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  13540. }
  13541.  
  13542. /** Получаем данные по подземелью */
  13543. function startDungeon(e) {
  13544. stopDung = false; // стоп подземка
  13545. let res = e.results;
  13546. let dungeonGetInfo = res[0].result.response;
  13547. if (!dungeonGetInfo) {
  13548. endDungeon('noDungeon', res);
  13549. return;
  13550. }
  13551. console.log("Начинаем копать на фулл: ", new Date());
  13552. let teamGetAll = res[1].result.response;
  13553. let teamGetFavor = res[2].result.response;
  13554. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  13555. startDungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  13556. titansStates = dungeonGetInfo.states.titans;
  13557.  
  13558. teams.hero = {
  13559. favor: teamGetFavor.dungeon_hero,
  13560. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  13561. teamNum: 0,
  13562. }
  13563. let heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  13564. if (heroPet) {
  13565. teams.hero.pet = heroPet;
  13566. }
  13567. teams.neutral = getTitanTeam('neutral');
  13568. teams.water = {
  13569. favor: {},
  13570. heroes: getTitanTeam('water'),
  13571. teamNum: 0,
  13572. };
  13573. teams.earth = {
  13574. favor: {},
  13575. heroes: getTitanTeam('earth'),
  13576. teamNum: 0,
  13577. };
  13578. teams.fire = {
  13579. favor: {},
  13580. heroes: getTitanTeam('fire'),
  13581. teamNum: 0,
  13582. };
  13583.  
  13584. checkFloor(dungeonGetInfo);
  13585. }
  13586.  
  13587. function getTitanTeam(type) {
  13588. switch (type) {
  13589. case 'neutral':
  13590. return [4023, 4022, 4012, 4021, 4011, 4010, 4020];
  13591. case 'water':
  13592. return [4000, 4001, 4002, 4003]
  13593. .filter(e => !titansStates[e]?.isDead);
  13594. case 'earth':
  13595. return [4020, 4022, 4021, 4023]
  13596. .filter(e => !titansStates[e]?.isDead);
  13597. case 'fire':
  13598. return [4010, 4011, 4012, 4013]
  13599. .filter(e => !titansStates[e]?.isDead);
  13600. }
  13601. }
  13602.  
  13603. /** Создать копию объекта */
  13604. function clone(a) {
  13605. return JSON.parse(JSON.stringify(a));
  13606. }
  13607.  
  13608. /** Находит стихию на этаже */
  13609. function findElement(floor, element) {
  13610. for (let i in floor) {
  13611. if (floor[i].attackerType === element) {
  13612. return i;
  13613. }
  13614. }
  13615. return undefined;
  13616. }
  13617.  
  13618. /** Проверяем этаж */
  13619. async function checkFloor(dungeonInfo) {
  13620. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  13621. saveProgress();
  13622. return;
  13623. }
  13624. checkTalent(dungeonInfo);
  13625. // console.log(dungeonInfo, dungeonActivity);
  13626. setProgress(`${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  13627. //setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  13628. if (dungeonActivity >= maxDungeonActivity) {
  13629. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  13630. return;
  13631. }
  13632. let activity = dungeonActivity - startDungeonActivity;
  13633. titansStates = dungeonInfo.states.titans;
  13634. if (stopDung){
  13635. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  13636. return;
  13637. }
  13638. /*if (activity / 1000 > countShowStats) {
  13639. countShowStats++;
  13640. showStats();
  13641. }*/
  13642. bestBattle = {};
  13643. let floorChoices = dungeonInfo.floor.userData;
  13644. if (floorChoices.length > 1) {
  13645. for (let element in teams) {
  13646. let teamNum = findElement(floorChoices, element);
  13647. if (!!teamNum) {
  13648. if (element == 'earth') {
  13649. teamNum = await chooseEarthOrFire(floorChoices);
  13650. if (teamNum < 0) {
  13651. endDungeon('Невозможно победить без потери Титана!', dungeonInfo);
  13652. return;
  13653. }
  13654. }
  13655. chooseElement(floorChoices[teamNum].attackerType, teamNum);
  13656. return;
  13657. }
  13658. }
  13659. } else {
  13660. chooseElement(floorChoices[0].attackerType, 0);
  13661. }
  13662. }
  13663. //тест черепахи
  13664. async function checkTalent(dungeonInfo) {
  13665. const talent = dungeonInfo.talent;
  13666. if (!talent) {
  13667. return;
  13668. }
  13669. const dungeonFloor = +dungeonInfo.floorNumber;
  13670. const talentFloor = +talent.floorRandValue;
  13671. let doorsAmount = 3 - talent.conditions.doorsAmount;
  13672. if (dungeonFloor === talentFloor && (!doorsAmount || !talent.conditions?.farmedDoors[dungeonFloor])) {
  13673. const reward = await Send({
  13674. calls: [
  13675. { name: 'heroTalent_getReward', args: { talentType: 'tmntDungeonTalent', reroll: false }, ident: 'group_0_body' },
  13676. { name: 'heroTalent_farmReward', args: { talentType: 'tmntDungeonTalent' }, ident: 'group_1_body' },
  13677. ],
  13678. }).then((e) => e.results[0].result.response);
  13679. const type = Object.keys(reward).pop();
  13680. const itemId = Object.keys(reward[type]).pop();
  13681. const count = reward[type][itemId];
  13682. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  13683. talentMsgReward += `<br> ${count} ${itemName}`;
  13684. doorsAmount++;
  13685. }
  13686. talentMsg = `<br>TMNT Talent: ${doorsAmount}/3 ${talentMsgReward}<br>`;
  13687. }
  13688.  
  13689. /** Выбираем огнем или землей атаковать */
  13690. async function chooseEarthOrFire(floorChoices) {
  13691. bestBattle.recovery = -11;
  13692. let selectedTeamNum = -1;
  13693. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  13694. for (let teamNum in floorChoices) {
  13695. let attackerType = floorChoices[teamNum].attackerType;
  13696. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  13697. }
  13698. }
  13699. console.log("Выбор команды огня или земли: ", selectedTeamNum < 0 ? "не сделан" : floorChoices[selectedTeamNum].attackerType);
  13700. return selectedTeamNum;
  13701. }
  13702.  
  13703. /** Попытка атаки землей и огнем */
  13704. async function attemptAttackEarthOrFire(teamNum, attackerType, attempt) {
  13705. let start = new Date();
  13706. let team = clone(teams[attackerType]);
  13707. let startIndex = team.heroes.length + attempt - 4;
  13708. if (startIndex >= 0) {
  13709. team.heroes = team.heroes.slice(startIndex);
  13710. let recovery = await getBestRecovery(teamNum, attackerType, team, 25);
  13711. if (recovery > bestBattle.recovery) {
  13712. bestBattle.recovery = recovery;
  13713. bestBattle.selectedTeamNum = teamNum;
  13714. bestBattle.team = team;
  13715. }
  13716. }
  13717. let workTime = new Date().getTime() - start.getTime();
  13718. timeDungeon.attackEarthOrFire += workTime;
  13719. if (bestBattle.recovery < -10) {
  13720. return -1;
  13721. }
  13722. return bestBattle.selectedTeamNum;
  13723. }
  13724.  
  13725. /** Выбираем стихию для атаки */
  13726. async function chooseElement(attackerType, teamNum) {
  13727. let result;
  13728. switch (attackerType) {
  13729. case 'hero':
  13730. case 'water':
  13731. result = await startBattle(teamNum, attackerType, teams[attackerType]);
  13732. break;
  13733. case 'earth':
  13734. case 'fire':
  13735. result = await attackEarthOrFire(teamNum, attackerType);
  13736. break;
  13737. case 'neutral':
  13738. result = await attackNeutral(teamNum, attackerType);
  13739. }
  13740. if (!!result && attackerType != 'hero') {
  13741. let recovery = (!!!bestBattle.recovery ? 10 * getRecovery(result) : bestBattle.recovery) * 100;
  13742. let titans = result.progress[0].attackers.heroes;
  13743. console.log("Проведен бой: " + attackerType +
  13744. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", titans);
  13745. }
  13746. endBattle(result);
  13747. }
  13748.  
  13749. /** Атакуем Землей или Огнем */
  13750. async function attackEarthOrFire(teamNum, attackerType) {
  13751. if (!!!bestBattle.recovery) {
  13752. bestBattle.recovery = -11;
  13753. let selectedTeamNum = -1;
  13754. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  13755. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  13756. }
  13757. if (selectedTeamNum < 0) {
  13758. endDungeon('Невозможно победить без потери Титана!', attackerType);
  13759. return;
  13760. }
  13761. }
  13762. return findAttack(teamNum, attackerType, bestBattle.team);
  13763. }
  13764.  
  13765. /** Находим подходящий результат для атаки */
  13766. async function findAttack(teamNum, attackerType, team) {
  13767. let start = new Date();
  13768. let recovery = -1000;
  13769. let iterations = 0;
  13770. let result;
  13771. let correction = 0.01;
  13772. for (let needRecovery = bestBattle.recovery; recovery < needRecovery; needRecovery -= correction, iterations++) {
  13773. result = await startBattle(teamNum, attackerType, team);
  13774. recovery = getRecovery(result);
  13775. }
  13776. bestBattle.recovery = recovery;
  13777. let workTime = new Date().getTime() - start.getTime();
  13778. timeDungeon.findAttack += workTime;
  13779. return result;
  13780. }
  13781.  
  13782. /** Атакуем Нейтральной командой */
  13783. async function attackNeutral(teamNum, attackerType) {
  13784. let start = new Date();
  13785. let factors = calcFactor();
  13786. bestBattle.recovery = -0.2;
  13787. await findBestBattleNeutral(teamNum, attackerType, factors, true)
  13788. if (bestBattle.recovery < 0 || (bestBattle.recovery < 0.2 && factors[0].value < 0.5)) {
  13789. let recovery = 100 * bestBattle.recovery;
  13790. console.log("Не удалось найти удачный бой в быстром режиме: " + attackerType +
  13791. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", bestBattle.attackers);
  13792. await findBestBattleNeutral(teamNum, attackerType, factors, false)
  13793. }
  13794. let workTime = new Date().getTime() - start.getTime();
  13795. timeDungeon.attackNeutral += workTime;
  13796. if (!!bestBattle.attackers) {
  13797. let team = getTeam(bestBattle.attackers);
  13798. return findAttack(teamNum, attackerType, team);
  13799. }
  13800. endDungeon('Не удалось найти удачный бой!', attackerType);
  13801. return undefined;
  13802. }
  13803.  
  13804. /** Находит лучшую нейтральную команду */
  13805. async function findBestBattleNeutral(teamNum, attackerType, factors, mode) {
  13806. let countFactors = factors.length < 4 ? factors.length : 4;
  13807. let aradgi = !titansStates['4013']?.isDead;
  13808. let edem = !titansStates['4023']?.isDead;
  13809. let dark = [4032, 4033].filter(e => !titansStates[e]?.isDead);
  13810. let light = [4042].filter(e => !titansStates[e]?.isDead);
  13811. let actions = [];
  13812. if (mode) {
  13813. for (let i = 0; i < countFactors; i++) {
  13814. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  13815. }
  13816. if (countFactors > 1) {
  13817. let firstId = factors[0].id;
  13818. let secondId = factors[1].id;
  13819. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13820. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13821. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, secondId)));
  13822. }
  13823. if (aradgi) {
  13824. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  13825. if (countFactors > 0) {
  13826. let firstId = factors[0].id;
  13827. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4000, 4013)));
  13828. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, 4013)));
  13829. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, 4013)));
  13830. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, 4013)));
  13831. }
  13832. if (edem) {
  13833. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4023, 4000, 4013)));
  13834. }
  13835. }
  13836. } else {
  13837. if (mode) {
  13838. for (let i = 0; i < factors.length; i++) {
  13839. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  13840. }
  13841. } else {
  13842. countFactors = factors.length < 2 ? factors.length : 2;
  13843. }
  13844. for (let i = 0; i < countFactors; i++) {
  13845. let mainId = factors[i].id;
  13846. if (aradgi && (mode || i > 0)) {
  13847. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, 4013)));
  13848. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, 4013)));
  13849. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, 4013)));
  13850. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, 4013)));
  13851. }
  13852. for (let i = 0; i < dark.length; i++) {
  13853. let darkId = dark[i];
  13854. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, darkId)));
  13855. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, darkId)));
  13856. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, darkId)));
  13857. }
  13858. for (let i = 0; i < light.length; i++) {
  13859. let lightId = light[i];
  13860. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, lightId)));
  13861. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, lightId)));
  13862. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, lightId)));
  13863. }
  13864. let isFull = mode || i > 0;
  13865. for (let j = isFull ? i + 1 : 2; j < factors.length; j++) {
  13866. let extraId = factors[j].id;
  13867. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, extraId)));
  13868. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, extraId)));
  13869. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, extraId)));
  13870. }
  13871. }
  13872. if (aradgi) {
  13873. if (mode) {
  13874. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  13875. }
  13876. for (let i = 0; i < dark.length; i++) {
  13877. let darkId = dark[i];
  13878. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4001, 4013)));
  13879. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4002, 4013)));
  13880. }
  13881. for (let i = 0; i < light.length; i++) {
  13882. let lightId = light[i];
  13883. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4001, 4013)));
  13884. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4002, 4013)));
  13885. }
  13886. }
  13887. for (let i = 0; i < dark.length; i++) {
  13888. let firstId = dark[i];
  13889. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  13890. for (let j = i + 1; j < dark.length; j++) {
  13891. let secondId = dark[j];
  13892. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13893. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13894. }
  13895. }
  13896. for (let i = 0; i < light.length; i++) {
  13897. let firstId = light[i];
  13898. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  13899. for (let j = i + 1; j < light.length; j++) {
  13900. let secondId = light[j];
  13901. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13902. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13903. }
  13904. }
  13905. }
  13906. for (let result of await Promise.all(actions)) {
  13907. let recovery = getRecovery(result);
  13908. if (recovery > bestBattle.recovery) {
  13909. bestBattle.recovery = recovery;
  13910. bestBattle.attackers = result.progress[0].attackers.heroes;
  13911. }
  13912. }
  13913. }
  13914.  
  13915. /** Получаем нейтральную команду */
  13916. function getNeutralTeam(id, swapId, addId) {
  13917. let neutralTeam = clone(teams.water);
  13918. let neutral = neutralTeam.heroes;
  13919. if (neutral.length == 4) {
  13920. if (!!swapId) {
  13921. for (let i in neutral) {
  13922. if (neutral[i] == swapId) {
  13923. neutral[i] = addId;
  13924. }
  13925. }
  13926. }
  13927. } else if (!!addId) {
  13928. neutral.push(addId);
  13929. }
  13930. neutral.push(id);
  13931. return neutralTeam;
  13932. }
  13933.  
  13934. /** Получить команду титанов */
  13935. function getTeam(titans) {
  13936. return {
  13937. favor: {},
  13938. heroes: Object.keys(titans).map(id => parseInt(id)),
  13939. teamNum: 0,
  13940. };
  13941. }
  13942.  
  13943. /** Вычисляем фактор боеготовности титанов */
  13944. function calcFactor() {
  13945. let neutral = teams.neutral;
  13946. let factors = [];
  13947. for (let i in neutral) {
  13948. let titanId = neutral[i];
  13949. let titan = titansStates[titanId];
  13950. let factor = !!titan ? titan.hp / titan.maxHp + titan.energy / 10000.0 : 1;
  13951. if (factor > 0) {
  13952. factors.push({id: titanId, value: factor});
  13953. }
  13954. }
  13955. factors.sort(function(a, b) {
  13956. return a.value - b.value;
  13957. });
  13958. return factors;
  13959. }
  13960.  
  13961. /** Возвращает наилучший результат из нескольких боев */
  13962. async function getBestRecovery(teamNum, attackerType, team, countBattle) {
  13963. let bestRecovery = -1000;
  13964. let actions = [];
  13965. for (let i = 0; i < countBattle; i++) {
  13966. actions.push(startBattle(teamNum, attackerType, team));
  13967. }
  13968. for (let result of await Promise.all(actions)) {
  13969. let recovery = getRecovery(result);
  13970. if (recovery > bestRecovery) {
  13971. bestRecovery = recovery;
  13972. }
  13973. }
  13974. return bestRecovery;
  13975. }
  13976.  
  13977. /** Возвращает разницу в здоровье атакующей команды после и до битвы и проверяет здоровье титанов на необходимый минимум*/
  13978. function getRecovery(result) {
  13979. if (result.result.stars < 3) {
  13980. return -100;
  13981. }
  13982. let beforeSumFactor = 0;
  13983. let afterSumFactor = 0;
  13984. let beforeTitans = result.battleData.attackers;
  13985. let afterTitans = result.progress[0].attackers.heroes;
  13986. for (let i in afterTitans) {
  13987. let titan = afterTitans[i];
  13988. let percentHP = titan.hp / beforeTitans[i].hp;
  13989. let energy = titan.energy;
  13990. let factor = checkTitan(i, energy, percentHP) ? getFactor(i, energy, percentHP) : -100;
  13991. afterSumFactor += factor;
  13992. }
  13993. for (let i in beforeTitans) {
  13994. let titan = beforeTitans[i];
  13995. let state = titan.state;
  13996. beforeSumFactor += !!state ? getFactor(i, state.energy, state.hp / titan.hp) : 1;
  13997. }
  13998. return afterSumFactor - beforeSumFactor;
  13999. }
  14000.  
  14001. /** Возвращает состояние титана*/
  14002. function getFactor(id, energy, percentHP) {
  14003. let elemantId = id.slice(2, 3);
  14004. let isEarthOrFire = elemantId == '1' || elemantId == '2';
  14005. let energyBonus = id == '4020' && energy == 1000 ? 0.1 : energy / 20000.0;
  14006. let factor = percentHP + energyBonus;
  14007. return isEarthOrFire ? factor : factor / 10;
  14008. }
  14009.  
  14010. /** Проверяет состояние титана*/
  14011. function checkTitan(id, energy, percentHP) {
  14012. switch (id) {
  14013. case '4020':
  14014. return percentHP > 0.25 || (energy == 1000 && percentHP > 0.05);
  14015. break;
  14016. case '4010':
  14017. return percentHP + energy / 2000.0 > 0.63;
  14018. break;
  14019. case '4000':
  14020. return percentHP > 0.62 || (energy < 1000 && (
  14021. (percentHP > 0.45 && energy >= 400) ||
  14022. (percentHP > 0.3 && energy >= 670)));
  14023. }
  14024. return true;
  14025. }
  14026.  
  14027.  
  14028. /** Начинаем бой */
  14029. function startBattle(teamNum, attackerType, args) {
  14030. return new Promise(function (resolve, reject) {
  14031. args.teamNum = teamNum;
  14032. let startBattleCall = {
  14033. calls: [{
  14034. name: "dungeonStartBattle",
  14035. args,
  14036. ident: "body"
  14037. }]
  14038. }
  14039. send(JSON.stringify(startBattleCall), resultBattle, {
  14040. resolve,
  14041. teamNum,
  14042. attackerType
  14043. });
  14044. });
  14045. }
  14046.  
  14047. /** Возращает результат боя в промис */
  14048. /*function resultBattle(resultBattles, args) {
  14049. if (!!resultBattles && !!resultBattles.results) {
  14050. let battleData = resultBattles.results[0].result.response;
  14051. let battleType = "get_tower";
  14052. if (battleData.type == "dungeon_titan") {
  14053. battleType = "get_titan";
  14054. }
  14055. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];//тест подземка правки
  14056. BattleCalc(battleData, battleType, function (result) {
  14057. result.teamNum = args.teamNum;
  14058. result.attackerType = args.attackerType;
  14059. args.resolve(result);
  14060. });
  14061. } else {
  14062. endDungeon('Потеряна связь с сервером игры!', 'break');
  14063. }
  14064. }*/
  14065. function resultBattle(resultBattles, args) {
  14066. battleData = resultBattles.results[0].result.response;
  14067. battleType = "get_tower";
  14068. if (battleData.type == "dungeon_titan") {
  14069. battleType = "get_titan";
  14070. }
  14071. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  14072. BattleCalc(battleData, battleType, function (result) {
  14073. result.teamNum = args.teamNum;
  14074. result.attackerType = args.attackerType;
  14075. args.resolve(result);
  14076. });
  14077. }
  14078.  
  14079. /** Заканчиваем бой */
  14080.  
  14081. ////
  14082. async function endBattle(battleInfo) {
  14083. if (!!battleInfo) {
  14084. const args = {
  14085. result: battleInfo.result,
  14086. progress: battleInfo.progress,
  14087. }
  14088. if (battleInfo.result.stars < 3) {
  14089. endDungeon('Герой или Титан мог погибнуть в бою!', battleInfo);
  14090. return;
  14091. }
  14092. if (countPredictionCard > 0) {
  14093. args.isRaid = true;
  14094. } else {
  14095. const timer = getTimer(battleInfo.battleTime);
  14096. console.log(timer);
  14097. await countdownTimer(timer, `${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity} ${talentMsg}`);
  14098. }
  14099. const calls = [{
  14100. name: "dungeonEndBattle",
  14101. args,
  14102. ident: "body"
  14103. }];
  14104. lastDungeonBattleData = null;
  14105. send(JSON.stringify({ calls }), resultEndBattle);
  14106. } else {
  14107. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  14108. }
  14109. }
  14110. /** Получаем и обрабатываем результаты боя */
  14111. function resultEndBattle(e) {
  14112. if (!!e && !!e.results) {
  14113. let battleResult = e.results[0].result.response;
  14114. if ('error' in battleResult) {
  14115. endDungeon('errorBattleResult', battleResult);
  14116. return;
  14117. }
  14118. let dungeonGetInfo = battleResult.dungeon ?? battleResult;
  14119. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  14120. checkFloor(dungeonGetInfo);
  14121. } else {
  14122. endDungeon('Потеряна связь с сервером игры!', 'break');
  14123. }
  14124. }
  14125.  
  14126. /** Добавить команду титанов в общий список команд */
  14127. function addTeam(team) {
  14128. for (let i in countTeam) {
  14129. if (equalsTeam(countTeam[i].team, team)) {
  14130. countTeam[i].count++;
  14131. return;
  14132. }
  14133. }
  14134. countTeam.push({team: team, count: 1});
  14135. }
  14136.  
  14137. /** Сравнить команды на равенство */
  14138. function equalsTeam(team1, team2) {
  14139. if (team1.length == team2.length) {
  14140. for (let i in team1) {
  14141. if (team1[i] != team2[i]) {
  14142. return false;
  14143. }
  14144. }
  14145. return true;
  14146. }
  14147. return false;
  14148. }
  14149.  
  14150. function saveProgress() {
  14151. let saveProgressCall = {
  14152. calls: [{
  14153. name: "dungeonSaveProgress",
  14154. args: {},
  14155. ident: "body"
  14156. }]
  14157. }
  14158. send(JSON.stringify(saveProgressCall), resultEndBattle);
  14159. }
  14160.  
  14161.  
  14162. /** Выводит статистику прохождения подземелья */
  14163. function showStats() {
  14164. let activity = dungeonActivity - startDungeonActivity;
  14165. let workTime = clone(timeDungeon);
  14166. workTime.all = new Date().getTime() - workTime.all;
  14167. for (let i in workTime) {
  14168. workTime[i] = (workTime[i] / 1000).round(0);
  14169. }
  14170. countTeam.sort(function(a, b) {
  14171. return b.count - a.count;
  14172. });
  14173. console.log(titansStates);
  14174. console.log("Собрано титанита: ", activity);
  14175. console.log("Скорость сбора: " + (3600 * activity / workTime.all).round(0) + " титанита/час");
  14176. console.log("Время раскопок: ");
  14177. for (let i in workTime) {
  14178. let timeNow = workTime[i];
  14179. console.log(i + ": ", (timeNow / 3600).round(0) + " ч. " + (timeNow % 3600 / 60).round(0) + " мин. " + timeNow % 60 + " сек.");
  14180. }
  14181. console.log("Частота использования команд: ");
  14182. for (let i in countTeam) {
  14183. let teams = countTeam[i];
  14184. console.log(teams.team + ": ", teams.count);
  14185. }
  14186. }
  14187.  
  14188. /** Заканчиваем копать подземелье */
  14189. function endDungeon(reason, info) {
  14190. if (!end) {
  14191. end = true;
  14192. console.log(reason, info);
  14193. showStats();
  14194. if (info == 'break') {
  14195. setProgress('Dungeon stoped: Титанит ' + dungeonActivity + '/' + maxDungeonActivity +
  14196. "\r\nПотеряна связь с сервером игры!", false, hideProgress);
  14197. } else {
  14198. setProgress('Dungeon completed: Титанит ' + dungeonActivity + '/' + maxDungeonActivity, false, hideProgress);
  14199. }
  14200. setTimeout(cheats.refreshGame, 1000);
  14201. resolve();
  14202. }
  14203. }
  14204. }
  14205.  
  14206. //дарим подарки участникам других гильдий не выходя из своей гильдии
  14207. function NewYearGift_Clan() {
  14208. console.log('NewYearGift_Clan called...');
  14209. const userID = getInput('userID');
  14210. const AmontID = getInput('AmontID');
  14211. const GiftNum = getInput('GiftNum');
  14212.  
  14213. const data = {
  14214. "calls": [{
  14215. "name": "newYearGiftSend",
  14216. "args": {
  14217. "userId": userID,
  14218. "amount": AmontID,
  14219. "giftNum": GiftNum,
  14220. "users": {
  14221. [userID]: AmontID
  14222. }
  14223. },
  14224. "ident": "body"
  14225. }
  14226. ]
  14227. }
  14228.  
  14229. const dataJson = JSON.stringify(data);
  14230.  
  14231. SendRequest(dataJson, e => {
  14232. let userInfo = e.results[0].result.response;
  14233. console.log(userInfo);
  14234. });
  14235. setProgress(I18N('SEND_GIFT'), true);
  14236. }
  14237. })();
  14238.  
  14239. /**
  14240. * TODO:
  14241. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  14242. * Добивание на арене титанов
  14243. * Закрытие окошек по Esc +-
  14244. * Починить работу скрипта на уровне команды ниже 10 +-
  14245. * Написать нормальную синхронизацию
  14246. * Запрет сбора квестов и отправки экспеиций в промежуток между локальным обновлением и глобальным обновлением дня
  14247. * Улучшение боев
  14248. */