HeroWarsHelper

Automation of actions for the game Hero Wars

目前为 2023-06-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.072
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage http://ilovemycomp.narod.ru/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @encoding utf-8
  16. // @include https://*.nextersglobal.com/*
  17. // @include https://*.hero-wars*.com/*
  18. // @match https://www.solfors.com/
  19. // @match https://t.me/s/hw_ru
  20. // @run-at document-start
  21. // ==/UserScript==
  22.  
  23. (function() {
  24. /**
  25. * Start script
  26. *
  27. * Стартуем скрипт
  28. */
  29. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  30. /**
  31. * Script info
  32. *
  33. * Информация о скрипте
  34. */
  35. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  36. ({name, version, author, homepage, lastModified, updateUrl, source}))
  37. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  38. /**
  39. * If we are on the gifts page, then we collect and send them to the server
  40. *
  41. * Если находимся на странице подарков, то собираем и отправляем их на сервер
  42. */
  43. if (['www.solfors.com', 't.me'].includes(location.host)) {
  44. setTimeout(sendCodes, 2000);
  45. return;
  46. }
  47. /**
  48. * Information for completing daily quests
  49. *
  50. * Информация для выполнения ежендевных квестов
  51. */
  52. const questsInfo = {};
  53. /**
  54. * Is the game data loaded
  55. *
  56. * Загружены ли данные игры
  57. */
  58. let isLoadGame = false;
  59. /**
  60. * Headers of the last request
  61. *
  62. * Заголовки последнего запроса
  63. */
  64. let lastHeaders = {};
  65. /**
  66. * Information about sent gifts
  67. *
  68. * Информация об отправленных подарках
  69. */
  70. let freebieCheckInfo = null;
  71. /**
  72. * User data
  73. *
  74. * Данные пользователя
  75. */
  76. let userInfo;
  77. /**
  78. * Original methods for working with AJAX
  79. *
  80. * Оригинальные методы для работы с AJAX
  81. */
  82. const original = {
  83. open: XMLHttpRequest.prototype.open,
  84. send: XMLHttpRequest.prototype.send,
  85. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  86. };
  87. /**
  88. * Decoder for converting byte data to JSON string
  89. *
  90. * Декодер для перобразования байтовых данных в JSON строку
  91. */
  92. const decoder = new TextDecoder("utf-8");
  93. /**
  94. * Stores a history of requests
  95. *
  96. * Хранит историю запросов
  97. */
  98. let requestHistory = {};
  99. /**
  100. * URL for API requests
  101. *
  102. * URL для запросов к API
  103. */
  104. let apiUrl = '';
  105.  
  106. /**
  107. * Connecting to the game code
  108. *
  109. * Подключение к коду игры
  110. */
  111. this.cheats = new hackGame();
  112. /**
  113. * The function of calculating the results of the battle
  114. *
  115. * Функция расчета результатов боя
  116. */
  117. this.BattleCalc = cheats.BattleCalc;
  118. /**
  119. * Sending a request available through the console
  120. *
  121. * Отправка запроса доступная через консоль
  122. */
  123. this.SendRequest = send;
  124. /**
  125. * Simple combat calculation available through the console
  126. *
  127. * Простой расчет боя доступный через консоль
  128. */
  129. this.Calc = function (data) {
  130. const type = getBattleType(data?.type);
  131. return new Promise((resolve, reject) => {
  132. try {
  133. BattleCalc(data, type, resolve);
  134. } catch (e) {
  135. reject(e);
  136. }
  137. })
  138. }
  139. /**
  140. * Short asynchronous request
  141. * Usage example (returns information about a character):
  142. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  143. *
  144. * Короткий асинхронный запрос
  145. * Пример использования (возвращает информацию о персонаже):
  146. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  147. */
  148. this.Send = function (json, pr) {
  149. return new Promise((resolve, reject) => {
  150. try {
  151. send(json, resolve, pr);
  152. } catch (e) {
  153. reject(e);
  154. }
  155. })
  156. }
  157.  
  158. const i18nLangData = {
  159. en: {
  160. /* Checkboxes */
  161. SKIP_FIGHTS: 'Skip battle',
  162. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  163. ENDLESS_CARDS: 'Endless cards',
  164. ENDLESS_CARDS_TITLE: 'Endless Prediction Cards',
  165. AUTO_EXPEDITION: 'Auto Expedition',
  166. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  167. CANCEL_FIGHT: 'Cancel battle',
  168. CANCEL_FIGHT_TITLE: 'The possibility of canceling the battle on VG',
  169. GIFTS: 'Gifts',
  170. GIFTS_TITLE: 'Collect gifts automatically',
  171. BATTLE_RECALCULATION: 'Battle recalculation',
  172. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  173. QUANTITY_CONTROL: 'Quantity control',
  174. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  175. REPEAT_CAMPAIGN: 'Repeat missions',
  176. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  177. DISABLE_DONAT: 'Disable donation',
  178. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  179. DAILY_QUESTS: 'Daily quests',
  180. DAILY_QUESTS_TITLE: 'Complete daily quests',
  181. AUTO_QUIZ: 'AutoQuiz',
  182. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  183. /* Input fields */
  184. HOW_MUCH_TITANITE: 'How much titanite to farm',
  185. COMBAT_SPEED: 'Combat Speed Multiplier',
  186. NUMBER_OF_TEST: 'Number of test fights',
  187. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  188. /* Buttons */
  189. RUN_SCRIPT: 'Run the',
  190. TO_DO_EVERYTHING: 'Do All',
  191. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  192. OUTLAND: 'Outland',
  193. OUTLAND_TITLE: 'Collect Outland',
  194. TITAN_ARENA: 'ToE',
  195. TITAN_ARENA_TITLE: 'Complete the titan arena',
  196. DUNGEON: 'Dungeon',
  197. DUNGEON_TITLE: 'Go through the dungeon',
  198. TOWER: 'Tower',
  199. TOWER_TITLE: 'Pass the tower',
  200. EXPEDITIONS: 'Expeditions',
  201. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  202. SYNC: 'Sync',
  203. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  204. ARCHDEMON: 'Archdemon',
  205. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  206. ESTER_EGGS: 'Easter eggs',
  207. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  208. REWARDS: 'Rewards',
  209. REWARDS_TITLE: 'Collect all quest rewards',
  210. MAIL: 'Mail',
  211. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  212. MINIONS: 'Minions',
  213. MINIONS_TITLE: 'Attack minions with saved packs',
  214. ADVENTURE: 'Adventure',
  215. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  216. STORM: 'Storm',
  217. STORM_TITLE: 'Passes the Storm along the specified route',
  218. SANCTUARY: 'Sanctuary',
  219. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  220. GUILD_WAR: 'Guild War',
  221. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  222. /* Misc */
  223. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank">tg</a>',
  224. GIFTS_SENT: 'Gifts sent!',
  225. DO_YOU_WANT: "Do you really want to do this?",
  226. BTN_RUN: 'Run',
  227. BTN_CANCEL: 'Cancel',
  228. BTN_OK: 'OK',
  229. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  230. BTN_AUTO: 'Auto',
  231. MSG_YOU_APPLIED: 'You applied',
  232. MSG_DAMAGE: 'damage',
  233. MSG_CANCEL_AND_STAT: 'Cancel and show statistic',
  234. MSG_REPEAT_MISSION: 'Repeat the mission?',
  235. BTN_REPEAT: 'Repeat',
  236. BTN_NO: 'No',
  237. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  238. BTN_OPEN: 'Open',
  239. QUESTION_COPY: 'Question copied to clipboard',
  240. ANSWER_KNOWN: 'The answer is known',
  241. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  242. BEING_RECALC: 'The battle is being recalculated',
  243. THIS_TIME: 'This time',
  244. VICTORY: 'VICTORY',
  245. DEFEAT: 'DEFEAT',
  246. CHANCE_TO_WIN: "Chance to win",
  247. OPEN_DOLLS: 'nesting dolls recursively',
  248. SENT_QUESTION: 'Question sent',
  249. SETTINGS: 'Settings',
  250. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  251. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  252. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  253. VALUES: 'Values',
  254. EXPEDITIONS_SENT: 'Expeditions sent',
  255. TITANIT: 'Titanit',
  256. COMPLETED: 'completed',
  257. FLOOR: 'Floor',
  258. LEVEL: 'Уровень',
  259. BATTLES: 'battles',
  260. EVENT: 'Event',
  261. NOT_AVAILABLE: 'not available',
  262. NO_HEROES: 'No heroes',
  263. DAMAGE_AMOUNT: 'Damage amount',
  264. NOTHING_TO_COLLECT: 'Nothing to collect',
  265. COLLECTED: 'Collected',
  266. REWARD: 'rewards',
  267. REMAINING_ATTEMPTS: 'Remaining attempts',
  268. BATTLES_CANCELED: 'Battles canceled',
  269. MINION_RAID: 'Minion Raid',
  270. STOPPED: 'Stopped',
  271. REPETITIONS: 'Repetitions',
  272. MISSIONS_PASSED: 'Missions passed',
  273. STOP: 'stop',
  274. TOTAL_OPEN: 'Total open',
  275. OPEN: 'Open',
  276. ROUND_STAT: 'Damage statistics for ',
  277. BATTLE: 'battles',
  278. MINIMUM: 'Minimum',
  279. MAXIMUM: 'Maximum',
  280. AVERAGE: 'Average',
  281. NOT_THIS_TIME: 'Not this time',
  282. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  283. SUCCESS: 'Success',
  284. RECEIVED: 'Received',
  285. LETTERS: 'letters',
  286. PORTALS: 'portals',
  287. ATTEMPTS: 'attempts',
  288. /* Quests */
  289. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  290. QUEST_10002: 'Complete 10 missions',
  291. QUEST_10003: 'Complete 3 heroic missions',
  292. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  293. QUEST_10006: 'Use the exchange of emeralds 1 time',
  294. QUEST_10007: 'Open 1 chest',
  295. QUEST_10016: 'Send gifts to guildmates',
  296. QUEST_10018: 'Use an experience potion',
  297. QUEST_10019: 'Open 1 chest in the Tower',
  298. QUEST_10020: 'Open 3 chests in Outland',
  299. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  300. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  301. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  302. QUEST_10024: 'Level up any artifact once',
  303. QUEST_10025: 'Start Expedition 1',
  304. QUEST_10026: 'Start 4 Expeditions',
  305. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  306. QUEST_10028: 'Level up any titan artifact',
  307. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  308. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  309. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  310. QUEST_10043: 'Start or Join an Adventure',
  311. QUEST_10044: 'Use Summon Pets 1 time',
  312. QUEST_10046: 'Open 3 chests in Adventure',
  313. QUEST_10047: 'Get 150 Guild Activity Points',
  314. NOTHING_TO_DO: 'Nothing to do',
  315. YOU_CAN_COMPLETE: 'You can complete quests',
  316. BTN_DO_IT: 'Do it',
  317. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  318. COMPLETED_QUESTS: 'Completed quests',
  319. /* everything button */
  320. ASSEMBLE_OUTLAND: 'Assemble Outland',
  321. PASS_THE_TOWER: 'Pass the tower',
  322. CHECK_EXPEDITIONS: 'Check Expeditions',
  323. COMPLETE_TOE: 'Complete ToE',
  324. COMPLETE_DUNGEON: 'Complete the dungeon',
  325. COLLECT_MAIL: 'Collect mail',
  326. COLLECT_MISC: 'Collect Easter Eggs, Skin Gems, Arena Keys and Coins',
  327. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  328. MAKE_A_SYNC: 'Make a sync',
  329.  
  330. RUN_FUNCTION: 'Run the following functions?',
  331. BTN_GO: 'Go!',
  332. PERFORMED: 'Performed',
  333. DONE: 'Done',
  334. ERRORS_OCCURRES: 'Errors occurred while executing',
  335. COPY_ERROR: 'Copy error information to clipboard',
  336. BTN_YES: 'Yes',
  337. ALL_TASK_COMPLETED: 'All tasks completed',
  338.  
  339. UNKNOWN: 'unknown',
  340. ENTER_THE_PATH: 'Enter the path of the adventure separated by commas',
  341. START_ADVENTURE: 'Start your adventure along this path!',
  342. BTN_CANCELED: 'Canceled',
  343. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  344. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  345. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  346. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  347. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  348. YES_CONTINUE: 'Yes, continue!',
  349. NOT_ENOUGH_AP: 'Not enough action points',
  350. ATTEMPTS_ARE_OVER: 'The attempts are over',
  351. MOVES: 'Moves',
  352. BUFF_GET_ERROR: 'Buff getting error',
  353. BATTLE_END_ERROR: 'Battle end error',
  354. AUTOBOT: 'Autobot',
  355. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  356. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  357. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  358. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  359.  
  360. },
  361. ru: {
  362. /* Чекбоксы */
  363. SKIP_FIGHTS: 'Пропуск боев',
  364. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  365. ENDLESS_CARDS: 'Бесконечные карты',
  366. ENDLESS_CARDS_TITLE: 'Бесконечные карты предсказаний',
  367. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  368. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  369. CANCEL_FIGHT: 'Отмена боя',
  370. CANCEL_FIGHT_TITLE: 'Возможность отмены боя на ВГ, СМ и в Асгарде',
  371. GIFTS: 'Подарки',
  372. GIFTS_TITLE: 'Собирать подарки автоматически',
  373. BATTLE_RECALCULATION: 'Прерасчет боя',
  374. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  375. QUANTITY_CONTROL: 'Контроль кол-ва',
  376. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  377. REPEAT_CAMPAIGN: 'Повтор в компании',
  378. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  379. DISABLE_DONAT: 'Отключить донат',
  380. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  381. DAILY_QUESTS: 'Ежедневные квесты',
  382. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  383. AUTO_QUIZ: 'АвтоВикторина',
  384. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  385. /* Поля ввода */
  386. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  387. COMBAT_SPEED: 'Множитель ускорения боя',
  388. NUMBER_OF_TEST: 'Количество тестовых боев',
  389. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  390. /* Кнопки */
  391. RUN_SCRIPT: 'Запустить скрипт',
  392. TO_DO_EVERYTHING: 'Сделать все',
  393. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  394. OUTLAND: 'Запределье',
  395. OUTLAND_TITLE: 'Собрать Запределье',
  396. TITAN_ARENA: 'Турнир Стихий',
  397. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  398. DUNGEON: 'Подземелье',
  399. DUNGEON_TITLE: 'Автопрохождение подземелья',
  400. TOWER: 'Башня',
  401. TOWER_TITLE: 'Автопрохождение башни',
  402. EXPEDITIONS: 'Экспедиции',
  403. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  404. SYNC: 'Синхронизация',
  405. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  406. ARCHDEMON: 'Архидемон',
  407. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  408. ESTER_EGGS: 'Пасхалки',
  409. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  410. REWARDS: 'Награды',
  411. REWARDS_TITLE: 'Собрать все награды за задания',
  412. MAIL: 'Почта',
  413. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  414. MINIONS: 'Прислужники',
  415. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  416. ADVENTURE: 'Приключение',
  417. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  418. STORM: 'Приключение',
  419. STORM_TITLE: 'Проходит приключение по указанному маршруту',
  420. SANCTUARY: 'Святилище',
  421. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  422. GUILD_WAR: 'Война гильдий',
  423. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  424. /* Разное */
  425. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank">tg</a> <a href="https://vk.com/invite/YNPxKGX" target="_blank">vk</a>',
  426. GIFTS_SENT: 'Подарки отправлены!',
  427. DO_YOU_WANT: "Вы действительно хотите это сделать?",
  428. BTN_RUN: 'Запускай',
  429. BTN_CANCEL: 'Отмена',
  430. BTN_OK: 'Ок',
  431. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  432. BTN_AUTO: 'Авто',
  433. MSG_YOU_APPLIED: 'Вы нанесли',
  434. MSG_DAMAGE: 'урона',
  435. MSG_CANCEL_AND_STAT: 'Отменить и показать Статистику',
  436. MSG_REPEAT_MISSION: 'Повторить миссию?',
  437. BTN_REPEAT: 'Повторить',
  438. BTN_NO: 'Нет',
  439. MSG_SPECIFY_QUANT: 'Указать количество:',
  440. BTN_OPEN: 'Открыть',
  441. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  442. ANSWER_KNOWN: 'Ответ известен',
  443. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  444. BEING_RECALC: 'Идет прерасчет боя',
  445. THIS_TIME: 'На этот раз',
  446. VICTORY: 'ПОБЕДА',
  447. DEFEAT: 'ПОРАЖЕНИЕ',
  448. CHANCE_TO_WIN: 'Шансы на победу',
  449. OPEN_DOLLS: 'матрешек рекурсивно',
  450. SENT_QUESTION: 'Вопрос отправлен',
  451. SETTINGS: 'Настройки',
  452. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  453. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  454. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  455. VALUES: 'Значения',
  456. EXPEDITIONS_SENT: 'Экспедиции отправлены',
  457. TITANIT: 'Титанит',
  458. COMPLETED: 'завершено',
  459. FLOOR: 'Этаж',
  460. LEVEL: 'Уровень',
  461. BATTLES: 'бои',
  462. EVENT: 'Эвент',
  463. NOT_AVAILABLE: 'недоступен',
  464. NO_HEROES: 'Нет героев',
  465. DAMAGE_AMOUNT: 'Количество урона',
  466. NOTHING_TO_COLLECT: 'Нечего собирать',
  467. COLLECTED: 'Собрано',
  468. REWARD: 'наград',
  469. REMAINING_ATTEMPTS: 'Осталось попыток',
  470. BATTLES_CANCELED: 'Битв отменено',
  471. MINION_RAID: 'Рейд прислужников',
  472. STOPPED: 'Остановлено',
  473. REPETITIONS: 'Повторений',
  474. MISSIONS_PASSED: 'Миссий пройдено',
  475. STOP: 'остановить',
  476. TOTAL_OPEN: 'Всего открыто',
  477. OPEN: 'Отркыто',
  478. ROUND_STAT: 'Статистика урона за',
  479. BATTLE: 'боев',
  480. MINIMUM: 'Минимальный',
  481. MAXIMUM: 'Максимальный',
  482. AVERAGE: 'Средний',
  483. NOT_THIS_TIME: 'Не в этот раз',
  484. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  485. SUCCESS: 'Успех',
  486. RECEIVED: 'Получено',
  487. LETTERS: 'писем',
  488. PORTALS: 'порталов',
  489. ATTEMPTS: 'попыток',
  490. QUEST_10001: 'Улучши умения героев 3 раза',
  491. QUEST_10002: 'Пройди 10 миссий',
  492. QUEST_10003: 'Пройди 3 героические миссии',
  493. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  494. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  495. QUEST_10007: 'Открой 1 сундук',
  496. QUEST_10016: 'Отправь подарки согильдийцам',
  497. QUEST_10018: 'Используй зелье опыта',
  498. QUEST_10019: 'Открой 1 сундук в Башне',
  499. QUEST_10020: 'Открой 3 сундука в Запределье',
  500. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  501. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  502. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  503. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  504. QUEST_10025: 'Начни 1 Экспедицию',
  505. QUEST_10026: 'Начни 4 Экспедиции',
  506. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  507. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  508. QUEST_10029: 'Открой сферу артефактов титанов',
  509. QUEST_10030: 'Улучши облик любого героя 1 раз',
  510. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  511. QUEST_10043: 'Начни или присоеденись к Приключению',
  512. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  513. QUEST_10046: 'Открой 3 сундука в Приключениях',
  514. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  515. NOTHING_TO_DO: 'Нечего выполнять',
  516. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  517. BTN_DO_IT: 'Выполняй',
  518. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  519. COMPLETED_QUESTS: 'Выполенно квестов',
  520. /* everything button */
  521. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  522. PASS_THE_TOWER: 'Пройти башню',
  523. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  524. COMPLETE_TOE: 'Пройти Турнир Стихий',
  525. COMPLETE_DUNGEON: 'Пройти подземелье',
  526. COLLECT_MAIL: 'Собрать почту',
  527. COLLECT_MISC: 'Собрать пасхалки, камни облика, ключи и монеты арены',
  528. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  529. MAKE_A_SYNC: 'Сделать синхронизацю',
  530.  
  531. RUN_FUNCTION: 'Выполнить следующие функции?',
  532. BTN_GO: 'Погнали!',
  533. PERFORMED: 'Выполняется',
  534. DONE: 'Выполено',
  535. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  536. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  537. BTN_YES: 'Да',
  538. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  539.  
  540. UNKNOWN: 'Неизвестно',
  541. ENTER_THE_PATH: 'Введите путь приключения через запятые',
  542. START_ADVENTURE: 'Начать приключение по этому пути!',
  543. BTN_CANCELED: 'Отменено',
  544. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  545. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  546. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  547. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  548. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  549. YES_CONTINUE: 'Да, продолжай!',
  550. NOT_ENOUGH_AP: 'Попыток не достаточно',
  551. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  552. MOVES: 'Ходы',
  553. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  554. BATTLE_END_ERROR: 'Ошибка завершения боя',
  555. AUTOBOT: 'АвтоБой',
  556. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  557. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  558. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  559. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  560. }
  561. }
  562.  
  563. let selectLang = 'en';
  564. function checkLang() {
  565. const html = document.querySelector('html')
  566. if (html && html.lang == 'ru') {
  567. selectLang = 'ru';
  568. } else {
  569. selectLang = 'en';
  570. }
  571. }
  572. checkLang();
  573.  
  574. this.I18N = function (constant) {
  575. if (constant && constant in i18nLangData[selectLang]) {
  576. return i18nLangData[selectLang][constant];
  577. }
  578. return `% ${constant} %`;
  579. };
  580.  
  581. /**
  582. * Checkboxes
  583. *
  584. * Чекбоксы
  585. */
  586. const checkboxes = {
  587. passBattle: {
  588. label: I18N('SKIP_FIGHTS'),
  589. cbox: null,
  590. title: I18N('SKIP_FIGHTS_TITLE'),
  591. default: false
  592. },
  593. endlessCards: {
  594. label: I18N('ENDLESS_CARDS'),
  595. cbox: null,
  596. title: I18N('ENDLESS_CARDS_TITLE'),
  597. default: true
  598. },
  599. sendExpedition: {
  600. label: I18N('AUTO_EXPEDITION'),
  601. cbox: null,
  602. title: I18N('AUTO_EXPEDITION_TITLE'),
  603. default: true
  604. },
  605. cancelBattleBan: {
  606. label: I18N('CANCEL_FIGHT'),
  607. cbox: null,
  608. title: I18N('CANCEL_FIGHT_TITLE'),
  609. default: false,
  610. },
  611. preCalcBattle: {
  612. label: I18N('BATTLE_RECALCULATION'),
  613. cbox: null,
  614. title: I18N('BATTLE_RECALCULATION_TITLE'),
  615. default: false
  616. },
  617. countControl: {
  618. label: I18N('QUANTITY_CONTROL'),
  619. cbox: null,
  620. title: I18N('QUANTITY_CONTROL_TITLE'),
  621. default: true
  622. },
  623. repeatMission: {
  624. label: I18N('REPEAT_CAMPAIGN'),
  625. cbox: null,
  626. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  627. default: false
  628. },
  629. noOfferDonat: {
  630. label: I18N('DISABLE_DONAT'),
  631. cbox: null,
  632. title: I18N('DISABLE_DONAT_TITLE'),
  633. /**
  634. * A crutch to get the field before getting the character id
  635. *
  636. * Костыль чтоб получать поле до получения id персонажа
  637. */
  638. default: (() => {
  639. $result = false;
  640. try {
  641. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  642. } catch(e) {
  643. $result = false;
  644. }
  645. return $result || false;
  646. })(),
  647. },
  648. dailyQuests: {
  649. label: I18N('DAILY_QUESTS'),
  650. cbox: null,
  651. title: I18N('DAILY_QUESTS_TITLE'),
  652. default: false
  653. }
  654. /*
  655. getAnswer: {
  656. label: I18N('AUTO_QUIZ'),
  657. cbox: null,
  658. title: I18N('AUTO_QUIZ_TITLE'),
  659. default: false
  660. }
  661. */
  662. };
  663. /**
  664. * Get checkbox state
  665. *
  666. * Получить состояние чекбокса
  667. */
  668. function isChecked(checkBox) {
  669. return checkboxes[checkBox].cbox?.checked;
  670. }
  671. /**
  672. * Input fields
  673. *
  674. * Поля ввода
  675. */
  676. const inputs = {
  677. countTitanit: {
  678. input: null,
  679. title: I18N('HOW_MUCH_TITANITE'),
  680. default: 150,
  681. },
  682. speedBattle: {
  683. input: null,
  684. title: I18N('COMBAT_SPEED'),
  685. default: 5,
  686. },
  687. countTestBattle: {
  688. input: null,
  689. title: I18N('NUMBER_OF_TEST'),
  690. default: 10,
  691. },
  692. countAutoBattle: {
  693. input: null,
  694. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  695. default: 10,
  696. }
  697. }
  698. /**
  699. * Checks the checkbox
  700. *
  701. * Поплучить данные поля ввода
  702. */
  703. function getInput(inputName) {
  704. return inputs[inputName].input.value;
  705. }
  706. /**
  707. * Button List
  708. *
  709. * Список кнопочек
  710. */
  711. const buttons = {
  712. getOutland: {
  713. name: I18N('TO_DO_EVERYTHING'),
  714. title: I18N('TO_DO_EVERYTHING_TITLE'),
  715. func: testDoYourBest,
  716. },
  717. /*
  718. getOutland: {
  719. name: I18N('OUTLAND'),
  720. title: I18N('OUTLAND_TITLE'),
  721. func: function () {
  722. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  723. },
  724. },
  725. */
  726. testTitanArena: {
  727. name: I18N('TITAN_ARENA'),
  728. title: I18N('TITAN_ARENA_TITLE'),
  729. func: function () {
  730. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  731. },
  732. },
  733. testDungeon: {
  734. name: I18N('DUNGEON'),
  735. title: I18N('DUNGEON_TITLE'),
  736. func: function () {
  737. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  738. },
  739. },
  740. /*
  741. testTower: {
  742. name: I18N('TOWER'),
  743. title: I18N('TOWER_TITLE'),
  744. func: function () {
  745. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  746. },
  747. },
  748. */
  749. sendExpedition: {
  750. name: I18N('EXPEDITIONS'),
  751. title: I18N('EXPEDITIONS_TITLE'),
  752. func: function () {
  753. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  754. },
  755. },
  756. newDay: {
  757. name: I18N('SYNC'),
  758. title: I18N('SYNC_TITLE'),
  759. func: function () {
  760. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  761. },
  762. },
  763. /*
  764. bossRatingEvent: {
  765. name: I18N('ARCHDEMON'),
  766. title: I18N('ARCHDEMON_TITLE'),
  767. func: function () {
  768. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  769. },
  770. },
  771. */
  772. /*
  773. offerFarmAllReward: {
  774. name: I18N('ESTER_EGGS'),
  775. title: I18N('ESTER_EGGS_TITLE'),
  776. func: function () {
  777. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  778. },
  779. },
  780. */
  781. questAllFarm: {
  782. name: I18N('REWARDS'),
  783. title: I18N('REWARDS_TITLE'),
  784. func: function () {
  785. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  786. },
  787. },
  788. mailGetAll: {
  789. name: I18N('MAIL'),
  790. title: I18N('MAIL_TITLE'),
  791. func: function () {
  792. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  793. },
  794. },
  795. testRaidNodes: {
  796. name: I18N('MINIONS'),
  797. title: I18N('MINIONS_TITLE'),
  798. func: function () {
  799. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  800. },
  801. },
  802. testAdventure: {
  803. name: I18N('ADVENTURE'),
  804. title: I18N('ADVENTURE_TITLE'),
  805. func: () => {
  806. testAdventure();
  807. },
  808. },
  809. /*
  810. testSoloAdventure: {
  811. name: I18N('STORM'),
  812. title: I18N('STORM_TITLE'),
  813. func: () => {
  814. testAdventure('solo');
  815. },
  816. },
  817. */
  818. goToSanctuary: {
  819. name: I18N('SANCTUARY'),
  820. title: I18N('SANCTUARY_TITLE'),
  821. func: cheats.goSanctuary,
  822. },
  823. goToClanWar: {
  824. name: I18N('GUILD_WAR'),
  825. title: I18N('GUILD_WAR_TITLE'),
  826. func: cheats.goClanWar,
  827. },
  828. }
  829. /**
  830. * Display buttons
  831. *
  832. * Вывести кнопочки
  833. */
  834. function addControlButtons() {
  835. for (let name in buttons) {
  836. button = buttons[name];
  837. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  838. }
  839. }
  840. /**
  841. * Adds links
  842. *
  843. * Добавляет ссылки
  844. */
  845. function addBottomUrls() {
  846. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  847. }
  848. /**
  849. * Stop repetition of the mission
  850. *
  851. * Остановить повтор миссии
  852. */
  853. let isStopSendMission = false;
  854. /**
  855. * There is a repetition of the mission
  856. *
  857. * Идет повтор миссии
  858. */
  859. let isSendsMission = false;
  860. /**
  861. * Data on the past mission
  862. *
  863. * Данные о прошедшей мисии
  864. */
  865. let lastMissionStart = {}
  866.  
  867. /**
  868. * Data on the past attack on the boss
  869. *
  870. * Данные о прошедшей атаке на босса
  871. */
  872. let lastBossBattle = {}
  873. /**
  874. * Data for calculating the last battle with the boss
  875. *
  876. * Данные для расчете последнего боя с боссом
  877. */
  878. let lastBossBattleInfo = null;
  879. /**
  880. * Ability to cancel the battle in Asgard
  881. *
  882. * Возможность отменить бой в Астгарде
  883. */
  884. let isCancalBossBattle = true;
  885. /**
  886. * Information about the last battle
  887. *
  888. * Данные о прошедшей битве
  889. */
  890. let lastBattleArg = {}
  891. /**
  892. * The name of the function of the beginning of the battle
  893. *
  894. * Имя функции начала боя
  895. */
  896. let nameFuncStartBattle = '';
  897. /**
  898. * The name of the function of the end of the battle
  899. *
  900. * Имя функции конца боя
  901. */
  902. let nameFuncEndBattle = '';
  903. /**
  904. * Data for calculating the last battle
  905. *
  906. * Данные для расчета последнего боя
  907. */
  908. let lastBattleInfo = null;
  909. /**
  910. * The ability to cancel the battle
  911. *
  912. * Возможность отменить бой
  913. */
  914. let isCancalBattle = true;
  915.  
  916. /**
  917. * Certificator of the last open nesting doll
  918. *
  919. * Идетификатор последней открытой матрешки
  920. */
  921. let lastRussianDollId = null;
  922. /**
  923. * Cancel the training guide
  924. *
  925. * Отменить обучающее руководство
  926. */
  927. this.isCanceledTutorial = false;
  928.  
  929. /**
  930. * Data from the last question of the quiz
  931. *
  932. * Данные последнего вопроса викторины
  933. */
  934. let lastQuestion = null;
  935. /**
  936. * Answer to the last question of the quiz
  937. *
  938. * Ответ на последний вопрос викторины
  939. */
  940. let lastAnswer = null;
  941. /**
  942. * Flag for opening keys or titan artifact spheres
  943. *
  944. * Флаг открытия ключей или сфер артефактов титанов
  945. */
  946. let artifactChestOpen = false;
  947. /**
  948. * The name of the function to open keys or orbs of titan artifacts
  949. *
  950. * Имя функции открытия ключей или сфер артефактов титанов
  951. */
  952. let artifactChestOpenCallName = '';
  953.  
  954. /**
  955. * Copies the text to the clipboard
  956. *
  957. * Копирует тест в буфер обмена
  958. * @param {*} text copied text // копируемый текст
  959. */
  960. function copyText(text) {
  961. let copyTextarea = document.createElement("textarea");
  962. copyTextarea.style.opacity = "0";
  963. copyTextarea.textContent = text;
  964. document.body.appendChild(copyTextarea);
  965. copyTextarea.select();
  966. document.execCommand("copy");
  967. document.body.removeChild(copyTextarea);
  968. delete copyTextarea;
  969. }
  970. /**
  971. * Returns the history of requests
  972. *
  973. * Возвращает историю запросов
  974. */
  975. this.getRequestHistory = function() {
  976. return requestHistory;
  977. }
  978. /**
  979. * Generates a random integer from min to max
  980. *
  981. * Гененирует случайное целое число от min до max
  982. */
  983. const random = function (min, max) {
  984. return Math.floor(Math.random() * (max - min + 1) + min);
  985. }
  986. /**
  987. * Clearing the request history
  988. *
  989. * Очистка истоии запросов
  990. */
  991. setInterval(function () {
  992. let now = Date.now();
  993. for (let i in requestHistory) {
  994. if (now - i > 300000) {
  995. delete requestHistory[i];
  996. }
  997. }
  998. }, 300000);
  999. /**
  1000. * DOM Loading Event page
  1001. *
  1002. * Событие загрузки DOM дерева страницы
  1003. */
  1004. document.addEventListener("DOMContentLoaded", () => {
  1005. /**
  1006. * Create the script interface
  1007. *
  1008. * Создание интерфеса скрипта
  1009. */
  1010. createInterface();
  1011. });
  1012. /**
  1013. * Gift codes collecting and sending codes
  1014. *
  1015. * Сбор и отправка кодов подарков
  1016. */
  1017. function sendCodes() {
  1018. let codes = [], count = 0;
  1019. if (!localStorage['giftSendIds']) {
  1020. localStorage['giftSendIds'] = '';
  1021. }
  1022. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  1023. let url = e?.href;
  1024. if (!url) return;
  1025. url = new URL(url);
  1026. let giftId = url.searchParams.get('gift_id');
  1027. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  1028. localStorage['giftSendIds'] += ';' + giftId;
  1029. codes.push(giftId);
  1030. count++;
  1031. });
  1032.  
  1033. if (codes.length) {
  1034. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  1035. sendGiftsCodes(codes);
  1036. }
  1037.  
  1038. if (!count) {
  1039. setTimeout(sendCodes, 2000);
  1040. }
  1041. }
  1042. /**
  1043. * Checking sent codes
  1044. *
  1045. * Проверка отправленных кодов
  1046. */
  1047. function checkSendGifts() {
  1048. if (!freebieCheckInfo) {
  1049. return;
  1050. }
  1051.  
  1052. let giftId = freebieCheckInfo.args.giftId;
  1053. let valName = 'giftSendIds_' + userInfo.id;
  1054. localStorage[valName] = localStorage[valName] ?? '';
  1055. if (!localStorage[valName].includes(giftId)) {
  1056. localStorage[valName] += ';' + giftId;
  1057. sendGiftsCodes([giftId]);
  1058. }
  1059. }
  1060. /**
  1061. * Sending codes
  1062. *
  1063. * Отправка кодов
  1064. */
  1065. function sendGiftsCodes(codes) {
  1066. fetch('https://zingery.ru/heroes/setGifts.php', {
  1067. method: 'POST',
  1068. body: JSON.stringify(codes)
  1069. }).then(
  1070. response => response.json()
  1071. ).then(
  1072. data => {
  1073. if (data.result) {
  1074. console.log(I18N('GIFTS_SENT'));
  1075. }
  1076. }
  1077. )
  1078. }
  1079. /**
  1080. * Displays the dialog box
  1081. *
  1082. * Отображает диалоговое окно
  1083. */
  1084. function confShow(message, yesCallback, noCallback) {
  1085. let buts = [];
  1086. message = message || I18N('DO_YOU_WANT');
  1087. noCallback = noCallback || (() => {});
  1088. if (yesCallback) {
  1089. buts = [
  1090. { msg: I18N('BTN_RUN'), result: true},
  1091. { msg: I18N('BTN_CANCEL'), result: false},
  1092. ]
  1093. } else {
  1094. yesCallback = () => {};
  1095. buts = [
  1096. { msg: I18N('BTN_OK'), result: true},
  1097. ];
  1098. }
  1099. popup.confirm(message, buts).then((e) => {
  1100. if (e) {
  1101. yesCallback();
  1102. } else {
  1103. noCallback();
  1104. }
  1105. });
  1106. }
  1107. /**
  1108. * Overriding/Proxying the Ajax Request Creation Method
  1109. *
  1110. * Переопределяем/проксируем метод создания Ajax запроса
  1111. */
  1112. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1113. this.uniqid = Date.now();
  1114. this.errorRequest = false;
  1115. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1116. if (!apiUrl) {
  1117. apiUrl = url;
  1118. socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1119. sNetwork = socialInfo ? socialInfo[1] : 'vk';
  1120. }
  1121. requestHistory[this.uniqid] = {
  1122. method,
  1123. url,
  1124. error: [],
  1125. headers: {},
  1126. request: null,
  1127. response: null,
  1128. signature: [],
  1129. calls: {},
  1130. };
  1131. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1132. this.errorRequest = true;
  1133. }
  1134. return original.open.call(this, method, url, async, user, password);
  1135. };
  1136. /**
  1137. * Overriding/Proxying the header setting method for the AJAX request
  1138. *
  1139. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1140. */
  1141. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1142. if (this.uniqid in requestHistory) {
  1143. requestHistory[this.uniqid].headers[name] = value;
  1144. } else {
  1145. check = true;
  1146. }
  1147.  
  1148. if (name == 'X-Auth-Signature') {
  1149. requestHistory[this.uniqid].signature.push(value);
  1150. if (!check) {
  1151. return;
  1152. }
  1153. }
  1154.  
  1155. return original.setRequestHeader.call(this, name, value);
  1156. };
  1157. /**
  1158. * Overriding/Proxying the AJAX Request Sending Method
  1159. *
  1160. * Переопределяем/проксируем метод отправки AJAX запроса
  1161. */
  1162. XMLHttpRequest.prototype.send = async function (sourceData) {
  1163. if (this.uniqid in requestHistory) {
  1164. let tempData = null;
  1165. if (getClass(sourceData) == "ArrayBuffer") {
  1166. tempData = decoder.decode(sourceData);
  1167. } else {
  1168. tempData = sourceData;
  1169. }
  1170. requestHistory[this.uniqid].request = tempData;
  1171. let headers = requestHistory[this.uniqid].headers;
  1172. lastHeaders = Object.assign({}, headers);
  1173. /**
  1174. * Game loading event
  1175. *
  1176. * Событие загрузки игры
  1177. */
  1178. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1179. isLoadGame = true;
  1180. await openOrMigrateDatabase(userInfo.id);
  1181. addControls();
  1182. addControlButtons();
  1183. addBottomUrls();
  1184.  
  1185. if (isChecked('sendExpedition')) {
  1186. checkExpedition();
  1187. }
  1188.  
  1189. checkSendGifts();
  1190. getAutoGifts();
  1191.  
  1192. cheats.activateHacks();
  1193. justInfo();
  1194. if (isChecked('dailyQuests')) {
  1195. testDailyQuests();
  1196. }
  1197. }
  1198. /**
  1199. * Outgoing request data processing
  1200. *
  1201. * Обработка данных исходящего запроса
  1202. */
  1203. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1204. /**
  1205. * Handling incoming request data
  1206. *
  1207. * Обработка данных входящего запроса
  1208. */
  1209. const oldReady = this.onreadystatechange;
  1210. this.onreadystatechange = function (e) {
  1211. if(this.readyState == 4 && this.status == 200) {
  1212. isTextResponse = this.responseType != "json";
  1213. let response = isTextResponse ? this.responseText : this.response;
  1214. requestHistory[this.uniqid].response = response;
  1215. /**
  1216. * Replacing incoming request data
  1217. *
  1218. * Заменна данных входящего запроса
  1219. */
  1220. if (isTextResponse) {
  1221. checkChangeResponse.call(this, response);
  1222. }
  1223. /**
  1224. * A function to run after the request is executed
  1225. *
  1226. * Функция запускаемая после выполения запроса
  1227. */
  1228. if (typeof this.onReadySuccess == 'function') {
  1229. setTimeout(this.onReadySuccess, 500);
  1230. }
  1231. }
  1232. if (oldReady) {
  1233. return oldReady.apply(this, arguments);
  1234. }
  1235. }
  1236. }
  1237. if (this.errorRequest) {
  1238. const oldReady = this.onreadystatechange;
  1239. this.onreadystatechange = function () {
  1240. Object.defineProperty(this, 'status', {
  1241. writable: true
  1242. });
  1243. this.status = 200;
  1244. Object.defineProperty(this, 'readyState', {
  1245. writable: true
  1246. });
  1247. this.readyState = 4;
  1248. Object.defineProperty(this, 'responseText', {
  1249. writable: true
  1250. });
  1251. this.responseText = JSON.stringify({
  1252. "result": true
  1253. });
  1254. return oldReady.apply(this, arguments);
  1255. }
  1256. this.onreadystatechange();
  1257. } else {
  1258. return original.send.call(this, sourceData);
  1259. }
  1260. };
  1261. /**
  1262. * Processing and substitution of outgoing data
  1263. *
  1264. * Обработка и подмена исходящих данных
  1265. */
  1266. async function checkChangeSend(sourceData, tempData) {
  1267. try {
  1268. /**
  1269. * A function that replaces battle data with incorrect ones to cancel combatя
  1270. *
  1271. * Функция заменяющая данные боя на неверные для отмены боя
  1272. */
  1273. const fixBattle = function (heroes) {
  1274. for (const ids in heroes) {
  1275. hero = heroes[ids];
  1276. hero.energy = random(1, 999);
  1277. if (hero.hp > 0) {
  1278. hero.hp = random(1, hero.hp);
  1279. }
  1280. }
  1281. }
  1282. /**
  1283. * Dialog window 2
  1284. *
  1285. * Диалоговое окно 2
  1286. */
  1287. const showMsg = async function (msg, ansF, ansS) {
  1288. if (typeof popup == 'object') {
  1289. return await popup.confirm(msg, [
  1290. {msg: ansF, result: false},
  1291. {msg: ansS, result: true},
  1292. ]);
  1293. } else {
  1294. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1295. }
  1296. }
  1297. /**
  1298. * Dialog window 3
  1299. *
  1300. * Диалоговое окно 3
  1301. */
  1302. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1303. return await popup.confirm(msg, [
  1304. {msg: ansF, result: 0},
  1305. {msg: ansS, result: 1},
  1306. {msg: ansT, result: 2},
  1307. ]);
  1308. }
  1309.  
  1310. let changeRequest = false;
  1311. testData = JSON.parse(tempData);
  1312. for (const call of testData.calls) {
  1313. if (!artifactChestOpen) {
  1314. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1315. }
  1316. /**
  1317. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1318. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1319. */
  1320. if ((call.name == 'adventure_endBattle' ||
  1321. call.name == 'adventureSolo_endBattle' ||
  1322. call.name == 'clanWarEndBattle' && isChecked('cancelBattleBan') ||
  1323. call.name == 'crossClanWar_endBattle' && isChecked('cancelBattleBan') ||
  1324. call.name == 'brawl_endBattle' ||
  1325. call.name == 'towerEndBattle' ||
  1326. call.name == 'clanRaid_endNodeBattle') &&
  1327. isCancalBattle) {
  1328. nameFuncEndBattle = call.name;
  1329. if (!call.args.result.win) {
  1330. let resultPopup = false;
  1331. if (call.name == 'adventure_endBattle' ||
  1332. call.name == 'adventureSolo_endBattle') {
  1333. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1334. } else {
  1335. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1336. }
  1337. if (resultPopup) {
  1338. fixBattle(call.args.progress[0].attackers.heroes);
  1339. fixBattle(call.args.progress[0].defenders.heroes);
  1340. changeRequest = true;
  1341. if (resultPopup > 1) {
  1342. this.onReadySuccess = testAutoBattle;
  1343. // setTimeout(bossBattle, 1000);
  1344. }
  1345. }
  1346. }
  1347. }
  1348. /**
  1349. * Canceled fight in Asgard
  1350. * Отмена боя в Асгарде
  1351. */
  1352. if (call.name == 'clanRaid_endBossBattle' &&
  1353. isCancalBossBattle &&
  1354. isChecked('cancelBattleBan')) {
  1355. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1356. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1357. let resultPopup = await showMsgs(
  1358. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1359. I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('MSG_CANCEL_AND_STAT'))
  1360. if (resultPopup) {
  1361. fixBattle(call.args.progress[0].attackers.heroes);
  1362. fixBattle(call.args.progress[0].defenders.heroes);
  1363. changeRequest = true;
  1364. if (resultPopup > 1) {
  1365. this.onReadySuccess = testBossBattle;
  1366. // setTimeout(bossBattle, 1000);
  1367. }
  1368. }
  1369. }
  1370. /**
  1371. * Save the Asgard Boss Attack Pack
  1372. * Сохраняем пачку для атаки босса Асгарда
  1373. */
  1374. if (call.name == 'clanRaid_startBossBattle') {
  1375. lastBossBattle = call.args;
  1376. }
  1377. /**
  1378. * Saving the request to start the last battle
  1379. * Сохранение запроса начала последнего боя
  1380. */
  1381. if (call.name == 'clanWarAttack' ||
  1382. call.name == 'crossClanWar_startBattle' ||
  1383. call.name == 'adventure_turnStartBattle') {
  1384. nameFuncStartBattle = call.name;
  1385. lastBattleArg = call.args;
  1386. }
  1387. /**
  1388. * Disable spending divination cards
  1389. * Отключить трату карт предсказаний
  1390. */
  1391. if (call.name == 'dungeonEndBattle') {
  1392. if (isChecked('endlessCards') && call.args.isRaid) {
  1393. delete call.args.isRaid;
  1394. changeRequest = true;
  1395. }
  1396. }
  1397. /**
  1398. * Quiz Answer
  1399. * Ответ на викторину
  1400. */
  1401. if (call.name == 'quizAnswer') {
  1402. /**
  1403. * Automatically changes the answer to the correct one if there is one.
  1404. * Автоматически меняет ответ на правильный если он есть
  1405. */
  1406. if (lastAnswer && isChecked('getAnswer')) {
  1407. call.args.answerId = lastAnswer;
  1408. lastAnswer = null;
  1409. changeRequest = true;
  1410. }
  1411. }
  1412. /**
  1413. * Present
  1414. * Подарки
  1415. */
  1416. if (call.name == 'freebieCheck') {
  1417. freebieCheckInfo = call;
  1418. }
  1419. /**
  1420. * Getting mission data for auto-repeat
  1421. * Получение данных миссии для автоповтора
  1422. */
  1423. if (isChecked('repeatMission') &&
  1424. call.name == 'missionEnd') {
  1425. let missionInfo = {
  1426. id: call.args.id,
  1427. result: call.args.result,
  1428. heroes: call.args.progress[0].attackers.heroes,
  1429. count: 0,
  1430. }
  1431. setTimeout(async () => {
  1432. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  1433. { msg: I18N('BTN_REPEAT'), result: true},
  1434. { msg: I18N('BTN_NO'), result: false},
  1435. ])) {
  1436. isStopSendMission = false;
  1437. isSendsMission = true;
  1438. sendsMission(missionInfo);
  1439. }
  1440. }, 0);
  1441. }
  1442. /**
  1443. * Getting mission data
  1444. * Получение данных миссии
  1445. */
  1446. if (call.name == 'missionStart') {
  1447. lastMissionStart = call.args;
  1448. }
  1449. /**
  1450. * Specify the quantity for Titan Orbs and Pet Eggs
  1451. * Указать количество для сфер титанов и яиц петов
  1452. */
  1453. if (isChecked('countControl') &&
  1454. (call.name == 'pet_chestOpen' ||
  1455. call.name == 'titanUseSummonCircle') &&
  1456. call.args.amount > 1) {
  1457. call.args.amount = 1;
  1458. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1459. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  1460. ]);
  1461. if (result) {
  1462. call.args.amount = result;
  1463. changeRequest = true;
  1464. }
  1465. }
  1466. /**
  1467. * Specify the amount for keys and spheres of titan artifacts
  1468. * Указать колличество для ключей и сфер артефактов титанов
  1469. */
  1470. if (isChecked('countControl') &&
  1471. (call.name == 'artifactChestOpen' ||
  1472. call.name == 'titanArtifactChestOpen') &&
  1473. call.args.amount > 1 &&
  1474. !changeRequest) {
  1475. artifactChestOpenCallName = call.name;
  1476. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1477. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  1478. ]);
  1479. if (result) {
  1480. let sphere = result < 10 ? 1 : 10;
  1481.  
  1482. call.args.amount = sphere;
  1483. result -= sphere;
  1484.  
  1485. for (let count = result; count > 0; count -= sphere) {
  1486. if (count < 10) sphere = 1;
  1487. const ident = artifactChestOpenCallName + "_" + count;
  1488. testData.calls.push({
  1489. name: artifactChestOpenCallName,
  1490. args: {
  1491. amount: sphere,
  1492. free: true,
  1493. },
  1494. ident: ident
  1495. });
  1496. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  1497. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  1498. }
  1499. requestHistory[this.uniqid].calls[call.name].push(ident);
  1500. }
  1501.  
  1502. artifactChestOpen = true;
  1503. changeRequest = true;
  1504. }
  1505. }
  1506. if (call.name == 'consumableUseLootBox') {
  1507. lastRussianDollId = call.args.libId;
  1508. /**
  1509. * Specify quantity for gold caskets
  1510. * Указать количество для золотых шкатулок
  1511. */
  1512. if (isChecked('countControl') &&
  1513. call.args.libId == 148 &&
  1514. call.args.amount > 1) {
  1515. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  1516. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  1517. ]);
  1518. call.args.amount = result;
  1519. changeRequest = true;
  1520. }
  1521. }
  1522. }
  1523.  
  1524. let headers = requestHistory[this.uniqid].headers;
  1525. if (changeRequest) {
  1526. sourceData = JSON.stringify(testData);
  1527. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  1528. }
  1529.  
  1530. let signature = headers['X-Auth-Signature'];
  1531. if (signature) {
  1532. this.setRequestHeader('X-Auth-Signature', signature, true);
  1533. }
  1534. } catch (err) {
  1535. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  1536. }
  1537. return sourceData;
  1538. }
  1539. /**
  1540. * Processing and substitution of incoming data
  1541. *
  1542. * Обработка и подмена входящих данных
  1543. */
  1544. async function checkChangeResponse(response) {
  1545. try {
  1546. isChange = false;
  1547. let nowTime = Math.round(Date.now() / 1000);
  1548. callsIdent = requestHistory[this.uniqid].calls;
  1549. respond = JSON.parse(response);
  1550. /**
  1551. * If the request returned an error removes the error (removes synchronization errors)
  1552. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  1553. */
  1554. if (respond.error) {
  1555. isChange = true;
  1556. console.error(respond.error);
  1557. delete respond.error;
  1558. respond.results = [];
  1559. }
  1560. let mainReward = null;
  1561. const allReward = {};
  1562. for (const call of respond.results) {
  1563. /**
  1564. * Getting a user ID
  1565. * Получение идетификатора пользователя
  1566. */
  1567. if (call.ident == callsIdent['registration']) {
  1568. userId = call.result.response.userId;
  1569. }
  1570. /**
  1571. * Brawl
  1572. * Потасовка
  1573. */
  1574. if (call.ident == callsIdent['brawl_getInfo']) {
  1575. brawl = call.result.response;
  1576. if (brawl) {
  1577. brawl.boughtEndlessLivesToday = 1;
  1578. isChange = true;
  1579. }
  1580. }
  1581. /**
  1582. * Hiding donation offers
  1583. * Скрываем предложения доната
  1584. */
  1585. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  1586. const billings = call.result.response?.billings;
  1587. const bundle = call.result.response?.bundle;
  1588. if (billings && bundle) {
  1589. call.result.response.billings = [];
  1590. call.result.response.bundle = [];
  1591. isChange = true;
  1592. }
  1593. }
  1594. /**
  1595. * Hiding donation offers
  1596. * Скрываем предложения доната
  1597. */
  1598. if (call.ident == callsIdent['offerGetAll'] && getSaveVal('noOfferDonat')) {
  1599. const offers = call.result.response;
  1600. if (offers) {
  1601. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type));
  1602. isChange = true;
  1603. }
  1604. }
  1605. /**
  1606. * Copies a quiz question to the clipboard
  1607. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  1608. */
  1609. if (call.ident == callsIdent['quizGetNewQuestion']) {
  1610. let quest = call.result.response;
  1611. console.log(quest.question);
  1612. copyText(quest.question);
  1613. setProgress(I18N('QUESTION_COPY'), true);
  1614. lastQuestion = quest;
  1615. if (isChecked('getAnswer')) {
  1616. const answer = await getAnswer(lastQuestion);
  1617. if (answer) {
  1618. lastAnswer = answer;
  1619. console.log(answer);
  1620. setProgress(`${I18N('ANSWER_KNOWN')}: ${answer}`, true);
  1621. } else {
  1622. setProgress(I18N('ANSWER_NOT_KNOWN'), true);
  1623. }
  1624. }
  1625. }
  1626. /**
  1627. * Submits a question with an answer to the database
  1628. * Отправляет вопрос с ответом в базу данных
  1629. */
  1630. if (call.ident == callsIdent['quizAnswer']) {
  1631. const answer = call.result.response;
  1632. if (lastQuestion) {
  1633. const answerInfo = {
  1634. answer,
  1635. question: lastQuestion
  1636. }
  1637. lastQuestion = null;
  1638. setTimeout(sendAnswerInfo, 0, answerInfo);
  1639. }
  1640. }
  1641. /**
  1642. * Get user data
  1643. * Получить даныне пользователя
  1644. */
  1645. if (call.ident == callsIdent['userGetInfo']) {
  1646. let user = call.result.response;
  1647. userInfo = Object.assign({}, user);
  1648. delete userInfo.refillable;
  1649. if (!questsInfo['userGetInfo']) {
  1650. questsInfo['userGetInfo'] = user;
  1651. }
  1652. }
  1653. /**
  1654. * Start of the battle for recalculation
  1655. * Начало боя для прерасчета
  1656. */
  1657. if ((call.ident == callsIdent['clanWarAttack'] ||
  1658. call.ident == callsIdent['crossClanWar_startBattle'] ||
  1659. call.ident == callsIdent['battleGetReplay'] ||
  1660. call.ident == callsIdent['adventure_turnStartBattle']) &&
  1661. isChecked('preCalcBattle')) {
  1662. setProgress('Идет прерасчет боя');
  1663. let battle = call.result.response.battle || call.result.response.replay;
  1664. lastBattleInfo = battle;
  1665. console.log(battle.type);
  1666. function getBattleInfo(battle, isRandSeed) {
  1667. return new Promise(function (resolve) {
  1668. if (isRandSeed) {
  1669. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  1670. }
  1671. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  1672. });
  1673. }
  1674. let actions = [getBattleInfo(battle, false)]
  1675. const countTestBattle = getInput('countTestBattle');
  1676. for (let i = 0; i < countTestBattle; i++) {
  1677. actions.push(getBattleInfo(battle, true));
  1678. }
  1679. Promise.all(actions)
  1680. .then(e => {
  1681. let firstBattle = e.shift();
  1682. let countWin = e.reduce((w, s) => w + s);
  1683. setProgress(`${I18N('THIS_TIME')} ${(firstBattle ? I18N('VICTORY') : I18N('DEFEAT'))} ${I18N('CHANCE_TO_WIN')}: ${Math.floor(countWin / e.length * 100)}% (${e.length})`, false, hideProgress)
  1684. });
  1685. }
  1686. /**
  1687. * Start of the Asgard boss fight
  1688. * Начало боя с боссом Асгарда
  1689. */
  1690. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  1691. lastBossBattleInfo = call.result.response.battle;
  1692. }
  1693. /**
  1694. * Cancel tutorial
  1695. * Отмена туториала
  1696. */
  1697. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  1698. let chains = call.result.response.chains;
  1699. for (let n in chains) {
  1700. chains[n] = 9999;
  1701. }
  1702. isChange = true;
  1703. }
  1704. /**
  1705. * Opening keys and spheres of titan artifacts
  1706. * Открытие ключей и сфер артефактов титанов
  1707. */
  1708. if (artifactChestOpen &&
  1709. (call.ident == callsIdent[artifactChestOpenCallName] ||
  1710. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  1711. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  1712.  
  1713. reward.forEach(e => {
  1714. for (let f in e) {
  1715. if (!allReward[f]) {
  1716. allReward[f] = {};
  1717. }
  1718. for (let o in e[f]) {
  1719. if (!allReward[f][o]) {
  1720. allReward[f][o] = e[f][o];
  1721. } else {
  1722. allReward[f][o] += e[f][o];
  1723. }
  1724. }
  1725. }
  1726. });
  1727.  
  1728. if (!call.ident.includes(artifactChestOpenCallName)) {
  1729. mainReward = call.result.response;
  1730. }
  1731. }
  1732. /**
  1733. * Auto-repeat opening matryoshkas
  1734. * АвтоПовтор открытия матрешек
  1735. */
  1736. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  1737. let lootBox = call.result.response;
  1738. let newCount = 0;
  1739. for (let n of lootBox) {
  1740. if (n?.consumable && n.consumable[lastRussianDollId]) {
  1741. newCount += n.consumable[lastRussianDollId]
  1742. }
  1743. }
  1744. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  1745. { msg: I18N('BTN_OPEN'), result: true},
  1746. { msg: I18N('BTN_NO'), result: false},
  1747. ])) {
  1748. openRussianDoll(lastRussianDollId, newCount);
  1749. }
  1750. }
  1751. /**
  1752. * Getting data on quests
  1753. * Получение данных по квестам
  1754. */
  1755. if (call.ident == callsIdent['questGetAll']) {
  1756. if (!questsInfo['questGetAll']) {
  1757. questsInfo['questGetAll'] = call.result.response;
  1758. }
  1759. }
  1760. /**
  1761. * Getting Inventory Data for Quests
  1762. * Получение данных инвентаря для квестов
  1763. */
  1764. if (call.ident == callsIdent['inventoryGet']) {
  1765. if (!questsInfo['inventoryGet']) {
  1766. questsInfo['inventoryGet'] = call.result.response;
  1767. }
  1768. }
  1769. /**
  1770. * Obtaining Hero Data for Quests
  1771. * Получение данных героев для квестов
  1772. */
  1773. if (call.ident == callsIdent['heroGetAll']) {
  1774. if (!questsInfo['heroGetAll']) {
  1775. questsInfo['heroGetAll'] = call.result.response;
  1776. }
  1777. }
  1778. /**
  1779. * Obtaining titan data for quests
  1780. * Получение данных титанов для квестов
  1781. */
  1782. if (call.ident == callsIdent['titanGetAll']) {
  1783. if (!questsInfo['titanGetAll']) {
  1784. questsInfo['titanGetAll'] = call.result.response;
  1785. }
  1786. }
  1787. }
  1788.  
  1789. if (mainReward && artifactChestOpen) {
  1790. console.log(allReward);
  1791. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  1792. artifactChestOpen = false;
  1793. artifactChestOpenCallName = '';
  1794. isChange = true;
  1795. }
  1796. } catch(err) {
  1797. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  1798. }
  1799.  
  1800. if (isChange) {
  1801. Object.defineProperty(this, 'responseText', {
  1802. writable: true
  1803. });
  1804. this.responseText = JSON.stringify(respond);
  1805. }
  1806. }
  1807.  
  1808. /**
  1809. * Request an answer to a question
  1810. *
  1811. * Запрос ответа на вопрос
  1812. */
  1813. async function getAnswer(question) {
  1814. return new Promise((resolve, reject) => {
  1815. fetch('https://zingery.ru/heroes/getAnswer.php', {
  1816. method: 'POST',
  1817. body: JSON.stringify(question)
  1818. }).then(
  1819. response => response.json()
  1820. ).then(
  1821. data => {
  1822. if (data.result) {
  1823. resolve(data.result);
  1824. } else {
  1825. resolve(false);
  1826. }
  1827. }
  1828. ).catch((error) => {
  1829. console.error(error);
  1830. resolve(false);
  1831. });
  1832. })
  1833. }
  1834.  
  1835. /**
  1836. * Submitting a question and answer to a database
  1837. *
  1838. * Отправка вопроса и ответа в базу данных
  1839. */
  1840. function sendAnswerInfo(answerInfo) {
  1841. fetch('https://zingery.ru/heroes/setAnswer.php', {
  1842. method: 'POST',
  1843. body: JSON.stringify(answerInfo)
  1844. }).then(
  1845. response => response.json()
  1846. ).then(
  1847. data => {
  1848. if (data.result) {
  1849. console.log(I18N('SENT_QUESTION'));
  1850. }
  1851. }
  1852. )
  1853. }
  1854.  
  1855. /**
  1856. * Returns the battle type by preset type
  1857. *
  1858. * Возвращает тип боя по типу пресета
  1859. */
  1860. function getBattleType(strBattleType) {
  1861. switch (strBattleType) {
  1862. case "invasion":
  1863. return "get_invasion";
  1864. case "titan_pvp_manual":
  1865. return "get_titanPvpManual";
  1866. case "titan_pvp":
  1867. return "get_titanPvp";
  1868. case "titan_clan_pvp":
  1869. case "clan_pvp_titan":
  1870. case "clan_global_pvp_titan":
  1871. case "challenge_titan":
  1872. return "get_titanClanPvp";
  1873. case "clan_raid": // Asgard Boss // Босс асгарда
  1874. case "adventure": // Adventures // Приключения
  1875. case "clan_global_pvp":
  1876. case "clan_pvp":
  1877. case "challenge":
  1878. case "grand":
  1879. case "arena":
  1880. return "get_clanPvp";
  1881. case "titan_tower":
  1882. return "get_titan";
  1883. case "tower":
  1884. return "get_tower";
  1885. case "pve":
  1886. return "get_pve";
  1887. case "pvp_manual":
  1888. return "get_pvpManual";
  1889. case "pvp":
  1890. return "get_pvp";
  1891. case "core":
  1892. return "get_core";
  1893. default:
  1894. return "get_clanPvp";
  1895. }
  1896. }
  1897. /**
  1898. * Returns the class name of the passed object
  1899. *
  1900. * Возвращает название класса переданного объекта
  1901. */
  1902. function getClass(obj) {
  1903. return {}.toString.call(obj).slice(8, -1);
  1904. }
  1905. /**
  1906. * Calculates the request signature
  1907. *
  1908. * Расчитывает сигнатуру запроса
  1909. */
  1910. this.getSignature = function(headers, data) {
  1911. let signatureStr = [headers["X-Request-Id"], headers["X-Auth-Token"], headers["X-Auth-Session-Id"], data, 'LIBRARY-VERSION=1'].join(':');
  1912. return md5(signatureStr);
  1913. }
  1914. /**
  1915. * Creates an interface
  1916. *
  1917. * Создает интерфейс
  1918. */
  1919. function createInterface() {
  1920. scriptMenu.init({
  1921. showMenu: true
  1922. });
  1923. scriptMenu.addHeader(GM_info.script.name, justInfo);
  1924. scriptMenu.addHeader('v' + GM_info.script.version);
  1925. }
  1926.  
  1927. function addControls() {
  1928. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  1929. for (let name in checkboxes) {
  1930. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  1931. /**
  1932. * Getting the state of checkboxes from storage
  1933. * Получаем состояние чекбоксов из storage
  1934. */
  1935. let val = storage.get(name, null);
  1936. if (val != null) {
  1937. checkboxes[name].cbox.checked = val;
  1938. } else {
  1939. storage.set(name, checkboxes[name].default);
  1940. checkboxes[name].cbox.checked = checkboxes[name].default;
  1941. }
  1942. /**
  1943. * Tracing the change event of the checkbox for writing to storage
  1944. * Отсеживание события изменения чекбокса для записи в storage
  1945. */
  1946. checkboxes[name].cbox.dataset['name'] = name;
  1947. checkboxes[name].cbox.addEventListener('change', async function (event) {
  1948. const nameCheckbox = this.dataset['name'];
  1949. if (this.checked && nameCheckbox == 'cancelBattleBan') {
  1950. this.checked = false;
  1951. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  1952. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  1953. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  1954. ])) {
  1955. return;
  1956. }
  1957. this.checked = true;
  1958. }
  1959. storage.set(nameCheckbox, this.checked);
  1960. })
  1961. }
  1962.  
  1963. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  1964. for (let name in inputs) {
  1965. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  1966. /**
  1967. * Get inputText state from storage
  1968. * Получаем состояние inputText из storage
  1969. */
  1970. let val = storage.get(name, null);
  1971. if (val != null) {
  1972. inputs[name].input.value = val;
  1973. } else {
  1974. storage.set(name, inputs[name].default);
  1975. inputs[name].input.value = inputs[name].default;
  1976. }
  1977. /**
  1978. * Tracing a field change event for a record in storage
  1979. * Отсеживание события изменения поля для записи в storage
  1980. */
  1981. inputs[name].input.dataset['name'] = name;
  1982. inputs[name].input.addEventListener('input', function () {
  1983. const inputName = this.dataset['name'];
  1984. let value = +this.value;
  1985. if (!value || Number.isNaN(value)) {
  1986. value = storage.get(inputName, inputs[inputName].default);
  1987. inputs[name].input.value = value;
  1988. }
  1989. storage.set(inputName, value);
  1990. })
  1991. }
  1992. }
  1993. /**
  1994. * Calculates HASH MD5 from string
  1995. *
  1996. * Расчитывает HASH MD5 из строки
  1997. */
  1998. function md5(r){for(var a=(r,n,t,e,o,u)=>f(c(f(f(n,r),f(e,u)),o),t),n=(r,n,t,e,o,u,f)=>a(n&t|~n&e,r,n,o,u,f),t=(r,n,t,e,o,u,f)=>a(n&e|t&~e,r,n,o,u,f),e=(r,n,t,e,o,u,f)=>a(n^t^e,r,n,o,u,f),o=(r,n,t,e,o,u,f)=>a(t^(n|~e),r,n,o,u,f),f=function(r,n){var t=(65535&r)+(65535&n);return(r>>16)+(n>>16)+(t>>16)<<16|65535&t},c=(r,n)=>r<<n|r>>>32-n,u=Array(r.length>>2),h=0;h<u.length;h++)u[h]=0;for(h=0;h<8*r.length;h+=8)u[h>>5]|=(255&r.charCodeAt(h/8))<<h%32;len=8*r.length,u[len>>5]|=128<<len%32,u[14+(len+64>>>9<<4)]=len;var l=1732584193,i=-271733879,g=-1732584194,v=271733878;for(h=0;h<u.length;h+=16){var A=l,d=i,C=g,m=v;i=o(i=o(i=o(i=o(i=e(i=e(i=e(i=e(i=t(i=t(i=t(i=t(i=n(i=n(i=n(i=n(i,g=n(g,v=n(v,l=n(l,i,g,v,u[h+0],7,-680876936),i,g,u[h+1],12,-389564586),l,i,u[h+2],17,606105819),v,l,u[h+3],22,-1044525330),g=n(g,v=n(v,l=n(l,i,g,v,u[h+4],7,-176418897),i,g,u[h+5],12,1200080426),l,i,u[h+6],17,-1473231341),v,l,u[h+7],22,-45705983),g=n(g,v=n(v,l=n(l,i,g,v,u[h+8],7,1770035416),i,g,u[h+9],12,-1958414417),l,i,u[h+10],17,-42063),v,l,u[h+11],22,-1990404162),g=n(g,v=n(v,l=n(l,i,g,v,u[h+12],7,1804603682),i,g,u[h+13],12,-40341101),l,i,u[h+14],17,-1502002290),v,l,u[h+15],22,1236535329),g=t(g,v=t(v,l=t(l,i,g,v,u[h+1],5,-165796510),i,g,u[h+6],9,-1069501632),l,i,u[h+11],14,643717713),v,l,u[h+0],20,-373897302),g=t(g,v=t(v,l=t(l,i,g,v,u[h+5],5,-701558691),i,g,u[h+10],9,38016083),l,i,u[h+15],14,-660478335),v,l,u[h+4],20,-405537848),g=t(g,v=t(v,l=t(l,i,g,v,u[h+9],5,568446438),i,g,u[h+14],9,-1019803690),l,i,u[h+3],14,-187363961),v,l,u[h+8],20,1163531501),g=t(g,v=t(v,l=t(l,i,g,v,u[h+13],5,-1444681467),i,g,u[h+2],9,-51403784),l,i,u[h+7],14,1735328473),v,l,u[h+12],20,-1926607734),g=e(g,v=e(v,l=e(l,i,g,v,u[h+5],4,-378558),i,g,u[h+8],11,-2022574463),l,i,u[h+11],16,1839030562),v,l,u[h+14],23,-35309556),g=e(g,v=e(v,l=e(l,i,g,v,u[h+1],4,-1530992060),i,g,u[h+4],11,1272893353),l,i,u[h+7],16,-155497632),v,l,u[h+10],23,-1094730640),g=e(g,v=e(v,l=e(l,i,g,v,u[h+13],4,681279174),i,g,u[h+0],11,-358537222),l,i,u[h+3],16,-722521979),v,l,u[h+6],23,76029189),g=e(g,v=e(v,l=e(l,i,g,v,u[h+9],4,-640364487),i,g,u[h+12],11,-421815835),l,i,u[h+15],16,530742520),v,l,u[h+2],23,-995338651),g=o(g,v=o(v,l=o(l,i,g,v,u[h+0],6,-198630844),i,g,u[h+7],10,1126891415),l,i,u[h+14],15,-1416354905),v,l,u[h+5],21,-57434055),g=o(g,v=o(v,l=o(l,i,g,v,u[h+12],6,1700485571),i,g,u[h+3],10,-1894986606),l,i,u[h+10],15,-1051523),v,l,u[h+1],21,-2054922799),g=o(g,v=o(v,l=o(l,i,g,v,u[h+8],6,1873313359),i,g,u[h+15],10,-30611744),l,i,u[h+6],15,-1560198380),v,l,u[h+13],21,1309151649),g=o(g,v=o(v,l=o(l,i,g,v,u[h+4],6,-145523070),i,g,u[h+11],10,-1120210379),l,i,u[h+2],15,718787259),v,l,u[h+9],21,-343485551),l=f(l,A),i=f(i,d),g=f(g,C),v=f(v,m)}var y=Array(l,i,g,v),b="";for(h=0;h<32*y.length;h+=8)b+=String.fromCharCode(y[h>>5]>>>h%32&255);var S="0123456789abcdef",j="";for(h=0;h<b.length;h++)u=b.charCodeAt(h),j+=S.charAt(u>>>4&15)+S.charAt(15&u);return j}
  1999. /**
  2000. * Script for beautiful dialog boxes
  2001. *
  2002. * Скрипт для красивых диалоговых окошек
  2003. */
  2004. const popup = new (function () {
  2005. this.popUp,
  2006. this.downer,
  2007. this.middle,
  2008. this.msgText,
  2009. this.buttons = [];
  2010. this.checkboxes = [];
  2011.  
  2012. function init() {
  2013. addStyle();
  2014. addBlocks();
  2015. }
  2016.  
  2017. const addStyle = () => {
  2018. let style = document.createElement('style');
  2019. style.innerText = `
  2020. .PopUp_ {
  2021. position: absolute;
  2022. min-width: 300px;
  2023. max-width: 500px;
  2024. max-height: 400px;
  2025. background-color: #190e08e6;
  2026. z-index: 10001;
  2027. top: 169px;
  2028. left: 345px;
  2029. border: 3px #ce9767 solid;
  2030. border-radius: 10px;
  2031. display: flex;
  2032. flex-direction: column;
  2033. justify-content: space-around;
  2034. padding: 15px 12px;
  2035. }
  2036.  
  2037. .PopUp_back {
  2038. position: absolute;
  2039. background-color: #00000066;
  2040. width: 100%;
  2041. height: 100%;
  2042. z-index: 10000;
  2043. top: 0;
  2044. left: 0;
  2045. }
  2046.  
  2047. .PopUp_blocks {
  2048. width: 100%;
  2049. height: 50%;
  2050. display: flex;
  2051. justify-content: space-evenly;
  2052. align-items: center;
  2053. flex-wrap: wrap;
  2054. justify-content: center;
  2055. }
  2056.  
  2057. .PopUp_blocks:last-child {
  2058. margin-top: 25px;
  2059. }
  2060.  
  2061. .PopUp_buttons {
  2062. display: flex;
  2063. margin: 10px 12px;
  2064. flex-direction: column;
  2065. }
  2066.  
  2067. .PopUp_button {
  2068. background-color: #52A81C;
  2069. border-radius: 5px;
  2070. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  2071. cursor: pointer;
  2072. padding: 5px 18px 8px;
  2073. }
  2074.  
  2075. .PopUp_input {
  2076. text-align: center;
  2077. font-size: 16px;
  2078. height: 27px;
  2079. border: 1px solid #cf9250;
  2080. border-radius: 9px 9px 0px 0px;
  2081. background: transparent;
  2082. color: #fce1ac;
  2083. padding: 1px 10px;
  2084. box-sizing: border-box;
  2085. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  2086. }
  2087.  
  2088. .PopUp_checkboxes {
  2089. display: flex;
  2090. flex-direction: column;
  2091. margin: 15px 15px -5px 15px;
  2092. align-items: flex-start;
  2093. }
  2094.  
  2095. .PopUp_ContCheckbox {
  2096. margin: 2px 0px;
  2097. }
  2098.  
  2099. .PopUp_checkbox {
  2100. position: absolute;
  2101. z-index: -1;
  2102. opacity: 0;
  2103. }
  2104. .PopUp_checkbox+label {
  2105. display: inline-flex;
  2106. align-items: center;
  2107. user-select: none;
  2108.  
  2109. font-size: 15px;
  2110. font-family: sans-serif;
  2111. font-weight: 600;
  2112. font-stretch: condensed;
  2113. letter-spacing: 1px;
  2114. color: #fce1ac;
  2115. text-shadow: 0px 0px 1px;
  2116. }
  2117. .PopUp_checkbox+label::before {
  2118. content: '';
  2119. display: inline-block;
  2120. width: 20px;
  2121. height: 20px;
  2122. border: 1px solid #cf9250;
  2123. border-radius: 7px;
  2124. margin-right: 7px;
  2125. }
  2126. .PopUp_checkbox:checked+label::before {
  2127. 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");
  2128. }
  2129.  
  2130. .PopUp_input::placeholder {
  2131. color: #fce1ac75;
  2132. }
  2133.  
  2134. .PopUp_input:focus {
  2135. outline: 0;
  2136. }
  2137.  
  2138. .PopUp_input + .PopUp_button {
  2139. border-radius: 0px 0px 5px 5px;
  2140. padding: 2px 18px 5px;
  2141. }
  2142.  
  2143. .PopUp_button:hover {
  2144. filter: brightness(1.2);
  2145. }
  2146.  
  2147. .PopUp_text {
  2148. font-size: 22px;
  2149. font-family: sans-serif;
  2150. font-weight: 600;
  2151. font-stretch: condensed;
  2152. letter-spacing: 1px;
  2153. text-align: center;
  2154. }
  2155.  
  2156. .PopUp_buttonText {
  2157. color: #E4FF4C;
  2158. text-shadow: 0px 1px 2px black;
  2159. }
  2160.  
  2161. .PopUp_msgText {
  2162. color: #FDE5B6;
  2163. text-shadow: 0px 0px 2px;
  2164. }
  2165.  
  2166. .PopUp_hideBlock {
  2167. display: none;
  2168. }
  2169. `;
  2170. document.head.appendChild(style);
  2171. }
  2172.  
  2173. const addBlocks = () => {
  2174. this.back = document.createElement('div');
  2175. this.back.classList.add('PopUp_back');
  2176. this.back.classList.add('PopUp_hideBlock');
  2177. document.body.append(this.back);
  2178.  
  2179. this.popUp = document.createElement('div');
  2180. this.popUp.classList.add('PopUp_');
  2181. this.back.append(this.popUp);
  2182.  
  2183. let upper = document.createElement('div')
  2184. upper.classList.add('PopUp_blocks');
  2185. this.popUp.append(upper);
  2186.  
  2187. this.middle = document.createElement('div')
  2188. this.middle.classList.add('PopUp_blocks');
  2189. this.middle.classList.add('PopUp_checkboxes');
  2190. this.popUp.append(this.middle);
  2191.  
  2192. this.downer = document.createElement('div')
  2193. this.downer.classList.add('PopUp_blocks');
  2194. this.popUp.append(this.downer);
  2195.  
  2196. this.msgText = document.createElement('div');
  2197. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  2198. upper.append(this.msgText);
  2199. }
  2200.  
  2201. this.showBack = function () {
  2202. this.back.classList.remove('PopUp_hideBlock');
  2203. }
  2204.  
  2205. this.hideBack = function () {
  2206. this.back.classList.add('PopUp_hideBlock');
  2207. }
  2208.  
  2209. this.show = function () {
  2210. if (this.checkboxes.length) {
  2211. this.middle.classList.remove('PopUp_hideBlock');
  2212. }
  2213. this.showBack();
  2214. this.popUp.classList.remove('PopUp_hideBlock');
  2215. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  2216. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  2217. }
  2218.  
  2219. this.hide = function () {
  2220. this.hideBack();
  2221. this.popUp.classList.add('PopUp_hideBlock');
  2222. }
  2223.  
  2224. this.addButton = (option, buttonClick) => {
  2225. const contButton = document.createElement('div');
  2226. contButton.classList.add('PopUp_buttons');
  2227. this.downer.append(contButton);
  2228.  
  2229. let inputField = {
  2230. value: option.result || option.default
  2231. }
  2232. if (option.isInput) {
  2233. inputField = document.createElement('input');
  2234. inputField.type = 'text';
  2235. if (option.placeholder) {
  2236. inputField.placeholder = option.placeholder;
  2237. }
  2238. if (option.default) {
  2239. inputField.value = option.default;
  2240. }
  2241. inputField.classList.add('PopUp_input');
  2242. contButton.append(inputField);
  2243. }
  2244.  
  2245. const button = document.createElement('div');
  2246. button.classList.add('PopUp_button');
  2247. contButton.append(button);
  2248.  
  2249. button.addEventListener('click', () => {
  2250. let result = '';
  2251. if (option.isInput) {
  2252. result = inputField.value;
  2253. }
  2254. buttonClick(result);
  2255. });
  2256.  
  2257. const buttonText = document.createElement('div');
  2258. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  2259. buttonText.innerText = option.msg;
  2260. button.append(buttonText);
  2261.  
  2262. this.buttons.push(contButton);
  2263. }
  2264.  
  2265. this.clearButtons = () => {
  2266. while (this.buttons.length) {
  2267. this.buttons.pop().remove();
  2268. }
  2269. }
  2270.  
  2271. this.addCheckBox = (checkBox) => {
  2272. const contCheckbox = document.createElement('div');
  2273. contCheckbox.classList.add('PopUp_ContCheckbox');
  2274. this.middle.append(contCheckbox);
  2275.  
  2276. const checkbox = document.createElement('input');
  2277. checkbox.type = 'checkbox';
  2278. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  2279. checkbox.dataset.name = checkBox.name;
  2280. checkbox.checked = checkBox.checked;
  2281. checkbox.label = checkBox.label;
  2282. checkbox.classList.add('PopUp_checkbox');
  2283. contCheckbox.appendChild(checkbox)
  2284.  
  2285. const checkboxLabel = document.createElement('label');
  2286. checkboxLabel.innerText = checkBox.label;
  2287. checkboxLabel.setAttribute('for', checkbox.id);
  2288. contCheckbox.appendChild(checkboxLabel);
  2289.  
  2290. this.checkboxes.push(checkbox);
  2291. }
  2292.  
  2293. this.clearCheckBox = () => {
  2294. this.middle.classList.add('PopUp_hideBlock');
  2295. while (this.checkboxes.length) {
  2296. this.checkboxes.pop().parentNode.remove();
  2297. }
  2298. }
  2299.  
  2300. this.setMsgText = (text) => {
  2301. this.msgText.innerHTML = text;
  2302. }
  2303.  
  2304. this.getCheckBoxes = () => {
  2305. const checkBoxes = [];
  2306.  
  2307. for (const checkBox of this.checkboxes) {
  2308. checkBoxes.push({
  2309. name: checkBox.dataset.name,
  2310. label: checkBox.label,
  2311. checked: checkBox.checked
  2312. });
  2313. }
  2314.  
  2315. return checkBoxes;
  2316. }
  2317.  
  2318. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  2319. this.clearButtons();
  2320. this.clearCheckBox();
  2321. return new Promise((complete, failed) => {
  2322. this.setMsgText(msg);
  2323. if (!buttOpt) {
  2324. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  2325. }
  2326. for (const checkBox of checkBoxes) {
  2327. this.addCheckBox(checkBox);
  2328. }
  2329. for (let butt of buttOpt) {
  2330. this.addButton(butt, (result) => {
  2331. result = result || butt.result;
  2332. complete(result);
  2333. popup.hide();
  2334. });
  2335. }
  2336. this.show();
  2337. });
  2338. }
  2339.  
  2340. document.addEventListener('DOMContentLoaded', init);
  2341. });
  2342. /**
  2343. * Script control panel
  2344. *
  2345. * Панель управления скриптом
  2346. */
  2347. const scriptMenu = new (function () {
  2348.  
  2349. this.mainMenu,
  2350. this.buttons = [],
  2351. this.checkboxes = [];
  2352. this.option = {
  2353. showMenu: false,
  2354. showDetails: {}
  2355. };
  2356.  
  2357. this.init = function (option = {}) {
  2358. this.option = Object.assign(this.option, option);
  2359. this.option.showDetails = this.loadShowDetails();
  2360. addStyle();
  2361. addBlocks();
  2362. }
  2363.  
  2364. const addStyle = () => {
  2365. style = document.createElement('style');
  2366. style.innerText = `
  2367. .scriptMenu_status {
  2368. position: absolute;
  2369. z-index: 10001;
  2370. /* max-height: 30px; */
  2371. top: -1px;
  2372. left: 30%;
  2373. cursor: pointer;
  2374. border-radius: 0px 0px 10px 10px;
  2375. background: #190e08e6;
  2376. border: 1px #ce9767 solid;
  2377. font-size: 18px;
  2378. font-family: sans-serif;
  2379. font-weight: 600;
  2380. font-stretch: condensed;
  2381. letter-spacing: 1px;
  2382. color: #fce1ac;
  2383. text-shadow: 0px 0px 1px;
  2384. transition: 0.5s;
  2385. padding: 2px 10px 3px;
  2386. }
  2387. .scriptMenu_statusHide {
  2388. top: -35px;
  2389. height: 30px;
  2390. overflow: hidden;
  2391. }
  2392. .scriptMenu_label {
  2393. position: absolute;
  2394. top: 30%;
  2395. left: -4px;
  2396. z-index: 9999;
  2397. cursor: pointer;
  2398. width: 30px;
  2399. height: 30px;
  2400. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  2401. border: 1px solid #1a2f04;
  2402. border-radius: 5px;
  2403. box-shadow:
  2404. inset 0px 2px 4px #83ce26,
  2405. inset 0px -4px 6px #1a2f04,
  2406. 0px 0px 2px black,
  2407. 0px 0px 0px 2px #ce9767;
  2408. }
  2409. .scriptMenu_label:hover {
  2410. filter: brightness(1.2);
  2411. }
  2412. .scriptMenu_arrowLabel {
  2413. width: 100%;
  2414. height: 100%;
  2415. background-size: 75%;
  2416. background-position: center;
  2417. background-repeat: no-repeat;
  2418. 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");
  2419. box-shadow: 0px 1px 2px #000;
  2420. border-radius: 5px;
  2421. filter: drop-shadow(0px 1px 2px #000D);
  2422. }
  2423. .scriptMenu_main {
  2424. position: absolute;
  2425. max-width: 285px;
  2426. z-index: 9999;
  2427. top: 50%;
  2428. transform: translateY(-50%);
  2429. background: #190e08e6;
  2430. border: 1px #ce9767 solid;
  2431. border-radius: 0px 10px 10px 0px;
  2432. border-left: none;
  2433. padding: 5px 10px 5px 5px;
  2434. box-sizing: border-box;
  2435. font-size: 15px;
  2436. font-family: sans-serif;
  2437. font-weight: 600;
  2438. font-stretch: condensed;
  2439. letter-spacing: 1px;
  2440. color: #fce1ac;
  2441. text-shadow: 0px 0px 1px;
  2442. transition: 1s;
  2443. display: flex;
  2444. flex-direction: column;
  2445. flex-wrap: nowrap;
  2446. }
  2447. .scriptMenu_showMenu {
  2448. display: none;
  2449. }
  2450. .scriptMenu_showMenu:checked~.scriptMenu_main {
  2451. left: 0px;
  2452. }
  2453. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  2454. left: -300px;
  2455. }
  2456. .scriptMenu_divInput {
  2457. margin: 2px;
  2458. }
  2459. .scriptMenu_divInputText {
  2460. margin: 2px;
  2461. align-self: center;
  2462. display: flex;
  2463. }
  2464. .scriptMenu_checkbox {
  2465. position: absolute;
  2466. z-index: -1;
  2467. opacity: 0;
  2468. }
  2469. .scriptMenu_checkbox+label {
  2470. display: inline-flex;
  2471. align-items: center;
  2472. user-select: none;
  2473. }
  2474. .scriptMenu_checkbox+label::before {
  2475. content: '';
  2476. display: inline-block;
  2477. width: 20px;
  2478. height: 20px;
  2479. border: 1px solid #cf9250;
  2480. border-radius: 7px;
  2481. margin-right: 7px;
  2482. }
  2483. .scriptMenu_checkbox:checked+label::before {
  2484. 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");
  2485. }
  2486. .scriptMenu_close {
  2487. width: 40px;
  2488. height: 40px;
  2489. position: absolute;
  2490. right: -18px;
  2491. top: -18px;
  2492. border: 3px solid #c18550;
  2493. border-radius: 20px;
  2494. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  2495. background-position-y: 3px;
  2496. box-shadow: -1px 1px 3px black;
  2497. cursor: pointer;
  2498. box-sizing: border-box;
  2499. }
  2500. .scriptMenu_close:hover {
  2501. filter: brightness(1.2);
  2502. }
  2503. .scriptMenu_crossClose {
  2504. width: 100%;
  2505. height: 100%;
  2506. background-size: 65%;
  2507. background-position: center;
  2508. background-repeat: no-repeat;
  2509. 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")
  2510. }
  2511. .scriptMenu_button {
  2512. user-select: none;
  2513. border-radius: 5px;
  2514. cursor: pointer;
  2515. padding: 5px 14px 8px;
  2516. margin: 4px;
  2517. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  2518. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  2519. }
  2520. .scriptMenu_button:hover {
  2521. filter: brightness(1.2);
  2522. }
  2523. .scriptMenu_buttonText {
  2524. color: #fce5b7;
  2525. text-shadow: 0px 1px 2px black;
  2526. text-align: center;
  2527. }
  2528. .scriptMenu_header {
  2529. text-align: center;
  2530. align-self: center;
  2531. font-size: 15px;
  2532. margin: 0px 15px;
  2533. }
  2534. .scriptMenu_header a {
  2535. color: #fce5b7;
  2536. text-decoration: none;
  2537. }
  2538. .scriptMenu_InputText {
  2539. text-align: center;
  2540. width: 130px;
  2541. height: 24px;
  2542. border: 1px solid #cf9250;
  2543. border-radius: 9px;
  2544. background: transparent;
  2545. color: #fce1ac;
  2546. padding: 0px 10px;
  2547. box-sizing: border-box;
  2548. }
  2549. .scriptMenu_InputText:focus {
  2550. filter: brightness(1.2);
  2551. outline: 0;
  2552. }
  2553. .scriptMenu_InputText::placeholder {
  2554. color: #fce1ac75;
  2555. }
  2556. .scriptMenu_Summary {
  2557. cursor: pointer;
  2558. margin-left: 7px;
  2559. }
  2560. .scriptMenu_Details {
  2561. align-self: center;
  2562. }
  2563. `;
  2564. document.head.appendChild(style);
  2565. }
  2566.  
  2567. const addBlocks = () => {
  2568. const main = document.createElement('div');
  2569. document.body.appendChild(main);
  2570.  
  2571. this.status = document.createElement('div');
  2572. this.status.classList.add('scriptMenu_status');
  2573. this.setStatus('');
  2574. main.appendChild(this.status);
  2575.  
  2576. const label = document.createElement('label');
  2577. label.classList.add('scriptMenu_label');
  2578. label.setAttribute('for', 'checkbox_showMenu');
  2579. main.appendChild(label);
  2580.  
  2581. const arrowLabel = document.createElement('div');
  2582. arrowLabel.classList.add('scriptMenu_arrowLabel');
  2583. label.appendChild(arrowLabel);
  2584.  
  2585. const checkbox = document.createElement('input');
  2586. checkbox.type = 'checkbox';
  2587. checkbox.id = 'checkbox_showMenu';
  2588. checkbox.checked = this.option.showMenu;
  2589. checkbox.classList.add('scriptMenu_showMenu');
  2590. main.appendChild(checkbox);
  2591.  
  2592. this.mainMenu = document.createElement('div');
  2593. this.mainMenu.classList.add('scriptMenu_main');
  2594. main.appendChild(this.mainMenu);
  2595.  
  2596. const closeButton = document.createElement('label');
  2597. closeButton.classList.add('scriptMenu_close');
  2598. closeButton.setAttribute('for', 'checkbox_showMenu');
  2599. this.mainMenu.appendChild(closeButton);
  2600.  
  2601. const crossClose = document.createElement('div');
  2602. crossClose.classList.add('scriptMenu_crossClose');
  2603. closeButton.appendChild(crossClose);
  2604. }
  2605.  
  2606. this.setStatus = (text, onclick) => {
  2607. if (!text) {
  2608. this.status.classList.add('scriptMenu_statusHide');
  2609. } else {
  2610. this.status.classList.remove('scriptMenu_statusHide');
  2611. this.status.innerHTML = text;
  2612. }
  2613.  
  2614. if (typeof onclick == 'function') {
  2615. this.status.addEventListener("click", onclick, {
  2616. once: true
  2617. });
  2618. }
  2619. }
  2620.  
  2621. /**
  2622. * Adding a text element
  2623. *
  2624. * Добавление текстового элемента
  2625. * @param {String} text text // текст
  2626. * @param {Function} func Click function // функция по клику
  2627. * @param {HTMLDivElement} main parent // родитель
  2628. */
  2629. this.addHeader = (text, func, main) => {
  2630. main = main || this.mainMenu;
  2631. const header = document.createElement('div');
  2632. header.classList.add('scriptMenu_header');
  2633. header.innerHTML = text;
  2634. if (typeof func == 'function') {
  2635. header.addEventListener('click', func);
  2636. }
  2637. main.appendChild(header);
  2638. }
  2639.  
  2640. /**
  2641. * Adding a button
  2642. *
  2643. * Добавление кнопки
  2644. * @param {String} text
  2645. * @param {Function} func
  2646. * @param {String} title
  2647. * @param {HTMLDivElement} main parent // родитель
  2648. */
  2649. this.addButton = (text, func, title, main) => {
  2650. main = main || this.mainMenu;
  2651. const button = document.createElement('div');
  2652. button.classList.add('scriptMenu_button');
  2653. button.title = title;
  2654. button.addEventListener('click', func);
  2655. main.appendChild(button);
  2656.  
  2657. const buttonText = document.createElement('div');
  2658. buttonText.classList.add('scriptMenu_buttonText');
  2659. buttonText.innerText = text;
  2660. button.appendChild(buttonText);
  2661. this.buttons.push(button);
  2662.  
  2663. return button;
  2664. }
  2665.  
  2666. /**
  2667. * Adding checkbox
  2668. *
  2669. * Добавление чекбокса
  2670. * @param {String} label
  2671. * @param {String} title
  2672. * @param {HTMLDivElement} main parent // родитель
  2673. * @returns
  2674. */
  2675. this.addCheckbox = (label, title, main) => {
  2676. main = main || this.mainMenu;
  2677. const divCheckbox = document.createElement('div');
  2678. divCheckbox.classList.add('scriptMenu_divInput');
  2679. divCheckbox.title = title;
  2680. main.appendChild(divCheckbox);
  2681.  
  2682. const checkbox = document.createElement('input');
  2683. checkbox.type = 'checkbox';
  2684. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  2685. checkbox.classList.add('scriptMenu_checkbox');
  2686. divCheckbox.appendChild(checkbox)
  2687.  
  2688. const checkboxLabel = document.createElement('label');
  2689. checkboxLabel.innerText = label;
  2690. checkboxLabel.setAttribute('for', checkbox.id);
  2691. divCheckbox.appendChild(checkboxLabel);
  2692.  
  2693. this.checkboxes.push(checkbox);
  2694. return checkbox;
  2695. }
  2696.  
  2697. /**
  2698. * Adding input field
  2699. *
  2700. * Добавление поля ввода
  2701. * @param {String} title
  2702. * @param {String} placeholder
  2703. * @param {HTMLDivElement} main parent // родитель
  2704. * @returns
  2705. */
  2706. this.addInputText = (title, placeholder, main) => {
  2707. main = main || this.mainMenu;
  2708. const divInputText = document.createElement('div');
  2709. divInputText.classList.add('scriptMenu_divInputText');
  2710. divInputText.title = title;
  2711. main.appendChild(divInputText);
  2712.  
  2713. const newInputText = document.createElement('input');
  2714. newInputText.type = 'text';
  2715. if (placeholder) {
  2716. newInputText.placeholder = placeholder;
  2717. }
  2718. newInputText.classList.add('scriptMenu_InputText');
  2719. divInputText.appendChild(newInputText)
  2720. return newInputText;
  2721. }
  2722.  
  2723. /**
  2724. * Adds a dropdown block
  2725. *
  2726. * Добавляет раскрывающийся блок
  2727. * @param {String} summary
  2728. * @param {String} name
  2729. * @returns
  2730. */
  2731. this.addDetails = (summaryText, name = null) => {
  2732. const details = document.createElement('details');
  2733. details.classList.add('scriptMenu_Details');
  2734. this.mainMenu.appendChild(details);
  2735.  
  2736. const summary = document.createElement('summary');
  2737. summary.classList.add('scriptMenu_Summary');
  2738. summary.innerText = summaryText;
  2739. if (name) {
  2740. const self = this;
  2741. details.open = this.option.showDetails[name];
  2742. details.dataset.name = name;
  2743. summary.addEventListener('click', () => {
  2744. self.option.showDetails[details.dataset.name] = !details.open;
  2745. self.saveShowDetails(self.option.showDetails);
  2746. });
  2747. }
  2748. details.appendChild(summary);
  2749.  
  2750. return details;
  2751. }
  2752.  
  2753. /**
  2754. * Saving the expanded state of the details blocks
  2755. *
  2756. * Сохранение состояния развенутости блоков details
  2757. * @param {*} value
  2758. */
  2759. this.saveShowDetails = (value) => {
  2760. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  2761. }
  2762.  
  2763. /**
  2764. * Loading the state of expanded blocks details
  2765. *
  2766. * Загрузка состояния развенутости блоков details
  2767. * @returns
  2768. */
  2769. this.loadShowDetails = () => {
  2770. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  2771.  
  2772. if (!showDetails) {
  2773. return {};
  2774. }
  2775.  
  2776. try {
  2777. showDetails = JSON.parse(showDetails);
  2778. } catch (e) {
  2779. return {};
  2780. }
  2781.  
  2782. return showDetails;
  2783. }
  2784. });
  2785. /**
  2786. * Database
  2787. *
  2788. * База данных
  2789. */
  2790. class Database {
  2791. constructor(dbName, storeName) {
  2792. this.dbName = dbName;
  2793. this.storeName = storeName;
  2794. this.db = null;
  2795. }
  2796.  
  2797. async open() {
  2798. return new Promise((resolve, reject) => {
  2799. const request = indexedDB.open(this.dbName);
  2800.  
  2801. request.onerror = () => {
  2802. reject(new Error(`Failed to open database ${this.dbName}`));
  2803. };
  2804.  
  2805. request.onsuccess = () => {
  2806. this.db = request.result;
  2807. resolve();
  2808. };
  2809.  
  2810. request.onupgradeneeded = (event) => {
  2811. const db = event.target.result;
  2812. if (!db.objectStoreNames.contains(this.storeName)) {
  2813. db.createObjectStore(this.storeName);
  2814. }
  2815. };
  2816. });
  2817. }
  2818.  
  2819. async set(key, value) {
  2820. return new Promise((resolve, reject) => {
  2821. const transaction = this.db.transaction([this.storeName], 'readwrite');
  2822. const store = transaction.objectStore(this.storeName);
  2823. const request = store.put(value, key);
  2824.  
  2825. request.onerror = () => {
  2826. reject(new Error(`Failed to save value with key ${key}`));
  2827. };
  2828.  
  2829. request.onsuccess = () => {
  2830. resolve();
  2831. };
  2832. });
  2833. }
  2834.  
  2835. async get(key, def) {
  2836. return new Promise((resolve, reject) => {
  2837. const transaction = this.db.transaction([this.storeName], 'readonly');
  2838. const store = transaction.objectStore(this.storeName);
  2839. const request = store.get(key);
  2840.  
  2841. request.onerror = () => {
  2842. resolve(def);
  2843. };
  2844.  
  2845. request.onsuccess = () => {
  2846. resolve(request.result);
  2847. };
  2848. });
  2849. }
  2850.  
  2851. async delete(key) {
  2852. return new Promise((resolve, reject) => {
  2853. const transaction = this.db.transaction([this.storeName], 'readwrite');
  2854. const store = transaction.objectStore(this.storeName);
  2855. const request = store.delete(key);
  2856.  
  2857. request.onerror = () => {
  2858. reject(new Error(`Failed to delete value with key ${key}`));
  2859. };
  2860.  
  2861. request.onsuccess = () => {
  2862. resolve();
  2863. };
  2864. });
  2865. }
  2866. }
  2867. /**
  2868. * Returns the stored value
  2869. *
  2870. * Возвращает сохраненное значение
  2871. */
  2872. function getSaveVal(saveName, def) {
  2873. const result = storage.get(saveName, def);
  2874. return result;
  2875. }
  2876. /**
  2877. * Stores value
  2878. *
  2879. * Сохраняет значение
  2880. */
  2881. function setSaveVal(saveName, value) {
  2882. storage.set(saveName, value);
  2883. }
  2884. /**
  2885. * Database initialization
  2886. *
  2887. * Инициализация базы данных
  2888. */
  2889. const db = new Database(GM_info.script.name, 'settings');
  2890. /**
  2891. * Data store
  2892. *
  2893. * Хранилище данных
  2894. */
  2895. const storage = {
  2896. userId: 0,
  2897. /**
  2898. * Default values
  2899. *
  2900. * Значения по умолчанию
  2901. */
  2902. values: [
  2903. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  2904. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  2905. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  2906. name: GM_info.script.name,
  2907. get: function (key, def) {
  2908. if (key in this.values) {
  2909. return this.values[key];
  2910. }
  2911. return def;
  2912. },
  2913. set: function (key, value) {
  2914. this.values[key] = value;
  2915. db.set(this.userId, this.values).catch(
  2916. e => null
  2917. );
  2918. localStorage[this.name + ':' + key] = value;
  2919. },
  2920. delete: function (key) {
  2921. delete this.values[key];
  2922. db.set(this.userId, this.values);
  2923. delete localStorage[this.name + ':' + key];
  2924. }
  2925. }
  2926. /**
  2927. * Returns all keys from localStorage that start with prefix (for migration)
  2928. *
  2929. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  2930. */
  2931. function getAllValuesStartingWith(prefix) {
  2932. const values = [];
  2933. for (let i = 0; i < localStorage.length; i++) {
  2934. const key = localStorage.key(i);
  2935. if (key.startsWith(prefix)) {
  2936. const val = localStorage.getItem(key);
  2937. const keyValue = key.split(':')[1];
  2938. values.push({ key: keyValue, val });
  2939. }
  2940. }
  2941. return values;
  2942. }
  2943. /**
  2944. * Opens or migrates to a database
  2945. *
  2946. * Открывает или мигрирует в базу данных
  2947. */
  2948. async function openOrMigrateDatabase(userId) {
  2949. storage.userId = userId;
  2950. try {
  2951. await db.open();
  2952. } catch(e) {
  2953. return;
  2954. }
  2955. let settings = await db.get(userId, false);
  2956.  
  2957. if (settings) {
  2958. storage.values = settings;
  2959. return;
  2960. }
  2961.  
  2962. const values = getAllValuesStartingWith(GM_info.script.name);
  2963. for (const value of values) {
  2964. let val = null;
  2965. try {
  2966. val = JSON.parse(value.val);
  2967. } catch {
  2968. break;
  2969. }
  2970. storage.values[value.key] = val;
  2971. }
  2972. await db.set(userId, storage.values);
  2973. }
  2974. /**
  2975. * Sending expeditions
  2976. *
  2977. * Отправка экспедиций
  2978. */
  2979. function checkExpedition() {
  2980. return new Promise((resolve, reject) => {
  2981. const expedition = new Expedition(resolve, reject);
  2982. expedition.start();
  2983. });
  2984. }
  2985.  
  2986. class Expedition {
  2987. checkExpedInfo = {
  2988. calls: [{
  2989. name: "expeditionGet",
  2990. args: {},
  2991. ident: "expeditionGet"
  2992. }, {
  2993. name: "heroGetAll",
  2994. args: {},
  2995. ident: "heroGetAll"
  2996. }]
  2997. }
  2998.  
  2999. constructor(resolve, reject) {
  3000. this.resolve = resolve;
  3001. this.reject = reject;
  3002. }
  3003.  
  3004. async start() {
  3005. const data = await Send(JSON.stringify(this.checkExpedInfo));
  3006.  
  3007. const expedInfo = data.results[0].result.response;
  3008. const dataHeroes = data.results[1].result.response;
  3009. const dataExped = { useHeroes: [], exped: [] };
  3010. const calls = [];
  3011.  
  3012. /**
  3013. * Adding expeditions to collect
  3014. * Добавляем экспедиции для сбора
  3015. */
  3016. for (var n in expedInfo) {
  3017. const exped = expedInfo[n];
  3018. const dateNow = (Date.now() / 1000);
  3019. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  3020. calls.push({
  3021. name: "expeditionFarm",
  3022. args: { expeditionId: exped.id },
  3023. ident: "expeditionFarm_" + exped.id
  3024. });
  3025. } else {
  3026. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  3027. }
  3028. if (exped.status == 1) {
  3029. dataExped.exped.push({ id: exped.id, power: exped.power });
  3030. }
  3031. }
  3032. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  3033.  
  3034. /**
  3035. * Putting together a list of heroes
  3036. * Собираем список героев
  3037. */
  3038. const heroesArr = [];
  3039. for (let n in dataHeroes) {
  3040. const hero = dataHeroes[n];
  3041. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  3042. heroesArr.push({ id: hero.id, power: hero.power })
  3043. }
  3044. }
  3045.  
  3046. /**
  3047. * Adding expeditions to send
  3048. * Добавляем экспедиции для отправки
  3049. */
  3050. heroesArr.sort((a, b) => (a.power - b.power));
  3051. for (const exped of dataExped.exped) {
  3052. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  3053. if (heroesIds && heroesIds.length > 4) {
  3054. for (let q in heroesArr) {
  3055. if (heroesIds.includes(heroesArr[q].id)) {
  3056. delete heroesArr[q];
  3057. }
  3058. }
  3059. calls.push({
  3060. name: "expeditionSendHeroes",
  3061. args: {
  3062. expeditionId: exped.id,
  3063. heroes: heroesIds
  3064. },
  3065. ident: "expeditionSendHeroes_" + exped.id
  3066. });
  3067. }
  3068. }
  3069.  
  3070. await Send(JSON.stringify({ calls }));
  3071. this.end();
  3072. }
  3073.  
  3074. /**
  3075. * Selection of heroes for expeditions
  3076. *
  3077. * Подбор героев для экспедиций
  3078. */
  3079. selectionHeroes(heroes, power) {
  3080. const resultHeroers = [];
  3081. const heroesIds = [];
  3082. for (let q = 0; q < 5; q++) {
  3083. for (let i in heroes) {
  3084. let hero = heroes[i];
  3085. if (heroesIds.includes(hero.id)) {
  3086. continue;
  3087. }
  3088.  
  3089. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  3090. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  3091. if (hero.power > need) {
  3092. resultHeroers.push(hero);
  3093. heroesIds.push(hero.id);
  3094. break;
  3095. }
  3096. }
  3097. }
  3098.  
  3099. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  3100. if (summ < power) {
  3101. return false;
  3102. }
  3103. return heroesIds;
  3104. }
  3105.  
  3106. /**
  3107. * Ends expedition script
  3108. *
  3109. * Завершает скрипт экспедиции
  3110. */
  3111. end() {
  3112. setProgress(I18N('EXPEDITIONS_SENT'), true);
  3113. this.resolve()
  3114. }
  3115. }
  3116. /**
  3117. * Sending a request
  3118. *
  3119. * Отправка запроса
  3120. */
  3121. function send(json, callback, pr) {
  3122. /**
  3123. * We get the headlines of the previous intercepted request
  3124. * Получаем заголовки предыдущего перехваченого запроса
  3125. */
  3126. let headers = lastHeaders;
  3127. /**
  3128. * We increase the header of the query Certifier by 1
  3129. * Увеличиваем заголовок идетификатора запроса на 1
  3130. */
  3131. headers["X-Request-Id"]++;
  3132. /**
  3133. * We calculate the title with the signature
  3134. * Расчитываем заголовок с сигнатурой
  3135. */
  3136. headers["X-Auth-Signature"] = getSignature(headers, json);
  3137. /**
  3138. * Create a new ajax request
  3139. * Создаем новый AJAX запрос
  3140. */
  3141. let xhr = new XMLHttpRequest;
  3142. /**
  3143. * Indicate the previously saved URL for API queries
  3144. * Указываем ранее сохраненный URL для API запросов
  3145. */
  3146. xhr.open('POST', apiUrl, true);
  3147. /**
  3148. * Add the function to the event change event
  3149. * Добавляем функцию к событию смены статуса запроса
  3150. */
  3151. xhr.onreadystatechange = function() {
  3152. /**
  3153. * If the result of the request is obtained, we call the flask function
  3154. * Если результат запроса получен вызываем колбек функцию
  3155. */
  3156. if(xhr.readyState == 4) {
  3157. let randTimeout = Math.random() * 200 + 200;
  3158. setTimeout(callback, randTimeout, xhr.response, pr);
  3159. }
  3160. };
  3161. /**
  3162. * Indicate the type of request
  3163. * Указываем тип запроса
  3164. */
  3165. xhr.responseType = 'json';
  3166. /**
  3167. * We set the request headers
  3168. * Задаем заголовки запроса
  3169. */
  3170. for(let nameHeader in headers) {
  3171. let head = headers[nameHeader];
  3172. xhr.setRequestHeader(nameHeader, head);
  3173. }
  3174. /**
  3175. * Sending a request
  3176. * Отправляем запрос
  3177. */
  3178. xhr.send(json);
  3179. }
  3180.  
  3181. /**
  3182. * Walkthrough of the dungeon
  3183. *
  3184. * Прохождение подземелья
  3185. */
  3186. function testDungeon() {
  3187. return new Promise((resolve, reject) => {
  3188. const dung = new executeDungeon(resolve, reject);
  3189. const titanit = getInput('countTitanit');
  3190. dung.start(titanit);
  3191. });
  3192. }
  3193.  
  3194. /**
  3195. * Walkthrough of the dungeon
  3196. *
  3197. * Прохождение подземелья
  3198. */
  3199. function executeDungeon(resolve, reject) {
  3200. dungeonActivity = 0;
  3201. maxDungeonActivity = 150;
  3202.  
  3203. titanGetAll = [];
  3204.  
  3205. teams = {
  3206. heroes: [],
  3207. earth: [],
  3208. fire: [],
  3209. neutral: [],
  3210. water: [],
  3211. }
  3212.  
  3213. titanStats = [];
  3214.  
  3215. titansStates = {};
  3216.  
  3217. callsExecuteDungeon = {
  3218. calls: [{
  3219. name: "dungeonGetInfo",
  3220. args: {},
  3221. ident: "dungeonGetInfo"
  3222. }, {
  3223. name: "teamGetAll",
  3224. args: {},
  3225. ident: "teamGetAll"
  3226. }, {
  3227. name: "teamGetFavor",
  3228. args: {},
  3229. ident: "teamGetFavor"
  3230. }, {
  3231. name: "clanGetInfo",
  3232. args: {},
  3233. ident: "clanGetInfo"
  3234. }, {
  3235. name: "titanGetAll",
  3236. args: {},
  3237. ident: "titanGetAll"
  3238. }]
  3239. }
  3240.  
  3241. this.start = function(titanit) {
  3242. maxDungeonActivity = titanit || 75;
  3243. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  3244. }
  3245.  
  3246. /**
  3247. * Getting data on the dungeon
  3248. *
  3249. * Получаем данные по подземелью
  3250. */
  3251. function startDungeon(e) {
  3252. res = e.results;
  3253. dungeonGetInfo = res[0].result.response;
  3254. if (!dungeonGetInfo) {
  3255. endDungeon('noDungeon', res);
  3256. return;
  3257. }
  3258. teamGetAll = res[1].result.response;
  3259. teamGetFavor = res[2].result.response;
  3260. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  3261. titanGetAll = Object.values(res[4].result.response);
  3262.  
  3263. teams.hero = {
  3264. favor: teamGetFavor.dungeon_hero,
  3265. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  3266. teamNum: 0,
  3267. }
  3268. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  3269. if (heroPet) {
  3270. teams.hero.pet = heroPet;
  3271. }
  3272.  
  3273. teams.neutral = {
  3274. favor: {},
  3275. heroes: getTitanTeam(titanGetAll, 'neutral'),
  3276. teamNum: 0,
  3277. };
  3278. teams.water = {
  3279. favor: {},
  3280. heroes: getTitanTeam(titanGetAll, 'water'),
  3281. teamNum: 0,
  3282. };
  3283. teams.fire = {
  3284. favor: {},
  3285. heroes: getTitanTeam(titanGetAll, 'fire'),
  3286. teamNum: 0,
  3287. };
  3288. teams.earth = {
  3289. favor: {},
  3290. heroes: getTitanTeam(titanGetAll, 'earth'),
  3291. teamNum: 0,
  3292. };
  3293.  
  3294.  
  3295. checkFloor(dungeonGetInfo);
  3296. }
  3297.  
  3298. function getTitanTeam(titans, type) {
  3299. switch (type) {
  3300. case 'neutral':
  3301. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  3302. case 'water':
  3303. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  3304. case 'fire':
  3305. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  3306. case 'earth':
  3307. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  3308. }
  3309. }
  3310.  
  3311. function fixTitanTeam(titans) {
  3312. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  3313. return titans;
  3314. }
  3315.  
  3316. /**
  3317. * Checking the floor
  3318. *
  3319. * Проверяем этаж
  3320. */
  3321. function checkFloor(dungeonInfo) {
  3322. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  3323. saveProgress();
  3324. return;
  3325. }
  3326. // console.log(dungeonInfo, dungeonActivity);
  3327. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ` + dungeonActivity + '/' + maxDungeonActivity);
  3328. if (dungeonActivity >= maxDungeonActivity) {
  3329. endDungeon('endDungeon');
  3330. return;
  3331. }
  3332. titansStates = dungeonInfo.states.titans;
  3333. titanStats = titanObjToArray(titansStates);
  3334. floorChoices = dungeonInfo.floor.userData;
  3335. floorType = dungeonInfo.floorType;
  3336. primeElement = dungeonInfo.elements.prime;
  3337. if (floorType == "battle") {
  3338. promises = [];
  3339. for (let teamNum in floorChoices) {
  3340. attackerType = floorChoices[teamNum].attackerType;
  3341. promises.push(startBattle(teamNum, attackerType));
  3342. }
  3343. Promise.all(promises)
  3344. .then(processingPromises);
  3345. }
  3346. }
  3347.  
  3348. function processingPromises(results) {
  3349. selectInfo = results[0];
  3350. if (results.length < 2) {
  3351. // console.log(selectInfo);
  3352. endBattle(selectInfo);
  3353. return;
  3354. }
  3355.  
  3356. selectInfo = false;
  3357. minRes = 1e10;
  3358. for (let info of results) {
  3359. diffXP = diffTitanXP(info.progress[0].attackers.heroes);
  3360. diffRes = diffXP;
  3361. if (info.attackerType == 'neutral') {
  3362. diffRes /= 2;
  3363. diffRes -= 4;
  3364. }
  3365. if (info.attackerType == primeElement) {
  3366. diffRes /= 2;
  3367. diffRes -= 5;
  3368. }
  3369. info.diffXP = diffXP
  3370. info.diffRes = diffRes
  3371. if (!info.result.win) {
  3372. continue;
  3373. }
  3374. if (diffRes < minRes) {
  3375. selectInfo = info;
  3376. minRes = diffRes;
  3377. }
  3378. }
  3379. // console.log(selectInfo.teamNum, results);
  3380. if (!selectInfo) {
  3381. endDungeon('dungeonEndBattle\n', results);
  3382. return;
  3383. }
  3384.  
  3385. startBattle(selectInfo.teamNum, selectInfo.attackerType)
  3386. .then(endBattle);
  3387. }
  3388.  
  3389. /**
  3390. * Let's start the fight
  3391. *
  3392. * Начинаем бой
  3393. */
  3394. function startBattle(teamNum, attackerType) {
  3395. return new Promise(function (resolve, reject) {
  3396. args = fixTitanTeam(teams[attackerType]);
  3397. args.teamNum = teamNum;
  3398. startBattleCall = {
  3399. calls: [{
  3400. name: "dungeonStartBattle",
  3401. args,
  3402. ident: "body"
  3403. }]
  3404. }
  3405. send(JSON.stringify(startBattleCall), resultBattle, {
  3406. resolve,
  3407. teamNum,
  3408. attackerType
  3409. });
  3410. });
  3411. }
  3412. /**
  3413. * Returns the result of the battle in a promise
  3414. *
  3415. * Возращает резульат боя в промис
  3416. */
  3417. function resultBattle(resultBattles, args) {
  3418. battleData = resultBattles.results[0].result.response;
  3419. battleType = "get_tower";
  3420. if (battleData.type == "dungeon_titan") {
  3421. battleType = "get_titan";
  3422. }
  3423. BattleCalc(battleData, battleType, function (result) {
  3424. result.teamNum = args.teamNum;
  3425. result.attackerType = args.attackerType;
  3426. args.resolve(result);
  3427. });
  3428. }
  3429. /**
  3430. * Finishing the fight
  3431. *
  3432. * Заканчиваем бой
  3433. */
  3434. function endBattle(battleInfo) {
  3435. if (battleInfo.result.win) {
  3436. endBattleCall = {
  3437. calls: [{
  3438. name: "dungeonEndBattle",
  3439. args: {
  3440. result: battleInfo.result,
  3441. progress: battleInfo.progress,
  3442. },
  3443. ident: "body"
  3444. }]
  3445. }
  3446. send(JSON.stringify(endBattleCall), resultEndBattle);
  3447. } else {
  3448. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  3449. }
  3450. }
  3451.  
  3452. /**
  3453. * Getting and processing battle results
  3454. *
  3455. * Получаем и обрабатываем результаты боя
  3456. */
  3457. function resultEndBattle(e) {
  3458. battleResult = e.results[0].result.response;
  3459. if ('error' in battleResult) {
  3460. endDungeon('errorBattleResult', battleResult);
  3461. return;
  3462. }
  3463. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  3464. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  3465. checkFloor(dungeonGetInfo);
  3466. }
  3467.  
  3468. /**
  3469. * Returns the difference between the maximum HP of the titans and transferred
  3470. *
  3471. * Возвращает разницу между максимальными ХП титанов и переданными
  3472. */
  3473. function diffTitanXP(titans) {
  3474. sumCurrentXp = 0;
  3475. for (let i in titans) {
  3476. sumCurrentXp += titans[i].hp
  3477. }
  3478. titanIds = Object.getOwnPropertyNames(titans);
  3479. maxHP = titanStats.reduce((n, e) =>
  3480. titanIds.includes(e.id.toString()) ? n + e.hp : n
  3481. , 0);
  3482. return maxHP < sumCurrentXp ? 0 : maxHP - sumCurrentXp;
  3483. }
  3484.  
  3485. /**
  3486. * Converts an object with IDs to an array with IDs
  3487. *
  3488. * Преобразует объект с идетификаторами в массив с идетификаторами
  3489. */
  3490. function titanObjToArray(obj) {
  3491. let titans = [];
  3492. for (let id in obj) {
  3493. obj[id].id = id;
  3494. titans.push(obj[id]);
  3495. }
  3496. return titans;
  3497. }
  3498.  
  3499. function saveProgress() {
  3500. let saveProgressCall = {
  3501. calls: [{
  3502. name: "dungeonSaveProgress",
  3503. args: {},
  3504. ident: "body"
  3505. }]
  3506. }
  3507. send(JSON.stringify(saveProgressCall), resultEndBattle);
  3508. }
  3509.  
  3510. function endDungeon(reason, info) {
  3511. console.log(reason, info);
  3512. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  3513. resolve();
  3514. }
  3515. }
  3516.  
  3517. /**
  3518. * Passing the tower
  3519. *
  3520. * Прохождение башни
  3521. */
  3522. function testTower() {
  3523. return new Promise((resolve, reject) => {
  3524. tower = new executeTower(resolve, reject);
  3525. tower.start();
  3526. });
  3527. }
  3528.  
  3529. /**
  3530. * Passing the tower
  3531. *
  3532. * Прохождение башни
  3533. */
  3534. function executeTower(resolve, reject) {
  3535. lastTowerInfo = {};
  3536.  
  3537. scullCoin = 0;
  3538.  
  3539. heroGetAll = [];
  3540.  
  3541. heroesStates = {};
  3542.  
  3543. argsBattle = {
  3544. heroes: [],
  3545. favor: {},
  3546. };
  3547.  
  3548. callsExecuteTower = {
  3549. calls: [{
  3550. name: "towerGetInfo",
  3551. args: {},
  3552. ident: "towerGetInfo"
  3553. }, {
  3554. name: "teamGetAll",
  3555. args: {},
  3556. ident: "teamGetAll"
  3557. }, {
  3558. name: "teamGetFavor",
  3559. args: {},
  3560. ident: "teamGetFavor"
  3561. }, {
  3562. name: "inventoryGet",
  3563. args: {},
  3564. ident: "inventoryGet"
  3565. }, {
  3566. name: "heroGetAll",
  3567. args: {},
  3568. ident: "heroGetAll"
  3569. }]
  3570. }
  3571.  
  3572. buffIds = [
  3573. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  3574. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  3575. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  3576. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  3577. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  3578. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  3579. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  3580. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  3581. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  3582. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  3583. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  3584. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  3585. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  3586. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  3587. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  3588. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  3589. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  3590. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  3591. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  3592. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  3593. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  3594. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  3595. ]
  3596.  
  3597. this.start = function () {
  3598. send(JSON.stringify(callsExecuteTower), startTower);
  3599. }
  3600.  
  3601. /**
  3602. * Getting data on the Tower
  3603. *
  3604. * Получаем данные по башне
  3605. */
  3606. function startTower(e) {
  3607. res = e.results;
  3608. towerGetInfo = res[0].result.response;
  3609. if (!towerGetInfo) {
  3610. endTower('noTower', res);
  3611. return;
  3612. }
  3613. teamGetAll = res[1].result.response;
  3614. teamGetFavor = res[2].result.response;
  3615. inventoryGet = res[3].result.response;
  3616. heroGetAll = Object.values(res[4].result.response);
  3617.  
  3618. scullCoin = inventoryGet.coin[7] ?? 0;
  3619.  
  3620. argsBattle.favor = teamGetFavor.tower;
  3621. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);;
  3622. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  3623. if (pet) {
  3624. argsBattle.pet = pet;
  3625. }
  3626.  
  3627. checkFloor(towerGetInfo);
  3628. }
  3629.  
  3630. function fixHeroesTeam(argsBattle) {
  3631. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  3632. if (fixHeroes.length < 5) {
  3633. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  3634. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  3635. Object.keys(argsBattle.favor).forEach(e => {
  3636. if (!fixHeroes.includes(+e)) {
  3637. delete argsBattle.favor[e];
  3638. }
  3639. })
  3640. }
  3641. argsBattle.heroes = fixHeroes;
  3642. return argsBattle;
  3643. }
  3644.  
  3645. /**
  3646. * Check the floor
  3647. *
  3648. * Проверяем этаж
  3649. */
  3650. function checkFloor(towerInfo) {
  3651. lastTowerInfo = towerInfo;
  3652. maySkipFloor = +towerInfo.maySkipFloor;
  3653. floorNumber = +towerInfo.floorNumber;
  3654. heroesStates = towerInfo.states.heroes;
  3655. floorInfo = towerInfo.floor;
  3656.  
  3657. /**
  3658. * Is there at least one chest open on the floor
  3659. * Открыт ли на этаже хоть один сундук
  3660. */
  3661. isOpenChest = false;
  3662. if (towerInfo.floorType == "chest") {
  3663. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  3664. }
  3665.  
  3666. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  3667. if (floorNumber > 49) {
  3668. if (isOpenChest) {
  3669. endTower('alreadyOpenChest 50 floor', floorNumber);
  3670. return;
  3671. }
  3672. }
  3673. /**
  3674. * If the chest is open and you can skip floors, then move on
  3675. * Если сундук открыт и можно скипать этажи, то переходим дальше
  3676. */
  3677. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  3678. if (isOpenChest) {
  3679. nextOpenChest(floorNumber);
  3680. } else {
  3681. nextChestOpen(floorNumber);
  3682. }
  3683. return;
  3684. }
  3685.  
  3686. // console.log(towerInfo, scullCoin);
  3687. switch (towerInfo.floorType) {
  3688. case "battle":
  3689. if (floorNumber <= maySkipFloor) {
  3690. skipFloor();
  3691. return;
  3692. }
  3693. if (floorInfo.state == 2) {
  3694. nextFloor();
  3695. return;
  3696. }
  3697. startBattle().then(endBattle);
  3698. return;
  3699. case "buff":
  3700. checkBuff(towerInfo);
  3701. return;
  3702. case "chest":
  3703. openChest(floorNumber);
  3704. return;
  3705. default:
  3706. console.log('!', towerInfo.floorType, towerInfo);
  3707. break;
  3708. }
  3709. }
  3710.  
  3711. /**
  3712. * Let's start the fight
  3713. *
  3714. * Начинаем бой
  3715. */
  3716. function startBattle() {
  3717. return new Promise(function (resolve, reject) {
  3718. towerStartBattle = {
  3719. calls: [{
  3720. name: "towerStartBattle",
  3721. args: fixHeroesTeam(argsBattle),
  3722. ident: "body"
  3723. }]
  3724. }
  3725. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  3726. });
  3727. }
  3728. /**
  3729. * Returns the result of the battle in a promise
  3730. *
  3731. * Возращает резульат боя в промис
  3732. */
  3733. function resultBattle(resultBattles, resolve) {
  3734. battleData = resultBattles.results[0].result.response;
  3735. battleType = "get_tower";
  3736. BattleCalc(battleData, battleType, function (result) {
  3737. resolve(result);
  3738. });
  3739. }
  3740. /**
  3741. * Finishing the fight
  3742. *
  3743. * Заканчиваем бой
  3744. */
  3745. function endBattle(battleInfo) {
  3746. if (battleInfo.result.win) {
  3747. endBattleCall = {
  3748. calls: [{
  3749. name: "towerEndBattle",
  3750. args: {
  3751. result: battleInfo.result,
  3752. progress: battleInfo.progress,
  3753. },
  3754. ident: "body"
  3755. }]
  3756. }
  3757. send(JSON.stringify(endBattleCall), resultEndBattle);
  3758. } else {
  3759. endTower('towerEndBattle win: false\n', battleInfo);
  3760. }
  3761. }
  3762.  
  3763. /**
  3764. * Getting and processing battle results
  3765. *
  3766. * Получаем и обрабатываем результаты боя
  3767. */
  3768. function resultEndBattle(e) {
  3769. battleResult = e.results[0].result.response;
  3770. if ('error' in battleResult) {
  3771. endTower('errorBattleResult', battleResult);
  3772. return;
  3773. }
  3774. if ('reward' in battleResult) {
  3775. scullCoin += battleResult.reward?.coin[7] ?? 0;
  3776. }
  3777. nextFloor();
  3778. }
  3779.  
  3780. function nextFloor() {
  3781. nextFloorCall = {
  3782. calls: [{
  3783. name: "towerNextFloor",
  3784. args: {},
  3785. ident: "body"
  3786. }]
  3787. }
  3788. send(JSON.stringify(nextFloorCall), checkDataFloor);
  3789. }
  3790.  
  3791. function openChest(floorNumber) {
  3792. floorNumber = floorNumber || 0;
  3793. openChestCall = {
  3794. calls: [{
  3795. name: "towerOpenChest",
  3796. args: {
  3797. num: 2
  3798. },
  3799. ident: "body"
  3800. }]
  3801. }
  3802. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  3803. }
  3804.  
  3805. function lastChest() {
  3806. endTower('openChest 50 floor', floorNumber);
  3807. }
  3808.  
  3809. function skipFloor() {
  3810. skipFloorCall = {
  3811. calls: [{
  3812. name: "towerSkipFloor",
  3813. args: {},
  3814. ident: "body"
  3815. }]
  3816. }
  3817. send(JSON.stringify(skipFloorCall), checkDataFloor);
  3818. }
  3819.  
  3820. function checkBuff(towerInfo) {
  3821. buffArr = towerInfo.floor;
  3822. promises = [];
  3823. for (let buff of buffArr) {
  3824. buffInfo = buffIds[buff.id];
  3825. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  3826. scullCoin -= buffInfo.cost;
  3827. promises.push(buyBuff(buff.id));
  3828. }
  3829. }
  3830. Promise.all(promises).then(nextFloor);
  3831. }
  3832.  
  3833. function buyBuff(buffId) {
  3834. return new Promise(function (resolve, reject) {
  3835. buyBuffCall = {
  3836. calls: [{
  3837. name: "towerBuyBuff",
  3838. args: {
  3839. buffId
  3840. },
  3841. ident: "body"
  3842. }]
  3843. }
  3844. send(JSON.stringify(buyBuffCall), resolve);
  3845. });
  3846. }
  3847.  
  3848. function checkDataFloor(result) {
  3849. towerInfo = result.results[0].result.response;
  3850. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  3851. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  3852. }
  3853. if ('tower' in towerInfo) {
  3854. towerInfo = towerInfo.tower;
  3855. }
  3856. if ('skullReward' in towerInfo) {
  3857. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  3858. }
  3859. checkFloor(towerInfo);
  3860. }
  3861. /**
  3862. * Getting tower rewards
  3863. *
  3864. * Получаем награды башни
  3865. */
  3866. function farmTowerRewards(reason) {
  3867. let { pointRewards, points } = lastTowerInfo;
  3868. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  3869. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  3870. if (!farmPoints.length) {
  3871. return;
  3872. }
  3873. let farmTowerRewardsCall = {
  3874. calls: [{
  3875. name: "tower_farmPointRewards",
  3876. args: {
  3877. points: farmPoints
  3878. },
  3879. ident: "tower_farmPointRewards"
  3880. }]
  3881. }
  3882.  
  3883. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  3884. farmTowerRewardsCall.calls.push({
  3885. name: "tower_farmSkullReward",
  3886. args: {},
  3887. ident: "tower_farmSkullReward"
  3888. });
  3889. }
  3890.  
  3891. send(JSON.stringify(farmTowerRewardsCall), () => { });
  3892. }
  3893.  
  3894. function fullSkipTower() {
  3895. /**
  3896. * Next chest
  3897. *
  3898. * Следующий сундук
  3899. */
  3900. function nextChest(n) {
  3901. return {
  3902. name: "towerNextChest",
  3903. args: {},
  3904. ident: "group_" + n + "_body"
  3905. }
  3906. }
  3907. /**
  3908. * Open chest
  3909. *
  3910. * Открыть сундук
  3911. */
  3912. function openChest(n) {
  3913. return {
  3914. name: "towerOpenChest",
  3915. args: {
  3916. "num": 2
  3917. },
  3918. ident: "group_" + n + "_body"
  3919. }
  3920. }
  3921.  
  3922. const fullSkipTowerCall = {
  3923. calls: []
  3924. }
  3925.  
  3926. let n = 0;
  3927. for (let i = 0; i < 15; i++) {
  3928. fullSkipTowerCall.calls.push(nextChest(++n));
  3929. fullSkipTowerCall.calls.push(openChest(++n));
  3930. }
  3931.  
  3932. send(JSON.stringify(fullSkipTowerCall), data => {
  3933. data.results[0] = data.results[28];
  3934. checkDataFloor(data);
  3935. });
  3936. }
  3937.  
  3938. function nextChestOpen(floorNumber) {
  3939. const calls = [{
  3940. name: "towerOpenChest",
  3941. args: {
  3942. num: 2
  3943. },
  3944. ident: "towerOpenChest"
  3945. }];
  3946.  
  3947. Send(JSON.stringify({ calls })).then(e => {
  3948. nextOpenChest(floorNumber);
  3949. });
  3950. }
  3951.  
  3952. function nextOpenChest(floorNumber) {
  3953. if (floorNumber > 49) {
  3954. endTower('openChest 50 floor', floorNumber);
  3955. return;
  3956. }
  3957. if (floorNumber == 1) {
  3958. fullSkipTower();
  3959. return;
  3960. }
  3961.  
  3962. let nextOpenChestCall = {
  3963. calls: [{
  3964. name: "towerNextChest",
  3965. args: {},
  3966. ident: "towerNextChest"
  3967. }, {
  3968. name: "towerOpenChest",
  3969. args: {
  3970. num: 2
  3971. },
  3972. ident: "towerOpenChest"
  3973. }]
  3974. }
  3975. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  3976. }
  3977.  
  3978. function endTower(reason, info) {
  3979. console.log(reason, info);
  3980. if (reason != 'noTower') {
  3981. farmTowerRewards(reason);
  3982. }
  3983. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  3984. resolve();
  3985. }
  3986. }
  3987.  
  3988. /**
  3989. * Passage of the arena of the titans
  3990. *
  3991. * Прохождение арены титанов
  3992. */
  3993. function testTitanArena() {
  3994. return new Promise((resolve, reject) => {
  3995. titAren = new executeTitanArena(resolve, reject);
  3996. titAren.start();
  3997. });
  3998. }
  3999.  
  4000. /**
  4001. * Passage of the arena of the titans
  4002. *
  4003. * Прохождение арены титанов
  4004. */
  4005. function executeTitanArena(resolve, reject) {
  4006. let titan_arena = [];
  4007. let finishListBattle = [];
  4008. /**
  4009. * ID of the current batch
  4010. *
  4011. * Идетификатор текущей пачки
  4012. */
  4013. let currentRival = 0;
  4014. /**
  4015. * Number of attempts to finish off the pack
  4016. *
  4017. * Количество попыток добития пачки
  4018. */
  4019. let attempts = 0;
  4020. /**
  4021. * Was there an attempt to finish off the current shooting range
  4022. *
  4023. * Была ли попытка добития текущего тира
  4024. */
  4025. let isCheckCurrentTier = false;
  4026. /**
  4027. * Current shooting range
  4028. *
  4029. * Текущий тир
  4030. */
  4031. let currTier = 0;
  4032. /**
  4033. * Number of battles on the current dash
  4034. *
  4035. * Количество битв на текущем тире
  4036. */
  4037. let countRivalsTier = 0;
  4038.  
  4039. let callsStart = {
  4040. calls: [{
  4041. name: "titanArenaGetStatus",
  4042. args: {},
  4043. ident: "titanArenaGetStatus"
  4044. }, {
  4045. name: "teamGetAll",
  4046. args: {},
  4047. ident: "teamGetAll"
  4048. }]
  4049. }
  4050.  
  4051. this.start = function () {
  4052. send(JSON.stringify(callsStart), startTitanArena);
  4053. }
  4054.  
  4055. function startTitanArena(data) {
  4056. let titanArena = data.results[0].result.response;
  4057. if (titanArena.status == 'disabled') {
  4058. endTitanArena('disabled', titanArena);
  4059. return;
  4060. }
  4061.  
  4062. let teamGetAll = data.results[1].result.response;
  4063. titan_arena = teamGetAll.titan_arena;
  4064.  
  4065. checkTier(titanArena)
  4066. }
  4067.  
  4068. function checkTier(titanArena) {
  4069. if (titanArena.status == "peace_time") {
  4070. endTitanArena('Peace_time', titanArena);
  4071. return;
  4072. }
  4073. currTier = titanArena.tier;
  4074. if (currTier) {
  4075. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  4076. }
  4077.  
  4078. if (titanArena.status == "completed_tier") {
  4079. titanArenaCompleteTier();
  4080. return;
  4081. }
  4082. /**
  4083. * Checking for the possibility of a raid
  4084. * Проверка на возможность рейда
  4085. */
  4086. if (titanArena.canRaid) {
  4087. titanArenaStartRaid();
  4088. return;
  4089. }
  4090. /**
  4091. * Check was an attempt to achieve the current shooting range
  4092. * Проверка была ли попытка добития текущего тира
  4093. */
  4094. if (!isCheckCurrentTier) {
  4095. checkRivals(titanArena.rivals);
  4096. return;
  4097. }
  4098.  
  4099. endTitanArena('Done or not canRaid', titanArena);
  4100. }
  4101. /**
  4102. * Submit dash information for verification
  4103. *
  4104. * Отправка информации о тире на проверку
  4105. */
  4106. function checkResultInfo(data) {
  4107. let titanArena = data.results[0].result.response;
  4108. checkTier(titanArena);
  4109. }
  4110. /**
  4111. * Finish the current tier
  4112. *
  4113. * Завершить текущий тир
  4114. */
  4115. function titanArenaCompleteTier() {
  4116. isCheckCurrentTier = false;
  4117. let calls = [{
  4118. name: "titanArenaCompleteTier",
  4119. args: {},
  4120. ident: "body"
  4121. }];
  4122. send(JSON.stringify({calls}), checkResultInfo);
  4123. }
  4124. /**
  4125. * Gathering points to be completed
  4126. *
  4127. * Собираем точки которые нужно добить
  4128. */
  4129. function checkRivals(rivals) {
  4130. finishListBattle = [];
  4131. for (let n in rivals) {
  4132. if (rivals[n].attackScore < 250) {
  4133. finishListBattle.push(n);
  4134. }
  4135. }
  4136. console.log('checkRivals', finishListBattle);
  4137. countRivalsTier = finishListBattle.length;
  4138. roundRivals();
  4139. }
  4140. /**
  4141. * Selecting the next point to finish off
  4142. *
  4143. * Выбор следующей точки для добития
  4144. */
  4145. function roundRivals() {
  4146. let countRivals = finishListBattle.length;
  4147. if (!countRivals) {
  4148. /**
  4149. * Whole range checked
  4150. *
  4151. * Весь тир проверен
  4152. */
  4153. isCheckCurrentTier = true;
  4154. titanArenaGetStatus();
  4155. return;
  4156. }
  4157. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  4158. currentRival = finishListBattle.pop();
  4159. attempts = +currentRival;
  4160. // console.log('roundRivals', currentRival);
  4161. titanArenaStartBattle(currentRival);
  4162. }
  4163. /**
  4164. * The start of a solo battle
  4165. *
  4166. * Начало одиночной битвы
  4167. */
  4168. function titanArenaStartBattle(rivalId) {
  4169. let calls = [{
  4170. name: "titanArenaStartBattle",
  4171. args: {
  4172. rivalId: rivalId,
  4173. titans: titan_arena
  4174. },
  4175. ident: "body"
  4176. }];
  4177. send(JSON.stringify({calls}), calcResult);
  4178. }
  4179. /**
  4180. * Calculation of the results of the battle
  4181. *
  4182. * Расчет результатов боя
  4183. */
  4184. function calcResult(data) {
  4185. let battlesInfo = data.results[0].result.response.battle;
  4186. /**
  4187. * If attempts are equal to the current battle number we make
  4188. * Если попытки равны номеру текущего боя делаем прерасчет
  4189. */
  4190. if (attempts == currentRival) {
  4191. preCalcBattle(battlesInfo);
  4192. return;
  4193. }
  4194. /**
  4195. * If there are still attempts, we calculate a new battle
  4196. * Если попытки еще есть делаем расчет нового боя
  4197. */
  4198. if (attempts > 0) {
  4199. attempts--;
  4200. calcBattleResult(battlesInfo)
  4201. .then(resultCalcBattle);
  4202. return;
  4203. }
  4204. /**
  4205. * Otherwise, go to the next opponent
  4206. * Иначе переходим к следующему сопернику
  4207. */
  4208. roundRivals();
  4209. }
  4210. /**
  4211. * Processing the results of the battle calculation
  4212. *
  4213. * Обработка результатов расчета битвы
  4214. */
  4215. function resultCalcBattle(resultBattle) {
  4216. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  4217. /**
  4218. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  4219. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  4220. */
  4221. if (resultBattle.result.win || !attempts) {
  4222. titanArenaEndBattle({
  4223. progress: resultBattle.progress,
  4224. result: resultBattle.result,
  4225. rivalId: resultBattle.battleData.typeId
  4226. });
  4227. return;
  4228. }
  4229. /**
  4230. * If not victory and there are attempts we start a new battle
  4231. * Если не победа и есть попытки начинаем новый бой
  4232. */
  4233. titanArenaStartBattle(resultBattle.battleData.typeId);
  4234. }
  4235. /**
  4236. * Returns the promise of calculating the results of the battle
  4237. *
  4238. * Возращает промис расчета результатов битвы
  4239. */
  4240. function getBattleInfo(battle, isRandSeed) {
  4241. return new Promise(function (resolve) {
  4242. if (isRandSeed) {
  4243. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  4244. }
  4245. // console.log(battle.seed);
  4246. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  4247. });
  4248. }
  4249. /**
  4250. * Recalculate battles
  4251. *
  4252. * Прерасчтет битвы
  4253. */
  4254. function preCalcBattle(battle) {
  4255. let actions = [getBattleInfo(battle, false)];
  4256. const countTestBattle = getInput('countTestBattle');
  4257. for (let i = 0; i < countTestBattle; i++) {
  4258. actions.push(getBattleInfo(battle, true));
  4259. }
  4260. Promise.all(actions)
  4261. .then(resultPreCalcBattle);
  4262. }
  4263. /**
  4264. * Processing the results of the battle recalculation
  4265. *
  4266. * Обработка результатов прерасчета битвы
  4267. */
  4268. function resultPreCalcBattle(e) {
  4269. let wins = e.map(n => n.result.win);
  4270. let firstBattle = e.shift();
  4271. let countWin = wins.reduce((w, s) => w + s);
  4272. let numReval = countRivalsTier - finishListBattle.length;
  4273. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + numReval + '/' + countRivalsTier + ' - ' + countWin + '/11');
  4274. console.log('resultPreCalcBattle', countWin + '/11' )
  4275. if (countWin > 0) {
  4276. attempts = getInput('countAutoBattle');
  4277. } else {
  4278. attempts = 0;
  4279. }
  4280. resultCalcBattle(firstBattle);
  4281. }
  4282.  
  4283. /**
  4284. * Complete an arena battle
  4285. *
  4286. * Завершить битву на арене
  4287. */
  4288. function titanArenaEndBattle(args) {
  4289. let calls = [{
  4290. name: "titanArenaEndBattle",
  4291. args,
  4292. ident: "body"
  4293. }];
  4294. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  4295. }
  4296.  
  4297. function resultTitanArenaEndBattle(e) {
  4298. let attackScore = e.results[0].result.response.attackScore;
  4299. let numReval = countRivalsTier - finishListBattle.length;
  4300. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  4301. /**
  4302. * TODO: Might need to improve the results.
  4303. * TODO: Возможно стоит сделать улучшение результатов
  4304. */
  4305. // console.log('resultTitanArenaEndBattle', e)
  4306. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  4307. roundRivals();
  4308. }
  4309. /**
  4310. * Arena State
  4311. *
  4312. * Состояние арены
  4313. */
  4314. function titanArenaGetStatus() {
  4315. let calls = [{
  4316. name: "titanArenaGetStatus",
  4317. args: {},
  4318. ident: "body"
  4319. }];
  4320. send(JSON.stringify({calls}), checkResultInfo);
  4321. }
  4322. /**
  4323. * Arena Raid Request
  4324. *
  4325. * Запрос рейда арены
  4326. */
  4327. function titanArenaStartRaid() {
  4328. let calls = [{
  4329. name: "titanArenaStartRaid",
  4330. args: {
  4331. titans: titan_arena
  4332. },
  4333. ident: "body"
  4334. }];
  4335. send(JSON.stringify({calls}), calcResults);
  4336. }
  4337.  
  4338. function calcResults(data) {
  4339. let battlesInfo = data.results[0].result.response;
  4340. let {attackers, rivals} = battlesInfo;
  4341.  
  4342. let promises = [];
  4343. for (let n in rivals) {
  4344. rival = rivals[n];
  4345. promises.push(calcBattleResult({
  4346. attackers: attackers,
  4347. defenders: [rival.team],
  4348. seed: rival.seed,
  4349. typeId: n,
  4350. }));
  4351. }
  4352.  
  4353. Promise.all(promises)
  4354. .then(results => {
  4355. const endResults = {};
  4356. for (let info of results) {
  4357. let id = info.battleData.typeId;
  4358. endResults[id] = {
  4359. progress: info.progress,
  4360. result: info.result,
  4361. }
  4362. }
  4363. titanArenaEndRaid(endResults);
  4364. });
  4365. }
  4366.  
  4367. function calcBattleResult(battleData) {
  4368. return new Promise(function (resolve, reject) {
  4369. BattleCalc(battleData, "get_titanClanPvp", resolve);
  4370. });
  4371. }
  4372.  
  4373. /**
  4374. * Sending Raid Results
  4375. *
  4376. * Отправка результатов рейда
  4377. */
  4378. function titanArenaEndRaid(results) {
  4379. titanArenaEndRaidCall = {
  4380. calls: [{
  4381. name: "titanArenaEndRaid",
  4382. args: {
  4383. results
  4384. },
  4385. ident: "body"
  4386. }]
  4387. }
  4388. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  4389. }
  4390.  
  4391. function checkRaidResults(data) {
  4392. results = data.results[0].result.response.results;
  4393. isSucsesRaid = true;
  4394. for (let i in results) {
  4395. isSucsesRaid &&= (results[i].attackScore >= 250);
  4396. }
  4397.  
  4398. if (isSucsesRaid) {
  4399. titanArenaCompleteTier();
  4400. } else {
  4401. titanArenaGetStatus();
  4402. }
  4403. }
  4404.  
  4405. function titanArenaFarmDailyReward() {
  4406. titanArenaFarmDailyRewardCall = {
  4407. calls: [{
  4408. name: "titanArenaFarmDailyReward",
  4409. args: {},
  4410. ident: "body"
  4411. }]
  4412. }
  4413. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  4414. }
  4415.  
  4416. function endTitanArena(reason, info) {
  4417. if (!['Peace_time', 'disabled'].includes(reason)) {
  4418. titanArenaFarmDailyReward();
  4419. }
  4420. console.log(reason, info);
  4421. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  4422. resolve();
  4423. }
  4424. }
  4425. let hideTimeoutProgress = 0;
  4426. /**
  4427. * Hide progress
  4428. *
  4429. * Скрыть прогресс
  4430. */
  4431. function hideProgress(timeout) {
  4432. timeout = timeout || 0;
  4433. clearTimeout(hideTimeoutProgress);
  4434. hideTimeoutProgress = setTimeout(function () {
  4435. scriptMenu.setStatus('');
  4436. }, timeout);
  4437. }
  4438. /**
  4439. * Progress display
  4440. *
  4441. * Отображение прогресса
  4442. */
  4443. function setProgress(text, hide, onclick) {
  4444. scriptMenu.setStatus(text, onclick);
  4445. hide = hide || false;
  4446. if (hide) {
  4447. hideProgress(3000);
  4448. }
  4449. }
  4450. function hackGame() {
  4451. selfGame = null;
  4452. bindId = 1e9;
  4453. /**
  4454. * List of correspondence of used classes to their names
  4455. *
  4456. * Список соответствия используемых классов их названиям
  4457. */
  4458. ObjectsList = [
  4459. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  4460. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  4461. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  4462. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  4463. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  4464.  
  4465. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  4466. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  4467. {name:"GameModel", prop:"game.model.GameModel"},
  4468. {name:"CommandManager", prop:"game.command.CommandManager"},
  4469. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  4470. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  4471. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  4472. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  4473. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  4474. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  4475. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  4476. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  4477. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  4478. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  4479. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  4480. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  4481. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  4482. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  4483. {name:"SettingToggleButton", prop:"game.view.popup.settings.SettingToggleButton"},
  4484. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  4485. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  4486. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  4487. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  4488. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  4489. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  4490. {name:"BattleConfig", prop:"battle.BattleConfig"},
  4491. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  4492. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  4493. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  4494. ];
  4495. /**
  4496. * Contains the game classes needed to write and override game methods
  4497. *
  4498. * Содержит классы игры необходимые для написания и подмены методов игры
  4499. */
  4500. Game = {
  4501. /**
  4502. * Function 'e'
  4503. * Функция 'e'
  4504. */
  4505. bindFunc: function (a, b) {
  4506. if (null == b)
  4507. return null;
  4508. null == b.__id__ && (b.__id__ = bindId++);
  4509. var c;
  4510. null == a.hx__closures__ ? a.hx__closures__ = {} :
  4511. c = a.hx__closures__[b.__id__];
  4512. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  4513. return c
  4514. },
  4515. };
  4516. /**
  4517. * Connects to game objects via the object creation event
  4518. *
  4519. * Подключается к объектам игры через событие создания объекта
  4520. */
  4521. function connectGame() {
  4522. for (let obj of ObjectsList) {
  4523. /**
  4524. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  4525. */
  4526. Object.defineProperty(Object.prototype, obj.prop, {
  4527. set: function (value) {
  4528. if (!selfGame) {
  4529. selfGame = this;
  4530. }
  4531. if (!Game[obj.name]) {
  4532. Game[obj.name] = value;
  4533. }
  4534. // console.log('set ' + obj.prop, this, value);
  4535. this[obj.prop + '_'] = value;
  4536. },
  4537. get: function () {
  4538. // console.log('get ' + obj.prop, this);
  4539. return this[obj.prop + '_'];
  4540. }
  4541. });
  4542. }
  4543. }
  4544. /**
  4545. * Game.BattlePresets
  4546. * @param {bool} a isReplay
  4547. * @param {bool} b autoToggleable
  4548. * @param {bool} c auto On Start
  4549. * @param {object} d config
  4550. * @param {bool} f showBothTeams
  4551. */
  4552. /**
  4553. * Returns the results of the battle to the callback function
  4554. * Возвращает в функцию callback результаты боя
  4555. * @param {*} battleData battle data данные боя
  4556. * @param {*} battleConfig combat configuration type options:
  4557. *
  4558. * тип конфигурации боя варианты:
  4559. *
  4560. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  4561. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  4562. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  4563. *
  4564. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  4565. *
  4566. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  4567. * @param {*} callback функция в которую вернуться результаты боя
  4568. */
  4569. this.BattleCalc = function (battleData, battleConfig, callback) {
  4570. // battleConfig = battleConfig || getBattleType(battleData.type)
  4571. if (!Game.BattlePresets) throw Error('Use connectGame');
  4572. battlePresets = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  4573. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  4574. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  4575. battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  4576. battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  4577. callback({
  4578. battleData,
  4579. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  4580. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  4581. })
  4582. });
  4583. battleInstantPlay.start();
  4584. }
  4585.  
  4586. /**
  4587. * Returns a function with the specified name from the class
  4588. *
  4589. * Возвращает из класса функцию с указанным именем
  4590. * @param {Object} classF Class // класс
  4591. * @param {String} nameF function name // имя функции
  4592. * @param {String} pos name and alias order // порядок имени и псевдонима
  4593. * @returns
  4594. */
  4595. function getF(classF, nameF, pos) {
  4596. pos = pos || false;
  4597. let prop = Object.entries(classF.prototype.__properties__)
  4598. if (!pos) {
  4599. return prop.filter((e) => e[1] == nameF).pop()[0];
  4600. } else {
  4601. return prop.filter((e) => e[0] == nameF).pop()[1];
  4602. }
  4603. }
  4604.  
  4605. /**
  4606. * Returns a function with the specified name from the class
  4607. *
  4608. * Возвращает из класса функцию с указанным именем
  4609. * @param {Object} classF Class // класс
  4610. * @param {String} nameF function name // имя функции
  4611. * @returns
  4612. */
  4613. function getFnP(classF, nameF) {
  4614. let prop = Object.entries(classF.__properties__)
  4615. return prop.filter((e) => e[1] == nameF).pop()[0];
  4616. }
  4617.  
  4618. /**
  4619. * Returns the function name with the specified ordinal from the class
  4620. *
  4621. * Возвращает имя функции с указаным порядковым номером из класса
  4622. * @param {Object} classF Class // класс
  4623. * @param {Number} nF Order number of function // порядковый номер функции
  4624. * @returns
  4625. */
  4626. function getFn(classF, nF) {
  4627. let prop = Object.keys(classF);
  4628. return prop[nF];
  4629. }
  4630.  
  4631. /**
  4632. * Returns the name of the function with the specified serial number from the prototype of the class
  4633. *
  4634. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  4635. * @param {Object} classF Class // класс
  4636. * @param {Number} nF Order number of function // порядковый номер функции
  4637. * @returns
  4638. */
  4639. function getProtoFn(classF, nF) {
  4640. let prop = Object.keys(classF.prototype);
  4641. return prop[nF];
  4642. }
  4643. /**
  4644. * Description of replaced functions
  4645. *
  4646. * Описание подменяемых функций
  4647. */
  4648. replaceFunction = {
  4649. company: function() {
  4650. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  4651. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  4652. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  4653. if (isChecked('passBattle')) {
  4654. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  4655.  
  4656. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  4657. a = new Game.BattleInstantPlay(c, a);
  4658. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  4659. a.start()
  4660. } else {
  4661. oldSkipMisson.call(this, a, b, c);
  4662. }
  4663. }
  4664.  
  4665. Game.PlayerMissionData.prototype.P$h = function (a) {
  4666. let GM_2 = getFn(Game.GameModel, 2);
  4667. let GM_P2 = getProtoFn(Game.GameModel, 2);
  4668. let CM_20 = getProtoFn(Game.CommandManager, 20);
  4669. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  4670. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  4671. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  4672. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  4673. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  4674. }
  4675. },
  4676. tower: function() {
  4677. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  4678. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  4679. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  4680. if (isChecked('passBattle')) {
  4681. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  4682. a = new Game.BattleInstantPlay(a, p);
  4683. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  4684. a.start()
  4685. } else {
  4686. oldSkipTower.call(this, a);;
  4687. }
  4688. }
  4689.  
  4690. Game.PlayerTowerData.prototype.P$h = function (a) {
  4691. let GM_2 = getFn(Game.GameModel, 2);
  4692. let GM_P2 = getProtoFn(Game.GameModel, 2);
  4693. let CM_29 = getProtoFn(Game.CommandManager, 29);
  4694. let TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  4695. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  4696. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  4697. let PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  4698. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]))
  4699. }
  4700. },
  4701. // skipSelectHero: function() {
  4702. // if (!HOST) throw Error('Use connectGame');
  4703. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  4704. // },
  4705. passBattle: function() {
  4706. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  4707. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  4708. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  4709. if (isChecked('passBattle')) {
  4710. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  4711. this[getProtoFn(Game.BattlePausePopup, 3)]();
  4712. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  4713. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabel, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  4714.  
  4715. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](Game.Translate.translate("UI_POPUP_BATTLE_RETREAT"), (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 15)]))); /** 14 > 15 */
  4716. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  4717. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 12)](),
  4718. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]() ?
  4719. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) :
  4720. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) /** 15 > 16 */
  4721. );
  4722.  
  4723. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabel, 23)]();
  4724. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 8)]());
  4725. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  4726. } else {
  4727. oldPassBattle.call(this, a);
  4728. }
  4729. }
  4730.  
  4731. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  4732. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  4733. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  4734. if (isChecked('passBattle')) {
  4735. return 'ПРОПУСК';
  4736. } else {
  4737. return oldFunc.call(this);
  4738. }
  4739. }
  4740. },
  4741. endlessCards: function() {
  4742. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  4743. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  4744. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  4745. if (isChecked('endlessCards')) {
  4746. return true;
  4747. } else {
  4748. return oldEndlessCards.call(this);
  4749. }
  4750. }
  4751. },
  4752. speedBattle: function () {
  4753. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  4754. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  4755. Game.BattleController.prototype[get_timeScale] = function () {
  4756. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  4757. if (speedBattle) {
  4758. const BC_11 = getProtoFn(Game.BattleController, 11);
  4759. const BSM_11 = getProtoFn(Game.BattleSettingsModel, 11);
  4760. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  4761. if (this[BC_11][BSM_11][BP_get_value]()) {
  4762. return 0;
  4763. }
  4764. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  4765. const BC_44 = getProtoFn(Game.BattleController, 44);
  4766. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  4767. const BC_13 = getProtoFn(Game.BattleController, 13);
  4768. const BC_3 = getFn(Game.BattleController, 3);
  4769. if (this[BC_11][BSM_2][BP_get_value]()) {
  4770. var a = speedBattle * this[BC_44]();
  4771. } else {
  4772. a = this[BC_11][BSM_1][BP_get_value]();
  4773. //const multiple = a == 1 ? speedBattle : this[BC_13][a];
  4774. a = this[BC_13][a] * Game.BattleController[BC_3][BP_get_value]() * this[BC_44]();
  4775. }
  4776. const BSM_22 = getProtoFn(Game.BattleSettingsModel, 22);
  4777. a > this[BC_11][BSM_22][BP_get_value]() && (a = this[BC_11][BSM_22][BP_get_value]());
  4778. const DS_21 = getFn(Game.DataStorage, 21);
  4779. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  4780. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  4781. var b = Game.DataStorage[DS_21][get_battleSpeedMultiplier]();
  4782. const R_1 = getFn(selfGame.Reflect, 1);
  4783. const BC_1 = getFn(Game.BattleController, 1);
  4784. const get_config = getF(Game.BattlePresets, "get_config");
  4785. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  4786. null != b && (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) : a * selfGame.Reflect[R_1](b, "default"));
  4787. return a
  4788. } else {
  4789. return oldSpeedBattle.call(this);
  4790. }
  4791. }
  4792. },
  4793. /**
  4794. * Remove the rare shop
  4795. *
  4796. * Удаление торговца редкими товарами
  4797. */
  4798. removeWelcomeShop: function () {
  4799. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  4800. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  4801. Game.SpecialShopModel.prototype[SSM_3] = function () {
  4802. if (isChecked('noOfferDonat')) {
  4803. return null;
  4804. } else {
  4805. return oldWelcomeShop.call(this);
  4806. }
  4807. }
  4808. },
  4809. /**
  4810. * Acceleration button without Valkyries favor
  4811. *
  4812. * Кнопка ускорения без Покровительства Валькирий
  4813. */
  4814. battleFastKey: function () {
  4815. const BGM_37 = getProtoFn(Game.BattleGuiMediator, 37);
  4816. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_37];
  4817. Game.BattleGuiMediator.prototype[BGM_37] = function () {
  4818. if (true) {
  4819. const BGM_8 = getProtoFn(Game.BattleGuiMediator, 8);
  4820. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  4821. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  4822. this[BGM_8][BPW_0](true);
  4823. this[BGM_9][BPW_0](true);
  4824. } else {
  4825. return oldBattleFastKey.call(this);
  4826. }
  4827. }
  4828. }
  4829. }
  4830. /**
  4831. * Starts replacing recorded functions
  4832. *
  4833. * Запускает замену записанных функций
  4834. */
  4835. this.activateHacks = function () {
  4836. if (!selfGame) throw Error('Use connectGame');
  4837. for (let func in replaceFunction) {
  4838. replaceFunction[func]();
  4839. }
  4840. }
  4841. /**
  4842. * Returns the game object
  4843. *
  4844. * Возвращает объект игры
  4845. */
  4846. this.getSelfGame = function () {
  4847. return selfGame;
  4848. }
  4849. /**
  4850. * Updates game data
  4851. *
  4852. * Обновляет данные игры
  4853. */
  4854. this.refreshGame = function () {
  4855. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  4856. }
  4857.  
  4858. /**
  4859. * Change the play screen on windowName
  4860. *
  4861. * Сменить экран игры на windowName
  4862. *
  4863. * Possible options:
  4864. *
  4865. * Возможные варианты:
  4866. *
  4867. * 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
  4868. */
  4869. this.goNavigtor = function (windowName) {
  4870. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  4871. let window = mechanicStorage[windowName];
  4872. let event = selfGame["game.mediator.gui.popup.PopupStashEventParams"]('');
  4873. let Game = selfGame['Game'];
  4874. let navigator = getF(Game, "get_navigator")
  4875. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  4876. let instance = getFnP(Game, 'get_instance');
  4877. Game[instance]()[navigator]()[navigate](window, event);
  4878. }
  4879. /**
  4880. * Move to the sanctuary cheats.goSanctuary()
  4881. *
  4882. * Переместиться в святилище cheats.goSanctuary()
  4883. */
  4884. this.goSanctuary = () => {
  4885. this.goNavigtor("SANCTUARY");
  4886. }
  4887. /**
  4888. * Go to Guild War
  4889. *
  4890. * Перейти к Войне Гильдий
  4891. */
  4892. this.goClanWar = function() {
  4893. let instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  4894. let player = selfGame["game.model.GameModel"][instance]().A;
  4895. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  4896. new clanWarSelect(player).open();
  4897. }
  4898.  
  4899. connectGame();
  4900. }
  4901. /**
  4902. * Auto collection of gifts
  4903. *
  4904. * Автосбор подарков
  4905. */
  4906. function getAutoGifts() {
  4907. let valName = 'giftSendIds_' + userInfo.id;
  4908.  
  4909. if (!localStorage['clearGift' + userInfo.id]) {
  4910. localStorage[valName] = '';
  4911. localStorage['clearGift' + userInfo.id] = '+';
  4912. }
  4913.  
  4914. if (!localStorage[valName]) {
  4915. localStorage[valName] = '';
  4916. }
  4917.  
  4918. /**
  4919. * Submit a request to receive gift codes
  4920. *
  4921. * Отправка запроса для получения кодов подарков
  4922. */
  4923. fetch('https://zingery.ru/heroes/getGifts.php', {
  4924. method: 'POST',
  4925. body: JSON.stringify({scriptInfo, userInfo})
  4926. }).then(
  4927. response => response.json()
  4928. ).then(
  4929. data => {
  4930. let freebieCheckCalls = {
  4931. calls: []
  4932. }
  4933. data.forEach((giftId, n) => {
  4934. if (localStorage[valName].includes(giftId)) return;
  4935. //localStorage[valName] += ';' + giftId;
  4936. freebieCheckCalls.calls.push({
  4937. name: "freebieCheck",
  4938. args: {
  4939. giftId
  4940. },
  4941. ident: giftId
  4942. });
  4943. });
  4944.  
  4945. if (!freebieCheckCalls.calls.length) {
  4946. return;
  4947. }
  4948.  
  4949. send(JSON.stringify(freebieCheckCalls), e => {
  4950. let countGetGifts = 0;
  4951. const gifts = [];
  4952. for (check of e.results) {
  4953. gifts.push(check.ident);
  4954. if (check.result.response != null) {
  4955. countGetGifts++;
  4956. }
  4957. }
  4958. const saveGifts = localStorage[valName].split(';');
  4959. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  4960. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  4961. });
  4962. }
  4963. )
  4964. }
  4965. /**
  4966. * To fill the kills in the Forge of Souls
  4967. *
  4968. * Набить килов в горниле душ
  4969. */
  4970. async function bossRatingEvent() {
  4971. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  4972. if (!topGet) {
  4973. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  4974. return;
  4975. }
  4976. const replayId = topGet.results[0].result.response[0].userData.replayId;
  4977. const result = await Send(JSON.stringify({
  4978. calls: [
  4979. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  4980. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  4981. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  4982. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  4983. ]
  4984. }));
  4985. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  4986. if (!bossEventInfo) {
  4987. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  4988. return;
  4989. }
  4990. const usedHeroes = bossEventInfo.progress.usedHeroes;
  4991. const party = Object.values(result.results[0].result.response.replay.attackers);
  4992. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  4993. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  4994. const calls = [];
  4995. /**
  4996. * First pack
  4997. *
  4998. * Первая пачка
  4999. */
  5000. const args = {
  5001. heroes: [],
  5002. favor: {}
  5003. }
  5004. for (let hero of party) {
  5005. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  5006. args.pet = hero.id;
  5007. continue;
  5008. }
  5009. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  5010. continue;
  5011. }
  5012. args.heroes.push(hero.id);
  5013. if (hero.favorPetId) {
  5014. args.favor[hero.id] = hero.favorPetId;
  5015. }
  5016. }
  5017. if (args.heroes.length) {
  5018. calls.push({
  5019. name: "bossRatingEvent_startBattle",
  5020. args,
  5021. ident: "body_0"
  5022. });
  5023. }
  5024. /**
  5025. * Other packs
  5026. *
  5027. * Другие пачки
  5028. */
  5029. let heroes = [];
  5030. let count = 1;
  5031. while (heroId = availableHeroes.pop()) {
  5032. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  5033. continue;
  5034. }
  5035. heroes.push(heroId);
  5036. if (heroes.length == 5) {
  5037. calls.push({
  5038. name: "bossRatingEvent_startBattle",
  5039. args: {
  5040. heroes: [...heroes],
  5041. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  5042. },
  5043. ident: "body_" + count
  5044. });
  5045. heroes = [];
  5046. count++;
  5047. }
  5048. }
  5049.  
  5050. if (!calls.length) {
  5051. setProgress(`${I18N('NO_HEROES')}`, true);
  5052. return;
  5053. }
  5054.  
  5055. const resultBattles = await Send(JSON.stringify({ calls }));
  5056. console.log(resultBattles);
  5057. rewardBossRatingEvent();
  5058. }
  5059. /**
  5060. * Collecting Rewards from the Forge of Souls
  5061. *
  5062. * Сбор награды из Горнила Душ
  5063. */
  5064. function rewardBossRatingEvent() {
  5065. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  5066. send(rewardBossRatingCall, function (data) {
  5067. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  5068. if (!bossEventInfo) {
  5069. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  5070. return;
  5071. }
  5072.  
  5073. let farmedChests = bossEventInfo.progress.farmedChests;
  5074. let score = bossEventInfo.progress.score;
  5075. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  5076. let revard = bossEventInfo.reward;
  5077.  
  5078. let getRewardCall = {
  5079. calls: []
  5080. }
  5081.  
  5082. let count = 0;
  5083. for (let i = 1; i < 10; i++) {
  5084. if (farmedChests.includes(i)) {
  5085. continue;
  5086. }
  5087. if (score < revard[i].score) {
  5088. break;
  5089. }
  5090. getRewardCall.calls.push({
  5091. name: "bossRatingEvent_getReward",
  5092. args: {
  5093. rewardId: i
  5094. },
  5095. ident: "body_" + i
  5096. });
  5097. count++;
  5098. }
  5099. if (!count) {
  5100. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  5101. return;
  5102. }
  5103.  
  5104. send(JSON.stringify(getRewardCall), e => {
  5105. console.log(e);
  5106. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  5107. });
  5108. });
  5109. }
  5110. /**
  5111. * Collect Easter eggs and event rewards
  5112. *
  5113. * Собрать пасхалки и награды событий
  5114. */
  5115. function offerFarmAllReward() {
  5116. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  5117. return Send(offerGetAllCall).then((data) => {
  5118. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  5119. if (!offerGetAll.length) {
  5120. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  5121. return;
  5122. }
  5123.  
  5124. const calls = [];
  5125. for (let reward of offerGetAll) {
  5126. calls.push({
  5127. name: "offerFarmReward",
  5128. args: {
  5129. offerId: reward.id
  5130. },
  5131. ident: "offerFarmReward_" + reward.id
  5132. });
  5133. }
  5134.  
  5135. return Send(JSON.stringify({ calls })).then(e => {
  5136. console.log(e);
  5137. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  5138. });
  5139. });
  5140. }
  5141. /**
  5142. * Assemble Outland
  5143. *
  5144. * Собрать запределье
  5145. */
  5146. function getOutland() {
  5147. return new Promise(function (resolve, reject) {
  5148. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  5149. let bosses = e.results[0].result.response;
  5150.  
  5151. let bossRaidOpenChestCall = {
  5152. calls: []
  5153. };
  5154.  
  5155. for (let boss of bosses) {
  5156. if (boss.mayRaid) {
  5157. bossRaidOpenChestCall.calls.push({
  5158. name: "bossRaid",
  5159. args: {
  5160. bossId: boss.id
  5161. },
  5162. ident: "bossRaid_" + boss.id
  5163. });
  5164. bossRaidOpenChestCall.calls.push({
  5165. name: "bossOpenChest",
  5166. args: {
  5167. bossId: boss.id,
  5168. amount: 1,
  5169. starmoney: 0
  5170. },
  5171. ident: "bossOpenChest_" + boss.id
  5172. });
  5173. } else if (boss.chestId == 1) {
  5174. bossRaidOpenChestCall.calls.push({
  5175. name: "bossOpenChest",
  5176. args: {
  5177. bossId: boss.id,
  5178. amount: 1,
  5179. starmoney: 0
  5180. },
  5181. ident: "bossOpenChest_" + boss.id
  5182. });
  5183. }
  5184. }
  5185.  
  5186. if (!bossRaidOpenChestCall.calls.length) {
  5187. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  5188. resolve();
  5189. return;
  5190. }
  5191.  
  5192. send(JSON.stringify(bossRaidOpenChestCall), e => {
  5193. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  5194. resolve();
  5195. });
  5196. });
  5197. });
  5198. }
  5199. /**
  5200. * Collect all rewards
  5201. *
  5202. * Собрать все награды
  5203. */
  5204. function questAllFarm() {
  5205. return new Promise(function (resolve, reject) {
  5206. let questGetAllCall = {
  5207. calls: [{
  5208. name: "questGetAll",
  5209. args: {},
  5210. ident: "body"
  5211. }]
  5212. }
  5213. send(JSON.stringify(questGetAllCall), function (data) {
  5214. let questGetAll = data.results[0].result.response;
  5215. const questAllFarmCall = {
  5216. calls: []
  5217. }
  5218. let number = 0;
  5219. for (let quest of questGetAll) {
  5220. if (quest.id < 1e6 && quest.state == 2) {
  5221. questAllFarmCall.calls.push({
  5222. name: "questFarm",
  5223. args: {
  5224. questId: quest.id
  5225. },
  5226. ident: `group_${number}_body`
  5227. });
  5228. number++;
  5229. }
  5230. }
  5231.  
  5232. if (!questAllFarmCall.calls.length) {
  5233. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  5234. resolve();
  5235. return;
  5236. }
  5237.  
  5238. send(JSON.stringify(questAllFarmCall), function (res) {
  5239. console.log(res);
  5240. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  5241. resolve();
  5242. });
  5243. });
  5244. })
  5245. }
  5246.  
  5247. /**
  5248. * Attack of the minions of Asgard
  5249. *
  5250. * Атака прислужников Асгарда
  5251. */
  5252. function testRaidNodes() {
  5253. return new Promise((resolve, reject) => {
  5254. const tower = new executeRaidNodes(resolve, reject);
  5255. tower.start();
  5256. });
  5257. }
  5258.  
  5259. /**
  5260. * Attack of the minions of Asgard
  5261. *
  5262. * Атака прислужников Асгарда
  5263. */
  5264. function executeRaidNodes(resolve, reject) {
  5265. let raidData = {
  5266. teams: [],
  5267. favor: {},
  5268. nodes: [],
  5269. attempts: 0,
  5270. countExecuteBattles: 0,
  5271. cancelBattle: 0,
  5272. }
  5273.  
  5274. callsExecuteRaidNodes = {
  5275. calls: [{
  5276. name: "clanRaid_getInfo",
  5277. args: {},
  5278. ident: "clanRaid_getInfo"
  5279. }, {
  5280. name: "teamGetAll",
  5281. args: {},
  5282. ident: "teamGetAll"
  5283. }, {
  5284. name: "teamGetFavor",
  5285. args: {},
  5286. ident: "teamGetFavor"
  5287. }]
  5288. }
  5289.  
  5290. this.start = function () {
  5291. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  5292. }
  5293.  
  5294. function startRaidNodes(data) {
  5295. res = data.results;
  5296. clanRaidInfo = res[0].result.response;
  5297. teamGetAll = res[1].result.response;
  5298. teamGetFavor = res[2].result.response;
  5299.  
  5300. let index = 0;
  5301. for (let team of teamGetAll.clanRaid_nodes) {
  5302. raidData.teams.push({
  5303. data: {},
  5304. heroes: team.filter(id => id < 6000),
  5305. pet: team.filter(id => id >= 6000).pop(),
  5306. battleIndex: index++
  5307. });
  5308. }
  5309. raidData.favor = teamGetFavor.clanRaid_nodes;
  5310.  
  5311. raidData.nodes = clanRaidInfo.nodes;
  5312. raidData.attempts = clanRaidInfo.attempts;
  5313. isCancalBattle = false;
  5314.  
  5315. checkNodes();
  5316. }
  5317.  
  5318. function getAttackNode() {
  5319. for (let nodeId in raidData.nodes) {
  5320. let node = raidData.nodes[nodeId];
  5321. let points = 0
  5322. for (team of node.teams) {
  5323. points += team.points;
  5324. }
  5325. let now = Date.now() / 1000;
  5326. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  5327. let countTeam = node.teams.length;
  5328. delete raidData.nodes[nodeId];
  5329. return {
  5330. nodeId,
  5331. countTeam
  5332. };
  5333. }
  5334. }
  5335. return null;
  5336. }
  5337.  
  5338. function checkNodes() {
  5339. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  5340. let nodeInfo = getAttackNode();
  5341. if (nodeInfo && raidData.attempts) {
  5342. startNodeBattles(nodeInfo);
  5343. return;
  5344. }
  5345.  
  5346. endRaidNodes('EndRaidNodes');
  5347. }
  5348.  
  5349. function startNodeBattles(nodeInfo) {
  5350. let {nodeId, countTeam} = nodeInfo;
  5351. let teams = raidData.teams.slice(0, countTeam);
  5352. let heroes = raidData.teams.map(e => e.heroes).flat();
  5353. let favor = {...raidData.favor};
  5354. for (let heroId in favor) {
  5355. if (!heroes.includes(+heroId)) {
  5356. delete favor[heroId];
  5357. }
  5358. }
  5359.  
  5360. let calls = [{
  5361. name: "clanRaid_startNodeBattles",
  5362. args: {
  5363. nodeId,
  5364. teams,
  5365. favor
  5366. },
  5367. ident: "body"
  5368. }];
  5369.  
  5370. send(JSON.stringify({calls}), resultNodeBattles);
  5371. }
  5372.  
  5373. function resultNodeBattles(e) {
  5374. if (e['error']) {
  5375. endRaidNodes('nodeBattlesError', e['error']);
  5376. return;
  5377. }
  5378.  
  5379. console.log(e);
  5380. let battles = e.results[0].result.response.battles;
  5381. let promises = [];
  5382. let battleIndex = 0;
  5383. for (let battle of battles) {
  5384. battle.battleIndex = battleIndex++;
  5385. promises.push(calcBattleResult(battle));
  5386. }
  5387.  
  5388. Promise.all(promises)
  5389. .then(results => {
  5390. const endResults = {};
  5391. let isAllWin = true;
  5392. for (let r of results) {
  5393. isAllWin &&= r.result.win;
  5394. }
  5395. if (!isAllWin) {
  5396. cancelEndNodeBattle(results[0]);
  5397. return;
  5398. }
  5399. raidData.countExecuteBattles = results.length;
  5400. let timeout = 500;
  5401. for (let r of results) {
  5402. setTimeout(endNodeBattle, timeout, r);
  5403. timeout += 500;
  5404. }
  5405. });
  5406. }
  5407. /**
  5408. * Returns the battle calculation promise
  5409. *
  5410. * Возвращает промис расчета боя
  5411. */
  5412. function calcBattleResult(battleData) {
  5413. return new Promise(function (resolve, reject) {
  5414. BattleCalc(battleData, "get_clanPvp", resolve);
  5415. });
  5416. }
  5417. /**
  5418. * Cancels the fight
  5419. *
  5420. * Отменяет бой
  5421. */
  5422. function cancelEndNodeBattle(r) {
  5423. const fixBattle = function (heroes) {
  5424. for (const ids in heroes) {
  5425. hero = heroes[ids];
  5426. hero.energy = random(1, 999);
  5427. if (hero.hp > 0) {
  5428. hero.hp = random(1, hero.hp);
  5429. }
  5430. }
  5431. }
  5432. fixBattle(r.progress[0].attackers.heroes);
  5433. fixBattle(r.progress[0].defenders.heroes);
  5434. endNodeBattle(r);
  5435. }
  5436. /**
  5437. * Ends the fight
  5438. *
  5439. * Завершает бой
  5440. */
  5441. function endNodeBattle(r) {
  5442. let nodeId = r.battleData.result.nodeId;
  5443. let battleIndex = r.battleData.battleIndex;
  5444. let calls = [{
  5445. name: "clanRaid_endNodeBattle",
  5446. args: {
  5447. nodeId,
  5448. battleIndex,
  5449. result: r.result,
  5450. progress: r.progress
  5451. },
  5452. ident: "body"
  5453. }]
  5454.  
  5455. SendRequest(JSON.stringify({calls}), battleResult);
  5456. }
  5457. /**
  5458. * Processing the results of the battle
  5459. *
  5460. * Обработка результатов боя
  5461. */
  5462. function battleResult(e) {
  5463. if (e['error']) {
  5464. endRaidNodes('missionEndError', e['error']);
  5465. return;
  5466. }
  5467. r = e.results[0].result.response;
  5468. if (r['error']) {
  5469. if (r.reason == "invalidBattle") {
  5470. raidData.cancelBattle++;
  5471. checkNodes();
  5472. } else {
  5473. endRaidNodes('missionEndError', e['error']);
  5474. }
  5475. return;
  5476. }
  5477.  
  5478. if (!(--raidData.countExecuteBattles)) {
  5479. raidData.attempts--;
  5480. checkNodes();
  5481. }
  5482. }
  5483. /**
  5484. * Completing a task
  5485. *
  5486. * Завершение задачи
  5487. */
  5488. function endRaidNodes(reason, info) {
  5489. isCancalBattle = true;
  5490. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  5491. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  5492. console.log(reason, info);
  5493. resolve();
  5494. }
  5495. }
  5496. /**
  5497. * Mission auto repeat
  5498. *
  5499. * Автоповтор миссии
  5500. * isStopSendMission = false;
  5501. * isSendsMission = true;
  5502. **/
  5503. this.sendsMission = async function (param) {
  5504. if (isStopSendMission) {
  5505. isSendsMission = false;
  5506. console.log(I18N('STOPPED'));
  5507. setProgress('');
  5508. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  5509. msg: 'Ok',
  5510. result: true
  5511. }, ])
  5512. return;
  5513. }
  5514.  
  5515. let missionStartCall = {
  5516. "calls": [{
  5517. "name": "missionStart",
  5518. "args": lastMissionStart,
  5519. "ident": "body"
  5520. }]
  5521. }
  5522. /**
  5523. * Mission Request
  5524. *
  5525. * Запрос на выполнение мисии
  5526. */
  5527. SendRequest(JSON.stringify(missionStartCall), async e => {
  5528. if (e['error']) {
  5529. isSendsMission = false;
  5530. console.log(e['error']);
  5531. setProgress('');
  5532. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  5533. await popup.confirm(msg, [
  5534. {msg: 'Ok', result: true},
  5535. ])
  5536. return;
  5537. }
  5538. /**
  5539. * Mission data calculation
  5540. *
  5541. * Расчет данных мисии
  5542. */
  5543. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  5544.  
  5545. let missionEndCall = {
  5546. "calls": [{
  5547. "name": "missionEnd",
  5548. "args": {
  5549. "id": param.id,
  5550. "result": r.result,
  5551. "progress": r.progress
  5552. },
  5553. "ident": "body"
  5554. }]
  5555. }
  5556. /**
  5557. * Mission Completion Request
  5558. *
  5559. * Запрос на завершение миссии
  5560. */
  5561. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  5562. if (e['error']) {
  5563. isSendsMission = false;
  5564. console.log(e['error']);
  5565. setProgress('');
  5566. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  5567. await popup.confirm(msg, [
  5568. {msg: 'Ok', result: true},
  5569. ])
  5570. return;
  5571. }
  5572. r = e.results[0].result.response;
  5573. if (r['error']) {
  5574. isSendsMission = false;
  5575. console.log(r['error']);
  5576. setProgress('');
  5577. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  5578. {msg: 'Ok', result: true},
  5579. ])
  5580. return;
  5581. }
  5582.  
  5583. param.count++;
  5584. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  5585. isStopSendMission = true;
  5586. });
  5587. setTimeout(sendsMission, 1, param);
  5588. });
  5589. })
  5590. });
  5591. }
  5592. /**
  5593. * Recursive opening of matryoshka dolls
  5594. *
  5595. * Рекурсивное открытие матрешек
  5596. */
  5597. function openRussianDoll(id, count, sum) {
  5598. sum = sum || 0;
  5599. sum += count;
  5600. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  5601. setProgress(`${I18N('OPEN')} ${count}`, true);
  5602. let result = e.results[0].result.response;
  5603. let newCount = 0;
  5604. for(let n of result) {
  5605. if (n?.consumable && n.consumable[id]) {
  5606. newCount += n.consumable[id]
  5607. }
  5608. }
  5609. if (newCount) {
  5610. openRussianDoll(id, newCount, sum);
  5611. } else {
  5612. popup.confirm(`${I18N('TOTAL_OPEN')} ${sum}`);
  5613. }
  5614. })
  5615. }
  5616.  
  5617. /**
  5618. * Asgard Boss Attack Replay
  5619. *
  5620. * Повтор атаки босса Асгарда
  5621. */
  5622. function testBossBattle() {
  5623. return new Promise((resolve, reject) => {
  5624. const bossBattle = new executeBossBattle(resolve, reject);
  5625. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  5626. });
  5627. }
  5628.  
  5629. /**
  5630. * Asgard Boss Attack Replay
  5631. *
  5632. * Повтор атаки босса Асгарда
  5633. */
  5634. function executeBossBattle(resolve, reject) {
  5635. let lastBossBattleArgs = {};
  5636. let reachDamage = 0;
  5637. let countBattle = 0;
  5638. let countMaxBattle = 10;
  5639. let lastDamage = 0;
  5640.  
  5641. this.start = function (battleArg, battleInfo) {
  5642. lastBossBattleArgs = battleArg;
  5643. preCalcBattle(battleInfo);
  5644. }
  5645.  
  5646. function getBattleInfo(battle) {
  5647. return new Promise(function (resolve) {
  5648. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5649. BattleCalc(battle, getBattleType(battle.type), e => {
  5650. let extra = e.progress[0].defenders.heroes[1].extra;
  5651. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  5652. });
  5653. });
  5654. }
  5655.  
  5656. function preCalcBattle(battle) {
  5657. let actions = [];
  5658. const countTestBattle = getInput('countTestBattle');
  5659. for (let i = 0; i < countTestBattle; i++) {
  5660. actions.push(getBattleInfo(battle, true));
  5661. }
  5662. Promise.all(actions)
  5663. .then(resultPreCalcBattle);
  5664. }
  5665.  
  5666. function fixDamage(damage) {
  5667. for (let i = 1e6; i > 1; i /= 10) {
  5668. if (damage > i) {
  5669. let n = i / 10;
  5670. damage = Math.ceil(damage / n) * n;
  5671. break;
  5672. }
  5673. }
  5674. return damage;
  5675. }
  5676.  
  5677. async function resultPreCalcBattle(damages) {
  5678. let maxDamage = 0;
  5679. let minDamage = 1e10;
  5680. let avgDamage = 0;
  5681. for (let damage of damages) {
  5682. avgDamage += damage
  5683. if (damage > maxDamage) {
  5684. maxDamage = damage;
  5685. }
  5686. if (damage < minDamage) {
  5687. minDamage = damage;
  5688. }
  5689. }
  5690. avgDamage /= damages.length;
  5691. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  5692.  
  5693. reachDamage = fixDamage(avgDamage);
  5694. const result = await popup.confirm(
  5695. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  5696. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  5697. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  5698. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  5699. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  5700. , [
  5701. { msg: I18N('BTN_OK'), result: 0},
  5702. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  5703. ])
  5704. if (result) {
  5705. reachDamage = result;
  5706. isCancalBossBattle = false;
  5707. startBossBattle();
  5708. return;
  5709. }
  5710. endBossBattle(I18N('BTN_CANCEL'));
  5711. }
  5712.  
  5713. function startBossBattle() {
  5714. countBattle++;
  5715. countMaxBattle = getInput('countAutoBattle');
  5716. if (countBattle > countMaxBattle) {
  5717. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  5718. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  5719. return;
  5720. }
  5721. let calls = [{
  5722. name: "clanRaid_startBossBattle",
  5723. args: lastBossBattleArgs,
  5724. ident: "body"
  5725. }];
  5726. send(JSON.stringify({calls}), calcResultBattle);
  5727. }
  5728.  
  5729. function calcResultBattle(e) {
  5730. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  5731. }
  5732.  
  5733. async function resultBattle(e) {
  5734. let extra = e.progress[0].defenders.heroes[1].extra
  5735. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  5736. console.log(resultDamage);
  5737. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  5738. lastDamage = resultDamage;
  5739. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  5740. {msg: 'Ок', result: true},
  5741. {msg: 'Не пойдет', result: false},
  5742. ])) {
  5743. endBattle(e, false);
  5744. return;
  5745. }
  5746. cancelEndBattle(e);
  5747. }
  5748.  
  5749. function cancelEndBattle (r) {
  5750. const fixBattle = function (heroes) {
  5751. for (const ids in heroes) {
  5752. hero = heroes[ids];
  5753. hero.energy = random(1, 999);
  5754. if (hero.hp > 0) {
  5755. hero.hp = random(1, hero.hp);
  5756. }
  5757. }
  5758. }
  5759. fixBattle(r.progress[0].attackers.heroes);
  5760. fixBattle(r.progress[0].defenders.heroes);
  5761. endBattle(r, true);
  5762. }
  5763.  
  5764. function endBattle(battleResult, isCancal) {
  5765. let calls = [{
  5766. name: "clanRaid_endBossBattle",
  5767. args: {
  5768. result: battleResult.result,
  5769. progress: battleResult.progress
  5770. },
  5771. ident: "body"
  5772. }];
  5773.  
  5774. send(JSON.stringify({calls}), e => {
  5775. console.log(e);
  5776. if (isCancal) {
  5777. startBossBattle();
  5778. return;
  5779. }
  5780. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  5781. setTimeout(() => {
  5782. scriptMenu.setStatus('');
  5783. }, 5000);
  5784. endBossBattle('Узпех!');
  5785. });
  5786. }
  5787.  
  5788. /**
  5789. * Completing a task
  5790. *
  5791. * Завершение задачи
  5792. */
  5793. function endBossBattle(reason, info) {
  5794. isCancalBossBattle = true;
  5795. console.log(reason, info);
  5796. resolve();
  5797. }
  5798. }
  5799.  
  5800. /**
  5801. * Auto-repeat attack
  5802. *
  5803. * Автоповтор атаки
  5804. */
  5805. function testAutoBattle() {
  5806. return new Promise((resolve, reject) => {
  5807. const bossBattle = new executeAutoBattle(resolve, reject);
  5808. bossBattle.start(lastBattleArg, lastBattleInfo);
  5809. });
  5810. }
  5811.  
  5812. /**
  5813. * Auto-repeat attack
  5814. *
  5815. * Автоповтор атаки
  5816. */
  5817. function executeAutoBattle(resolve, reject) {
  5818. let battleArg = {};
  5819. let countBattle = 0;
  5820. let countMaxBattle = 10;
  5821.  
  5822. this.start = function (battleArgs, battleInfo) {
  5823. battleArg = battleArgs;
  5824. preCalcBattle(battleInfo);
  5825. }
  5826. /**
  5827. * Returns a promise for combat recalculation
  5828. *
  5829. * Возвращает промис для прерасчета боя
  5830. */
  5831. function getBattleInfo(battle) {
  5832. return new Promise(function (resolve) {
  5833. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5834. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  5835. });
  5836. }
  5837. /**
  5838. * Battle recalculation
  5839. *
  5840. * Прерасчет боя
  5841. */
  5842. function preCalcBattle(battle) {
  5843. let actions = [];
  5844. const countTestBattle = getInput('countTestBattle');
  5845. for (let i = 0; i < countTestBattle; i++) {
  5846. actions.push(getBattleInfo(battle));
  5847. }
  5848. Promise.all(actions)
  5849. .then(resultPreCalcBattle);
  5850. }
  5851. /**
  5852. * Processing the results of the battle recalculation
  5853. *
  5854. * Обработка результатов прерасчета боя
  5855. */
  5856. function resultPreCalcBattle(results) {
  5857. let countWin = results.reduce((w, s) => w + s);
  5858. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, true);
  5859. if (countWin > 0) {
  5860. isCancalBattle = false;
  5861. startBattle();
  5862. return;
  5863. }
  5864. endAutoBattle(I18N('NOT_THIS_TIME'));
  5865. }
  5866. /**
  5867. * Start battle
  5868. *
  5869. * Начало боя
  5870. */
  5871. function startBattle() {
  5872. countBattle++;
  5873. countMaxBattle = getInput('countAutoBattle');
  5874. setProgress(countBattle + '/' + countMaxBattle);
  5875. if (countBattle > countMaxBattle) {
  5876. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  5877. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  5878. return;
  5879. }
  5880. let calls = [{
  5881. name: nameFuncStartBattle,
  5882. args: battleArg,
  5883. ident: "body"
  5884. }];
  5885. send(JSON.stringify({
  5886. calls
  5887. }), calcResultBattle);
  5888. }
  5889. /**
  5890. * Battle calculation
  5891. *
  5892. * Расчет боя
  5893. */
  5894. function calcResultBattle(e) {
  5895. let battle = e.results[0].result.response.battle
  5896. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  5897. }
  5898. /**
  5899. * Processing the results of the battle
  5900. *
  5901. * Обработка результатов боя
  5902. */
  5903. function resultBattle(e) {
  5904. let isWin = e.result.win;
  5905. console.log(isWin);
  5906. if (isWin) {
  5907. endBattle(e, false);
  5908. return;
  5909. }
  5910. cancelEndBattle(e);
  5911. }
  5912. /**
  5913. * Cancel fight
  5914. *
  5915. * Отмена боя
  5916. */
  5917. function cancelEndBattle(r) {
  5918. const fixBattle = function (heroes) {
  5919. for (const ids in heroes) {
  5920. hero = heroes[ids];
  5921. hero.energy = random(1, 999);
  5922. if (hero.hp > 0) {
  5923. hero.hp = random(1, hero.hp);
  5924. }
  5925. }
  5926. }
  5927. fixBattle(r.progress[0].attackers.heroes);
  5928. fixBattle(r.progress[0].defenders.heroes);
  5929. endBattle(r, true);
  5930. }
  5931. /**
  5932. * End of the fight
  5933. *
  5934. * Завершение боя */
  5935. function endBattle(battleResult, isCancal) {
  5936. let calls = [{
  5937. name: nameFuncEndBattle,
  5938. args: {
  5939. result: battleResult.result,
  5940. progress: battleResult.progress
  5941. },
  5942. ident: "body"
  5943. }];
  5944.  
  5945. send(JSON.stringify({
  5946. calls
  5947. }), e => {
  5948. console.log(e);
  5949. if (isCancal) {
  5950. startBattle();
  5951. return;
  5952. }
  5953. scriptMenu.setStatus(`${I18N('VICTORY')}!`);
  5954. setTimeout(() => {
  5955. scriptMenu.setStatus('');
  5956. }, 5000)
  5957. endAutoBattle(`${I18N('SUCCESS')}!`)
  5958. });
  5959. }
  5960. /**
  5961. * Completing a task
  5962. *
  5963. * Завершение задачи
  5964. */
  5965. function endAutoBattle(reason, info) {
  5966. isCancalBattle = true;
  5967. console.log(reason, info);
  5968. resolve();
  5969. }
  5970. }
  5971. /**
  5972. * Collect all mail, except letters with energy and charges of the portal
  5973. *
  5974. * Собрать всю почту, кроме писем с энергией и зарядами портала
  5975. */
  5976. function mailGetAll() {
  5977. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  5978.  
  5979. return Send(getMailInfo).then(dataMail => {
  5980. const letters = dataMail.results[0].result.response.letters;
  5981. const letterIds = lettersFilter(letters);
  5982. if (!letterIds.length) {
  5983. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  5984. return;
  5985. }
  5986.  
  5987. const calls = [
  5988. { name: "mailFarm", args: { letterIds }, ident: "body" }
  5989. ];
  5990.  
  5991. return Send(JSON.stringify({ calls })).then(res => {
  5992. const lettersIds = res.results[0].result.response;
  5993. if (lettersIds) {
  5994. const countLetters = Object.keys(lettersIds).length;
  5995. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  5996. }
  5997. });
  5998. });
  5999. }
  6000. /**
  6001. * Filters received emails
  6002. *
  6003. * Фильтрует получаемые письма
  6004. */
  6005. function lettersFilter(letters) {
  6006. const lettersIds = [];
  6007. for (let l in letters) {
  6008. letter = letters[l];
  6009. const reward = letter.reward;
  6010. /**
  6011. * Mail Collection Exceptions
  6012. *
  6013. * Исключения на сбор писем
  6014. */
  6015. const isFarmLetter = !(
  6016. /** Portals // сферы портала */
  6017. (reward?.refillable ? reward.refillable[45] : false) ||
  6018. /** Energy // энергия */
  6019. (reward?.stamina ? reward.stamina : false) ||
  6020. /** accelerating energy gain // ускорение набора энергии */
  6021. (reward?.buff ? true : false) ||
  6022. /** VIP Points // вип очки */
  6023. (reward?.vipPoints ? reward.vipPoints : false) ||
  6024. /** souls of heroes // душы героев */
  6025. (reward?.fragmentHero ? true : false) ||
  6026. /** heroes // герои */
  6027. (reward?.bundleHeroReward ? true : false)
  6028. );
  6029. if (isFarmLetter) {
  6030. lettersIds.push(~~letter.id);
  6031. }
  6032. }
  6033. return lettersIds;
  6034. }
  6035. /**
  6036. * Displaying information about the areas of the portal and attempts on the VG
  6037. *
  6038. * Отображение информации о сферах портала и попытках на ВГ
  6039. */
  6040. async function justInfo() {
  6041. return new Promise(async (resolve, reject) => {
  6042. const calls = [{
  6043. name: "userGetInfo",
  6044. args: {},
  6045. ident: "userGetInfo"
  6046. },
  6047. {
  6048. name: "clanWarGetInfo",
  6049. args: {},
  6050. ident: "clanWarGetInfo"
  6051. }];
  6052. const result = await Send(JSON.stringify({ calls }));
  6053. const infos = result.results;
  6054. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  6055. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  6056. const sanctuaryButton = buttons['goToSanctuary'].button;
  6057. const clanWarButton = buttons['goToClanWar'].button;
  6058. if (portalSphere.amount) {
  6059. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  6060. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  6061. } else {
  6062. sanctuaryButton.style.color = '';
  6063. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  6064. }
  6065. if (clanWarMyTries) {
  6066. clanWarButton.style.color = 'red';
  6067. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  6068. } else {
  6069. clanWarButton.style.color = '';
  6070. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  6071. }
  6072. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  6073. resolve();
  6074. });
  6075. }
  6076.  
  6077. function testDailyQuests() {
  6078. return new Promise((resolve, reject) => {
  6079. const bossBattle = new dailyQuests(resolve, reject, questsInfo);
  6080. bossBattle.start();
  6081. });
  6082. }
  6083. /**
  6084. * Automatic completion of daily quests
  6085. *
  6086. * Автоматическое выполнение ежедневных квестов
  6087. */
  6088. class dailyQuests {
  6089. /**
  6090. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  6091. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  6092. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  6093. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  6094. */
  6095. dataQuests = {
  6096. 10001: {
  6097. /**
  6098. * TODO: Watch heroes and money
  6099. * TODO: Смотреть героев и деньги
  6100. */
  6101. description: 'Улучши умения героев 3 раза', //
  6102. isWeCanDo: () => false,
  6103. },
  6104. 10002: {
  6105. description: 'Пройди 10 миссий', // --------------
  6106. isWeCanDo: () => false,
  6107. },
  6108. 10003: {
  6109. description: 'Пройди 3 героические миссии', // --------------
  6110. isWeCanDo: () => false,
  6111. },
  6112. 10004: {
  6113. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  6114. isWeCanDo: () => false,
  6115. },
  6116. 10006: {
  6117. description: 'Используй обмен изумрудов 1 раз',
  6118. doItCall: [{ name: "refillableAlchemyUse", args: { multi: false }, ident: "refillableAlchemyUse" }],
  6119. isWeCanDo: () => false,
  6120. },
  6121. 10007: {
  6122. description: 'Открой 1 сундук', // ++++++++++++++++
  6123. doItCall: [{ name: "chestBuy", args: { chest: "town", free: true, pack: false }, ident: "chestBuy" }],
  6124. isWeCanDo: (info) => {
  6125. const chestInfo = info['userGetInfo'].refillable.find(e => e.id == 37);
  6126. return chestInfo.amount > 0;
  6127. },
  6128. },
  6129. 10016: {
  6130. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  6131. doItCall: [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  6132. isWeCanDo: () => true,
  6133. },
  6134. 10018: {
  6135. /**
  6136. * TODO: Watch heroes, watch potions (consumable 9, 10, 11, 12)
  6137. * TODO: Смотреть героев, смотреть зелья (consumable 9, 10, 11, 12)
  6138. */
  6139. description: 'Используй зелье опыта',
  6140. /**
  6141. * Spends a bank of experience on Galahard
  6142. * Тратит банку опыта на Галахарда
  6143. */
  6144. doItCall: [{ name: "consumableUseHeroXp", args: { heroId: 2, libId: 10, amount: 1 }, ident: "consumableUseHeroXp" }],
  6145. isWeCanDo: () => false,
  6146. },
  6147. 10019: {
  6148. description: 'Открой 1 сундук в Башне',
  6149. doItFunc: testTower,
  6150. isWeCanDo: () => false,
  6151. },
  6152. 10020: {
  6153. description: 'Открой 3 сундука в Запределье',
  6154. isWeCanDo: () => false,
  6155. },
  6156. 10021: {
  6157. description: 'Собери 75 Титанита в Подземелье Гильдии',
  6158. isWeCanDo: () => false,
  6159. },
  6160. 10022: {
  6161. description: 'Собери 150 Титанита в Подземелье Гильдии',
  6162. doItFunc: testDungeon,
  6163. isWeCanDo: () => false,
  6164. },
  6165. 10023: {
  6166. /**
  6167. * TODO: Watch heroes, watch sparks (24 consumable, 250 at level 0 and 7000 gold)
  6168. * TODO: Смотреть героев, смотреть искры (consumable 24, 250 на 0 уровне и золото 7000)
  6169. */
  6170. description: 'Прокачай Дар Стихий на 1 уровень',
  6171. /**
  6172. * Upgrade and Reset Gift of the Elements to Galahard
  6173. * Улучшение и сброс дара стихий Галахарду
  6174. */
  6175. doItCall: [
  6176. { name: "heroTitanGiftLevelUp", args: { heroId: 2 }, ident: "heroTitanGiftLevelUp" },
  6177. { name: "heroTitanGiftDrop", args: { heroId: 2 }, ident: "heroTitanGiftDrop" }
  6178. ],
  6179. isWeCanDo: () => false,
  6180. },
  6181. 10024: {
  6182. /**
  6183. * TODO: Watch Heroes
  6184. * TODO: Смотреть героев
  6185. */
  6186. description: 'Повысь уровень любого артефакта один раз',
  6187. isWeCanDo: () => false,
  6188. },
  6189. 10025: {
  6190. description: 'Начни 1 Экспедицию',
  6191. doItFunc: checkExpedition,
  6192. isWeCanDo: () => false,
  6193. },
  6194. 10026: {
  6195. description: 'Начни 4 Экспедиции', // --------------
  6196. doItFunc: checkExpedition,
  6197. isWeCanDo: () => false,
  6198. },
  6199. 10027: {
  6200. description: 'Победи в 1 бою Турнира Стихий',
  6201. doItFunc: testTitanArena,
  6202. isWeCanDo: () => false,
  6203. },
  6204. 10028: {
  6205. /**
  6206. * TODO: Смотреть титанов, можно качать арты за золото если золота больше 5 лямов
  6207. * TODO: Watch titans, you can download arts for gold if there is more than 5kk gold
  6208. */
  6209. description: 'Повысь уровень любого артефакта титанов',
  6210. isWeCanDo: () => false,
  6211. },
  6212. 10029: {
  6213. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  6214. doItCall: [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  6215. isWeCanDo: (info) => {
  6216. return info['inventoryGet']?.consumable[55] > 0
  6217. },
  6218. },
  6219. 10030: {
  6220. /**
  6221. * TODO: Watch Heroes
  6222. * TODO: Смотреть героев
  6223. */
  6224. description: 'Улучши облик любого героя 1 раз',
  6225. isWeCanDo: () => false,
  6226. },
  6227. 10031: {
  6228. description: 'Победи в 6 боях Турнира Стихий', // --------------
  6229. doItFunc: testTitanArena,
  6230. isWeCanDo: () => false,
  6231. },
  6232. 10043: {
  6233. description: 'Начни или присоеденись к Приключению', // --------------
  6234. isWeCanDo: () => false,
  6235. },
  6236. 10044: {
  6237. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  6238. doItCall: [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  6239. isWeCanDo: (info) => {
  6240. return info['inventoryGet']?.consumable[90] > 0
  6241. },
  6242. },
  6243. 10046: {
  6244. /**
  6245. * TODO: Watch Adventure
  6246. * TODO: Смотреть приключение
  6247. */
  6248. description: 'Открой 3 сундука в Приключениях',
  6249. isWeCanDo: () => false,
  6250. },
  6251. 10047: {
  6252. /**
  6253. * TODO: Watch heroes and runes consumable 1, 2, 3, 4
  6254. * TODO: Смотреть героев и руны consumable 1, 2, 3, 4
  6255. */
  6256. description: 'Набери 150 очков активности в Гильдии',
  6257. /**
  6258. * Upgrade the rune Galahard
  6259. * Прокачать руну Галахарду
  6260. */
  6261. doItCall: [{ name: "heroEnchantRune", args: { heroId: 2, tier: 0, items: { consumable: { '1': 1 } } }, ident: "heroEnchantRune" }],
  6262. isWeCanDo: () => false,
  6263. },
  6264. };
  6265.  
  6266. constructor(resolve, reject, questInfo) {
  6267. this.resolve = resolve;
  6268. this.reject = reject;
  6269. this.questInfo = questInfo
  6270. }
  6271.  
  6272. async start() {
  6273. /**
  6274. * TODO may not be needed
  6275. *
  6276. * TODO возожно не нужна
  6277. */
  6278. let countQuest = 0;
  6279. const weCanDo = [];
  6280. const selectedActions = getSaveVal('selectedActions', {});
  6281. for (let quest of this.questInfo['questGetAll']) {
  6282. if (quest.id in this.dataQuests && quest.state == 1) {
  6283. if (!selectedActions[quest.id]) {
  6284. selectedActions[quest.id] = {
  6285. checked: false
  6286. }
  6287. }
  6288. if (!this.dataQuests[quest.id].isWeCanDo(this.questInfo)) {
  6289. continue;
  6290. }
  6291. weCanDo.push({
  6292. name: quest.id,
  6293. label: I18N(`QUEST_${quest.id}`),
  6294. checked: selectedActions[quest.id].checked
  6295. });
  6296. countQuest++;
  6297. }
  6298. }
  6299.  
  6300. if (!weCanDo.length) {
  6301. this.end(I18N('NOTHING_TO_DO'));
  6302. return;
  6303. }
  6304.  
  6305. console.log(weCanDo);
  6306. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  6307. { msg: I18N('BTN_DO_IT'), result: true },
  6308. { msg: I18N('BTN_CANCEL'), result: false },
  6309. ], weCanDo);
  6310. if (!answer) {
  6311. this.end('');
  6312. return;
  6313. }
  6314. const taskList = popup.getCheckBoxes();
  6315. taskList.forEach(e => {
  6316. selectedActions[e.name].checked = e.checked;
  6317. });
  6318. setSaveVal('selectedActions', selectedActions);
  6319. const calls = [];
  6320. let countChecked = 0;
  6321. for (const task of taskList) {
  6322. if (task.checked) {
  6323. countChecked++;
  6324. const quest = this.dataQuests[task.name]
  6325. console.log(quest.description);
  6326.  
  6327. if (quest.doItCall) {
  6328. calls.push(...quest.doItCall);
  6329. }
  6330. }
  6331. }
  6332.  
  6333. if (!countChecked) {
  6334. this.end(I18N('NOT_QUEST_COMPLETED'));
  6335. return;
  6336. }
  6337.  
  6338. await Send(JSON.stringify({ calls }));
  6339. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  6340. }
  6341.  
  6342. errorHandling(error) {
  6343. //console.error(error);
  6344. let errorInfo = error.toString() + '\n';
  6345. try {
  6346. const errorStack = error.stack.split('\n');
  6347. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  6348. errorInfo += errorStack.slice(0, endStack).join('\n');
  6349. } catch (e) {
  6350. errorInfo += error.stack;
  6351. }
  6352. copyText(errorInfo);
  6353. }
  6354.  
  6355. end(status) {
  6356. setProgress(status, true);
  6357. this.resolve();
  6358. }
  6359. }
  6360.  
  6361. function testDoYourBest() {
  6362. return new Promise((resolve, reject) => {
  6363. const doIt = new doYourBest(resolve, reject);
  6364. doIt.start();
  6365. });
  6366. }
  6367. /**
  6368. * Do everything button
  6369. *
  6370. * Кнопка сделать все
  6371. */
  6372. class doYourBest {
  6373.  
  6374. funcList = [
  6375. {
  6376. name: 'getOutland',
  6377. label: I18N('ASSEMBLE_OUTLAND'),
  6378. checked: false
  6379. },
  6380. {
  6381. name: 'testTower',
  6382. label: I18N('PASS_THE_TOWER'),
  6383. checked: false
  6384. },
  6385. {
  6386. name: 'checkExpedition',
  6387. label: I18N('CHECK_EXPEDITIONS'),
  6388. checked: false
  6389. },
  6390. {
  6391. name: 'testTitanArena',
  6392. label: I18N('COMPLETE_TOE'),
  6393. checked: false
  6394. },
  6395. {
  6396. name: 'testDungeon',
  6397. label: I18N('COMPLETE_DUNGEON'),
  6398. checked: false
  6399. },
  6400. {
  6401. name: 'mailGetAll',
  6402. label: I18N('COLLECT_MAIL'),
  6403. checked: false
  6404. },
  6405. {
  6406. name: 'collectAllStuff',
  6407. label: I18N('COLLECT_MISC'),
  6408. checked: false
  6409. },
  6410. {
  6411. name: 'questAllFarm',
  6412. label: I18N('COLLECT_QUEST_REWARDS'),
  6413. checked: false
  6414. },
  6415. {
  6416. name: 'synchronization',
  6417. label: I18N('MAKE_A_SYNC'),
  6418. checked: false
  6419. },
  6420. ];
  6421.  
  6422. functions = {
  6423. getOutland,
  6424. testTower,
  6425. checkExpedition,
  6426. testTitanArena,
  6427. testDungeon,
  6428. mailGetAll,
  6429. collectAllStuff: async () => {
  6430. await offerFarmAllReward();
  6431. await Send('{"calls":[{"name":"subscriptionFarm","args":{},"ident":"body"},{"name":"zeppelinGiftFarm","args":{},"ident":"zeppelinGiftFarm"},{"name":"grandFarmCoins","args":{},"ident":"grandFarmCoins"}]}');
  6432. },
  6433. questAllFarm,
  6434. synchronization: async () => {
  6435. cheats.refreshGame();
  6436. }
  6437. }
  6438.  
  6439. constructor(resolve, reject, questInfo) {
  6440. this.resolve = resolve;
  6441. this.reject = reject;
  6442. this.questInfo = questInfo
  6443. }
  6444.  
  6445. async start() {
  6446. const selectedDoIt = getSaveVal('selectedDoIt', {});
  6447.  
  6448. this.funcList.forEach(task => {
  6449. if (!selectedDoIt[task.name]) {
  6450. selectedDoIt[task.name] = {
  6451. checked: task.checked
  6452. }
  6453. } else {
  6454. task.checked = selectedDoIt[task.name].checked
  6455. }
  6456. });
  6457.  
  6458. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  6459. { msg: I18N('BTN_CANCEL'), result: false },
  6460. { msg: I18N('BTN_GO'), result: true },
  6461. ], this.funcList);
  6462.  
  6463. if (!answer) {
  6464. this.end('');
  6465. return;
  6466. }
  6467.  
  6468. const taskList = popup.getCheckBoxes();
  6469. taskList.forEach(task => {
  6470. selectedDoIt[task.name].checked = task.checked;
  6471. });
  6472. setSaveVal('selectedDoIt', selectedDoIt);
  6473. for (const task of popup.getCheckBoxes()) {
  6474. if (task.checked) {
  6475. try {
  6476. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  6477. await this.functions[task.name]();
  6478. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  6479. } catch (error) {
  6480. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  6481. { msg: I18N('BTN_NO'), result: false },
  6482. { msg: I18N('BTN_YES'), result: true },
  6483. ])) {
  6484. this.errorHandling(error);
  6485. }
  6486. }
  6487. }
  6488. }
  6489. setTimeout((msg) => {
  6490. this.end(msg);
  6491. }, 2000, I18N('ALL_TASK_COMPLETED'));
  6492. return;
  6493. }
  6494.  
  6495. errorHandling(error) {
  6496. //console.error(error);
  6497. let errorInfo = error.toString() + '\n';
  6498. try {
  6499. const errorStack = error.stack.split('\n');
  6500. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  6501. errorInfo += errorStack.slice(0, endStack).join('\n');
  6502. } catch (e) {
  6503. errorInfo += error.stack;
  6504. }
  6505. copyText(errorInfo);
  6506. }
  6507.  
  6508. end(status) {
  6509. setProgress(status, true);
  6510. this.resolve();
  6511. }
  6512. }
  6513. /**
  6514. * Passing the adventure along the specified route
  6515. *
  6516. * Прохождение приключения по указанному маршруту
  6517. */
  6518. function testAdventure(type) {
  6519. return new Promise((resolve, reject) => {
  6520. const bossBattle = new executeAdventure(resolve, reject);
  6521. bossBattle.start(type);
  6522. });
  6523. }
  6524. /**
  6525. * Passing the adventure along the specified route
  6526. *
  6527. * Прохождение приключения по указанному маршруту
  6528. */
  6529. class executeAdventure {
  6530.  
  6531. type = 'default';
  6532.  
  6533. actions = {
  6534. default: {
  6535. getInfo: "adventure_getInfo",
  6536. startBattle: 'adventure_turnStartBattle',
  6537. endBattle: 'adventure_endBattle',
  6538. collectBuff: 'adventure_turnCollectBuff'
  6539. },
  6540. solo: {
  6541. getInfo: "adventureSolo_getInfo",
  6542. startBattle: 'adventureSolo_turnStartBattle',
  6543. endBattle: 'adventureSolo_endBattle',
  6544. collectBuff: 'adventureSolo_turnCollectBuff'
  6545. }
  6546. }
  6547.  
  6548. terminatеReason = I18N('UNKNOWN');
  6549. callAdventureInfo = {
  6550. name: "adventure_getInfo",
  6551. args: {},
  6552. ident: "adventure_getInfo"
  6553. }
  6554. callTeamGetAll = {
  6555. name: "teamGetAll",
  6556. args: {},
  6557. ident: "teamGetAll"
  6558. }
  6559. callTeamGetFavor = {
  6560. name: "teamGetFavor",
  6561. args: {},
  6562. ident: "teamGetFavor"
  6563. }
  6564. callStartBattle = {
  6565. name: "adventure_turnStartBattle",
  6566. args: {},
  6567. ident: "body"
  6568. }
  6569. callEndBattle = {
  6570. name: "adventure_endBattle",
  6571. args: {
  6572. result: {},
  6573. progress: {},
  6574. },
  6575. ident: "body"
  6576. }
  6577. callCollectBuff = {
  6578. name: "adventure_turnCollectBuff",
  6579. args: {},
  6580. ident: "body"
  6581. }
  6582.  
  6583. constructor(resolve, reject) {
  6584. this.resolve = resolve;
  6585. this.reject = reject;
  6586. }
  6587.  
  6588. async start(type) {
  6589. this.type = type || this.type;
  6590. this.path = await this.getPath();
  6591. if (!this.path) {
  6592. this.end();
  6593. return;
  6594. }
  6595. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  6596. const data = await Send(JSON.stringify({
  6597. calls: [
  6598. this.callAdventureInfo,
  6599. this.callTeamGetAll,
  6600. this.callTeamGetFavor
  6601. ]
  6602. }));
  6603. return this.checkAdventureInfo(data.results);
  6604. }
  6605.  
  6606. async getPath() {
  6607. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  6608. {
  6609. msg: I18N('START_ADVENTURE'),
  6610. placeholder: '1,2,3,4,5,6',
  6611. isInput: true,
  6612. default: getSaveVal('adventurePath', '')
  6613. },
  6614. {
  6615. msg: I18N('BTN_CANCEL'),
  6616. result: false
  6617. },
  6618. ]);
  6619. if (!answer) {
  6620. this.terminatеReason = I18N('BTN_CANCELED');
  6621. return false;
  6622. }
  6623. let path = answer.split(',');
  6624. if (path.length < 2) {
  6625. this.terminatеReason = I18N('MUST_TWO_POINTS');
  6626. return false;
  6627. }
  6628.  
  6629. for (let p in path) {
  6630. path[p] = +path[p].trim()
  6631. if (Number.isNaN(path[p])) {
  6632. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  6633. return false;
  6634. }
  6635. }
  6636. setSaveVal('adventurePath', answer);
  6637. return path;
  6638. }
  6639.  
  6640. checkAdventureInfo(data) {
  6641. this.advInfo = data[0].result.response;
  6642. if (!this.advInfo) {
  6643. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  6644. return this.end();
  6645. }
  6646. const heroesTeam = data[1].result.response.adventure_hero;
  6647. const favor = data[2]?.result.response.adventure_hero;
  6648. const heroes = heroesTeam.slice(0, 5);
  6649. const pet = heroesTeam[5];
  6650. this.args = {
  6651. pet,
  6652. heroes,
  6653. favor,
  6654. path: [],
  6655. broadcast: false
  6656. }
  6657. const advUserInfo = this.advInfo.users[userInfo.id];
  6658. this.turnsLeft = advUserInfo.turnsLeft;
  6659. this.currentNode = advUserInfo.currentNode;
  6660. this.nodes = this.advInfo.nodes;
  6661. return this.loop();
  6662. }
  6663.  
  6664. async loop() {
  6665. const position = this.path.indexOf(+this.currentNode);
  6666. if (!(~position)) {
  6667. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  6668. return this.end();
  6669. }
  6670. this.path = this.path.slice(position);
  6671. if ((this.path.length - 1) > this.turnsLeft &&
  6672. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  6673. { msg: I18N('YES_CONTINUE'), result: false },
  6674. { msg: I18N('BTN_NO'), result: true },
  6675. ])) {
  6676. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  6677. return this.end();
  6678. }
  6679. const toPath = [];
  6680. for (const nodeId of this.path) {
  6681. if (!this.turnsLeft) {
  6682. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  6683. return this.end();
  6684. }
  6685. toPath.push(nodeId);
  6686. console.log(toPath);
  6687. if (toPath.length > 1) {
  6688. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  6689. }
  6690. if (nodeId == this.currentNode) {
  6691. continue;
  6692. }
  6693.  
  6694. const nodeInfo = this.getNodeInfo(nodeId);
  6695. if (nodeInfo.type == 'TYPE_COMBAT') {
  6696. if (nodeInfo.state == 'empty') {
  6697. this.turnsLeft--;
  6698. continue;
  6699. }
  6700.  
  6701. /**
  6702. * Disable regular battle cancellation
  6703. *
  6704. * Отключаем штатную отменую боя
  6705. */
  6706. isCancalBattle = false;
  6707. if (await this.battle(toPath)) {
  6708. this.turnsLeft--;
  6709. toPath.splice(0, toPath.indexOf(nodeId));
  6710. nodeInfo.state = 'empty';
  6711. isCancalBattle = true;
  6712. continue;
  6713. }
  6714. isCancalBattle = true;
  6715. return this.end()
  6716. }
  6717.  
  6718. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  6719. const buff = this.checkBuff(nodeInfo);
  6720. if (buff == null) {
  6721. continue;
  6722. }
  6723.  
  6724. if (await this.collectBuff(buff, toPath)) {
  6725. this.turnsLeft--;
  6726. toPath.splice(0, toPath.indexOf(nodeId));
  6727. continue;
  6728. }
  6729. this.terminatеReason = I18N('BUFF_GET_ERROR');
  6730. return this.end();
  6731. }
  6732. }
  6733. this.terminatеReason = I18N('SUCCESS');
  6734. return this.end();
  6735. }
  6736.  
  6737. /**
  6738. * Carrying out a fight
  6739. *
  6740. * Проведение боя
  6741. */
  6742. async battle(path, preCalc = true) {
  6743. const data = await this.startBattle(path);
  6744. try {
  6745. const battle = data.results[0].result.response.battle;
  6746. const result = await Calc(battle);
  6747. if (result.result.win) {
  6748. const info = await this.endBattle(result);
  6749. if (info.results[0].result.response?.error) {
  6750. this.terminatеReason = I18N('BATTLE_END_ERROR');
  6751. return false;
  6752. }
  6753. } else {
  6754. await this.cancelBattle(result);
  6755.  
  6756. if (preCalc && await this.preCalcBattle(battle)) {
  6757. path = path.slice(-2);
  6758. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  6759. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  6760. const result = await this.battle(path, false);
  6761. if (result) {
  6762. setProgress(I18N('VICTORY'));
  6763. return true;
  6764. }
  6765. }
  6766. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  6767. return false;
  6768. }
  6769. return false;
  6770. }
  6771. } catch (error) {
  6772. console.error(error);
  6773. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  6774. { msg: 'Нет', result: false },
  6775. { msg: 'Да', result: true },
  6776. ])) {
  6777. this.errorHandling(error, data);
  6778. }
  6779. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  6780. return false;
  6781. }
  6782. return true;
  6783. }
  6784.  
  6785. /**
  6786. * Recalculate battles
  6787. *
  6788. * Прерасчтет битвы
  6789. */
  6790. async preCalcBattle(battle) {
  6791. const countTestBattle = getInput('countTestBattle');
  6792. for (let i = 0; i < countTestBattle; i++) {
  6793. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6794. const result = await Calc(battle);
  6795. if (result.result.win) {
  6796. console.log(i, countTestBattle);
  6797. return true;
  6798. }
  6799. }
  6800. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  6801. return false;
  6802. }
  6803.  
  6804. /**
  6805. * Starts a fight
  6806. *
  6807. * Начинает бой
  6808. */
  6809. startBattle(path) {
  6810. this.args.path = path;
  6811. this.callStartBattle.name = this.actions[this.type].startBattle;
  6812. this.callStartBattle.args = this.args
  6813. const calls = [this.callStartBattle];
  6814. return Send(JSON.stringify({ calls }));
  6815. }
  6816.  
  6817. cancelBattle(battle) {
  6818. const fixBattle = function (heroes) {
  6819. for (const ids in heroes) {
  6820. const hero = heroes[ids];
  6821. hero.energy = random(1, 999);
  6822. if (hero.hp > 0) {
  6823. hero.hp = random(1, hero.hp);
  6824. }
  6825. }
  6826. }
  6827. fixBattle(battle.progress[0].attackers.heroes);
  6828. fixBattle(battle.progress[0].defenders.heroes);
  6829. return this.endBattle(battle);
  6830. }
  6831.  
  6832. /**
  6833. * Ends the fight
  6834. *
  6835. * Заканчивает бой
  6836. */
  6837. endBattle(battle) {
  6838. this.callEndBattle.name = this.actions[this.type].endBattle;
  6839. this.callEndBattle.args.result = battle.result
  6840. this.callEndBattle.args.progress = battle.progress
  6841. const calls = [this.callEndBattle];
  6842. return Send(JSON.stringify({ calls }));
  6843. }
  6844.  
  6845. /**
  6846. * Checks if you can get a buff
  6847. *
  6848. * Проверяет можно ли получить баф
  6849. */
  6850. checkBuff(nodeInfo) {
  6851. let id = null;
  6852. let value = 0;
  6853. for (const buffId in nodeInfo.buffs) {
  6854. const buff = nodeInfo.buffs[buffId];
  6855. if (buff.owner == null && buff.value > value) {
  6856. id = buffId;
  6857. value = buff.value;
  6858. }
  6859. }
  6860. nodeInfo.buffs[id].owner = 'Я';
  6861. return id;
  6862. }
  6863.  
  6864. /**
  6865. * Collects a buff
  6866. *
  6867. * Собирает баф
  6868. */
  6869. async collectBuff(buff, path) {
  6870. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  6871. this.callCollectBuff.args = { buff, path };
  6872. const calls = [this.callCollectBuff];
  6873. return Send(JSON.stringify({ calls }));
  6874. }
  6875.  
  6876. getNodeInfo(nodeId) {
  6877. return this.nodes.find(node => node.id == nodeId);
  6878. }
  6879.  
  6880. errorHandling(error, data) {
  6881. //console.error(error);
  6882. let errorInfo = error.toString() + '\n';
  6883. try {
  6884. const errorStack = error.stack.split('\n');
  6885. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  6886. errorInfo += errorStack.slice(0, endStack).join('\n');
  6887. } catch (e) {
  6888. errorInfo += error.stack;
  6889. }
  6890. if (data) {
  6891. errorInfo += '\nData: ' + JSON.stringify(data);
  6892. }
  6893. copyText(errorInfo);
  6894. }
  6895.  
  6896. end() {
  6897. isCancalBattle = true;
  6898. setProgress(this.terminatеReason, true);
  6899. console.log(this.terminatеReason);
  6900. this.resolve();
  6901. }
  6902. }
  6903. })();
  6904.  
  6905. /**
  6906. * TODO:
  6907. * Получение всех уровней при сборе всех наград (квест на титанит и на энку)
  6908. * Добивание на арене титанов
  6909. */