HeroWarsDungeon

Automation of actions for the game Hero Wars

当前为 2024-05-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsDungeon
  3. // @name:en HeroWarsDungeon
  4. // @name:ru HeroWarsDungeon
  5. // @namespace HeroWarsDungeon
  6. // @version 2.231.1
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY, ApuoH, Gudwin
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/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://apps-1701433570146040.apps.fbsbx.com/*
  17. // @include https://*.nextersglobal.com/*
  18. // @include https://*.hero-wars*.com/*
  19. // @match https://www.solfors.com/
  20. // @match https://t.me/s/hw_ru
  21. // @run-at document-start
  22. // ==/UserScript==
  23.  
  24. (function() {
  25. /**
  26. * Start script
  27. *
  28. * Стартуем скрипт
  29. */
  30. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  31. /**
  32. * Script info
  33. *
  34. * Информация о скрипте
  35. */
  36. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  37. ({name, version, author, homepage, lastModified, updateUrl, source}))
  38. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  39. /**
  40. * If we are on the gifts page, then we collect and send them to the server
  41. *
  42. * Если находимся на странице подарков, то собираем и отправляем их на сервер
  43. */
  44. if (['www.solfors.com', 't.me'].includes(location.host)) {
  45. setTimeout(sendCodes, 2000);
  46. return;
  47. }
  48. /**
  49. * Information for completing daily quests
  50. *
  51. * Информация для выполнения ежендевных квестов
  52. */
  53. const questsInfo = {};
  54. /**
  55. * Is the game data loaded
  56. *
  57. * Загружены ли данные игры
  58. */
  59. let isLoadGame = false;
  60. /**
  61. * Headers of the last request
  62. *
  63. * Заголовки последнего запроса
  64. */
  65. let lastHeaders = {};
  66. /**
  67. * Information about sent gifts
  68. *
  69. * Информация об отправленных подарках
  70. */
  71. let freebieCheckInfo = null;
  72. /**
  73. * missionTimer
  74. *
  75. * missionTimer
  76. */
  77. let missionBattle = null;
  78. /** Пачки для тестов в чате*/ //тест сохранка
  79. let repleyBattle = {
  80. defenders: {},
  81. attackers: {},
  82. effects: {},
  83. state: {},
  84. seed: undefined
  85. }
  86. /**
  87. * User data
  88. *
  89. * Данные пользователя
  90. */
  91. let userInfo;
  92. /**
  93. * Original methods for working with AJAX
  94. *
  95. * Оригинальные методы для работы с AJAX
  96. */
  97. const original = {
  98. open: XMLHttpRequest.prototype.open,
  99. send: XMLHttpRequest.prototype.send,
  100. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  101. SendWebSocket: WebSocket.prototype.send,
  102. };
  103. /**
  104. * Decoder for converting byte data to JSON string
  105. *
  106. * Декодер для перобразования байтовых данных в JSON строку
  107. */
  108. const decoder = new TextDecoder("utf-8");
  109. /**
  110. * Stores a history of requests
  111. *
  112. * Хранит историю запросов
  113. */
  114. let requestHistory = {};
  115. /**
  116. * URL for API requests
  117. *
  118. * URL для запросов к API
  119. */
  120. let apiUrl = '';
  121.  
  122. /**
  123. * Connecting to the game code
  124. *
  125. * Подключение к коду игры
  126. */
  127. this.cheats = new hackGame();
  128. /**
  129. * The function of calculating the results of the battle
  130. *
  131. * Функция расчета результатов боя
  132. */
  133. this.BattleCalc = cheats.BattleCalc;
  134. /**
  135. * Sending a request available through the console
  136. *
  137. * Отправка запроса доступная через консоль
  138. */
  139. this.SendRequest = send;
  140. /**
  141. * Simple combat calculation available through the console
  142. *
  143. * Простой расчет боя доступный через консоль
  144. */
  145. this.Calc = function (data) {
  146. const type = getBattleType(data?.type);
  147. return new Promise((resolve, reject) => {
  148. try {
  149. BattleCalc(data, type, resolve);
  150. } catch (e) {
  151. reject(e);
  152. }
  153. })
  154. }
  155. //тест остановка подземки
  156. let stopDung = false;
  157. /**
  158. * Short asynchronous request
  159. * Usage example (returns information about a character):
  160. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  161. *
  162. * Короткий асинхронный запрос
  163. * Пример использования (возвращает информацию о персонаже):
  164. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  165. */
  166. this.Send = function (json, pr) {
  167. return new Promise((resolve, reject) => {
  168. try {
  169. send(json, resolve, pr);
  170. } catch (e) {
  171. reject(e);
  172. }
  173. })
  174. }
  175.  
  176. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  177. const i18nLangData = {
  178. /* English translation by BaBa */
  179. en: {
  180. /* Checkboxes */
  181. SKIP_FIGHTS: 'Skip battle',
  182. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  183. ENDLESS_CARDS: 'Infinite cards',
  184. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  185. AUTO_EXPEDITION: 'Auto Expedition',
  186. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  187. CANCEL_FIGHT: 'Cancel battle',
  188. CANCEL_FIGHT_TITLE: 'The possibility of canceling the battle on VG',
  189. GIFTS: 'Gifts',
  190. GIFTS_TITLE: 'Collect gifts automatically',
  191. BATTLE_RECALCULATION: 'Battle recalculation',
  192. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  193. BATTLE_FISHING: 'Finishing',
  194. BATTLE_FISHING_TITLE: 'Finishing off the team from the last replay in the chat',
  195. BATTLE_TRENING: 'Workout',
  196. BATTLE_TRENING_TITLE: 'A training battle in the chat against the team from the last replay',
  197. QUANTITY_CONTROL: 'Quantity control',
  198. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  199. REPEAT_CAMPAIGN: 'Repeat missions',
  200. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  201. DISABLE_DONAT: 'Disable donation',
  202. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  203. DAILY_QUESTS: 'Quests',
  204. DAILY_QUESTS_TITLE: 'Complete daily quests',
  205. AUTO_QUIZ: 'AutoQuiz',
  206. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  207. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  208. HIDE_SERVERS: 'Collapse servers',
  209. HIDE_SERVERS_TITLE: 'Hide unused servers',
  210. /* Input fields */
  211. HOW_MUCH_TITANITE: 'How much titanite to farm',
  212. COMBAT_SPEED: 'Combat Speed Multiplier',
  213. HOW_REPEAT_CAMPAIGN: 'how many mission replays', //тест добавил
  214. NUMBER_OF_TEST: 'Number of test fights',
  215. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  216. USER_ID_TITLE: 'Enter the player ID',
  217. AMOUNT: 'Gift number, 1 - hero development, 2 - pets, 3 - light, 4 - darkness, 5 - ascension, 6 - appearance',
  218. GIFT_NUM: 'Number of gifts to be sent',
  219. /* Buttons */
  220. RUN_SCRIPT: 'Run the',
  221. STOP_SCRIPT: 'Stop the',
  222. TO_DO_EVERYTHING: 'Do All',
  223. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  224. OUTLAND: 'Outland',
  225. OUTLAND_TITLE: 'Collect Outland',
  226. TITAN_ARENA: 'ToE',
  227. TITAN_ARENA_TITLE: 'Complete the titan arena',
  228. DUNGEON: 'Dungeon',
  229. DUNGEON_TITLE: 'Go through the dungeon',
  230. DUNGEON2: 'Dungeon full',
  231. DUNGEON_FULL_TITLE: 'Dungeon for Full Titans',
  232. STOP_DUNGEON: 'Stop Dungeon',
  233. STOP_DUNGEON_TITLE: 'Stop digging the dungeon',
  234. SEER: 'Seer',
  235. SEER_TITLE: 'Roll the Seer',
  236. TOWER: 'Tower',
  237. TOWER_TITLE: 'Pass the tower',
  238. EXPEDITIONS: 'Expeditions',
  239. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  240. SYNC: 'Sync',
  241. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  242. ARCHDEMON: 'Archdemon',
  243. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  244. CRUCIBLE_SOULS: 'Crucible',
  245. CRUCIBLE_SOULS_TITLE: 'Fill the kilos in the crucible of souls',
  246. ESTER_EGGS: 'Easter eggs',
  247. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  248. REWARDS: 'Rewards',
  249. REWARDS_TITLE: 'Collect all quest rewards',
  250. MAIL: 'Mail',
  251. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  252. MINIONS: 'Minions',
  253. MINIONS_TITLE: 'Attack minions with saved packs',
  254. ADVENTURE: 'Adventure',
  255. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  256. STORM: 'Storm',
  257. STORM_TITLE: 'Passes the Storm along the specified route',
  258. SANCTUARY: 'Sanctuary',
  259. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  260. GUILD_WAR: 'Guild War',
  261. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  262. SECRET_WEALTH: 'Secret Wealth',
  263. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  264. /* Misc */
  265. BOTTOM_URLS: '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a>',
  266. GIFTS_SENT: 'Gifts sent!',
  267. DO_YOU_WANT: "Do you really want to do this?",
  268. BTN_RUN: 'Run',
  269. BTN_CANCEL: 'Cancel',
  270. BTN_OK: 'OK',
  271. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  272. BTN_AUTO: 'Auto',
  273. MSG_YOU_APPLIED: 'You applied',
  274. MSG_DAMAGE: 'damage',
  275. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  276. MSG_REPEAT_MISSION: 'Repeat the mission?',
  277. BTN_REPEAT: 'Repeat',
  278. BTN_NO: 'No',
  279. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  280. BTN_OPEN: 'Open',
  281. QUESTION_COPY: 'Question copied to clipboard',
  282. ANSWER_KNOWN: 'The answer is known',
  283. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  284. BEING_RECALC: 'The battle is being recalculated',
  285. THIS_TIME: 'This time',
  286. VICTORY: '<span style="color:green;">VICTORY</span>',
  287. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  288. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  289. OPEN_DOLLS: 'nesting dolls recursively',
  290. SENT_QUESTION: 'Question sent',
  291. SETTINGS: 'Settings',
  292. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  293. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  294. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  295. VALUES: 'Values',
  296. SAVING: 'Saving',
  297. USER_ID: 'User Id',
  298. SEND_GIFT: 'The gift has been sent',
  299. EXPEDITIONS_SENT: 'Expeditions sent',
  300. TITANIT: 'Titanit',
  301. COMPLETED: 'completed',
  302. FLOOR: 'Floor',
  303. LEVEL: 'Level',
  304. BATTLES: 'battles',
  305. EVENT: 'Event',
  306. NOT_AVAILABLE: 'not available',
  307. NO_HEROES: 'No heroes',
  308. DAMAGE_AMOUNT: 'Damage amount',
  309. NOTHING_TO_COLLECT: 'Nothing to collect',
  310. COLLECTED: 'Collected',
  311. REWARD: 'rewards',
  312. REMAINING_ATTEMPTS: 'Remaining attempts',
  313. BATTLES_CANCELED: 'Battles canceled',
  314. MINION_RAID: 'Minion Raid',
  315. STOPPED: 'Stopped',
  316. REPETITIONS: 'Repetitions',
  317. MISSIONS_PASSED: 'Missions passed',
  318. STOP: 'stop',
  319. TOTAL_OPEN: 'Total open',
  320. OPEN: 'Open',
  321. ROUND_STAT: 'Damage statistics for ',
  322. BATTLE: 'battles',
  323. MINIMUM: 'Minimum',
  324. MAXIMUM: 'Maximum',
  325. AVERAGE: 'Average',
  326. NOT_THIS_TIME: 'Not this time',
  327. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  328. SUCCESS: 'Success',
  329. RECEIVED: 'Received',
  330. LETTERS: 'letters',
  331. PORTALS: 'portals',
  332. ATTEMPTS: 'attempts',
  333. /* Quests */
  334. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  335. QUEST_10002: 'Complete 10 missions',
  336. QUEST_10003: 'Complete 3 heroic missions',
  337. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  338. QUEST_10006: 'Use the exchange of emeralds 1 time',
  339. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  340. QUEST_10016: 'Send gifts to guildmates',
  341. QUEST_10018: 'Use an experience potion',
  342. QUEST_10019: 'Open 1 chest in the Tower',
  343. QUEST_10020: 'Open 3 chests in Outland',
  344. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  345. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  346. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  347. QUEST_10024: 'Level up any artifact once',
  348. QUEST_10025: 'Start Expedition 1',
  349. QUEST_10026: 'Start 4 Expeditions',
  350. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  351. QUEST_10028: 'Level up any titan artifact',
  352. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  353. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  354. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  355. QUEST_10043: 'Start or Join an Adventure',
  356. QUEST_10044: 'Use Summon Pets 1 time',
  357. QUEST_10046: 'Open 3 chests in Adventure',
  358. QUEST_10047: 'Get 150 Guild Activity Points',
  359. NOTHING_TO_DO: 'Nothing to do',
  360. YOU_CAN_COMPLETE: 'You can complete quests',
  361. BTN_DO_IT: 'Do it',
  362. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  363. COMPLETED_QUESTS: 'Completed quests',
  364. /* everything button */
  365. ASSEMBLE_OUTLAND: 'Assemble Outland',
  366. PASS_THE_TOWER: 'Pass the tower',
  367. CHECK_EXPEDITIONS: 'Check Expeditions',
  368. COMPLETE_TOE: 'Complete ToE',
  369. COMPLETE_DUNGEON: 'Complete the dungeon',
  370. COMPLETE_DUNGEON_FULL: 'Complete the dungeon for Full Titans',
  371. COLLECT_MAIL: 'Collect mail',
  372. COLLECT_MISC: 'Collect some bullshit',
  373. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  374. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  375. MAKE_A_SYNC: 'Make a sync',
  376.  
  377. RUN_FUNCTION: 'Run the following functions?',
  378. BTN_GO: 'Go!',
  379. PERFORMED: 'Performed',
  380. DONE: 'Done',
  381. ERRORS_OCCURRES: 'Errors occurred while executing',
  382. COPY_ERROR: 'Copy error information to clipboard',
  383. BTN_YES: 'Yes',
  384. ALL_TASK_COMPLETED: 'All tasks completed',
  385.  
  386. UNKNOWN: 'unknown',
  387. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  388. START_ADVENTURE: 'Start your adventure along this path!',
  389. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  390. BTN_CANCELED: 'Canceled',
  391. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  392. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  393. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  394. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  395. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  396. YES_CONTINUE: 'Yes, continue!',
  397. NOT_ENOUGH_AP: 'Not enough action points',
  398. ATTEMPTS_ARE_OVER: 'The attempts are over',
  399. MOVES: 'Moves',
  400. BUFF_GET_ERROR: 'Buff getting error',
  401. BATTLE_END_ERROR: 'Battle end error',
  402. AUTOBOT: 'Autobot',
  403. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  404. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  405. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  406. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  407. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  408. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  409. FIND_COEFF: 'Find the coefficient greater than',
  410. BTN_PASS: 'PASS',
  411. BRAWLS: 'Brawls',
  412. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  413. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  414. LOSSES: 'Losses',
  415. WINS: 'Wins',
  416. FIGHTS: 'Fights',
  417. STAGE: 'Stage',
  418. DONT_HAVE_LIVES: 'You don\'t have lives',
  419. LIVES: 'Lives',
  420. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  421. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  422. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  423. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  424. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  425. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  426. DAILY_BONUS: 'Daily bonus',
  427. DO_DAILY_QUESTS: 'Do daily quests',
  428. ACTIONS: 'Actions',
  429. ACTIONS_TITLE: 'Dialog box with various actions',
  430. OTHERS: 'Others',
  431. OTHERS_TITLE: 'Others',
  432. CHOOSE_ACTION: 'Choose an action',
  433. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  434. STAMINA: 'Energy',
  435. BOXES_OVER: 'The boxes are over',
  436. NO_BOXES: 'No boxes',
  437. NO_MORE_ACTIVITY: 'No more activity for items today',
  438. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  439. GET_ACTIVITY: 'Get Activity',
  440. NOT_ENOUGH_ITEMS: 'Not enough items',
  441. ACTIVITY_RECEIVED: 'Activity received',
  442. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  443. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  444. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  445. CHESTS_NOT_AVAILABLE: 'Chests not available',
  446. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  447. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  448. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  449. SOMETHING_WENT_WRONG: 'Something went wrong',
  450. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  451. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  452. GET_ENERGY: 'Get Energy',
  453. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  454. ITEM_EXCHANGE: 'Item Exchange',
  455. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  456. BUY_SOULS: 'Buy souls',
  457. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  458. BUY_OUTLAND: 'Buy Outland',
  459. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  460. RAID: 'Raid',
  461. AUTO_RAID_ADVENTURE: 'Raid adventure',
  462. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  463. CLAN_STAT: 'Clan statistics',
  464. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  465. BTN_AUTO_F5: 'Auto (F5)',
  466. BOSS_DAMAGE: 'Boss Damage: ',
  467. NOTHING_BUY: 'Nothing to buy',
  468. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  469. BUY_FOR_GOLD: 'Buy for gold',
  470. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  471. REWARDS_AND_MAIL: 'Rewars and Mail',
  472. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  473. New_Year_Clan: 'a gift for a friend',
  474. New_Year_Clan_TITLE: 'New Year gifts to friends',
  475. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  476. TIMER_ALREADY: 'Timer already started {time}',
  477. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  478. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  479. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  480. EPIC_BRAWL: 'Cosmic Battle',
  481. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  482. RELOAD_GAME: 'Reload game',
  483. TIMER: 'Timer:',
  484. SHOW_ERRORS: 'Show errors',
  485. SHOW_ERRORS_TITLE: 'Show server request errors',
  486. ERROR_MSG: 'Error: {name}<br>{description}',
  487. EVENT_AUTO_BOSS: 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  488. BEST_SLOW: 'Best (slower)',
  489. FIRST_FAST: 'First (faster)',
  490. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  491. ERROR_F12: 'Error, details in the console (F12)',
  492. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  493. BEST_PACK: 'Best pack:',
  494. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  495. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  496. BOSS_VICTORY_IMPOSSIBLE: 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles? <p style="color:red;">Using this feature may be considered as DDoS attack or HTTP flooding and result in permanent ban</p>',
  497. BOSS_HAS_BEEN_DEF_TEXT: 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  498. MAP: 'Map: ',
  499. PLAYER_POS: 'Player positions:',
  500. NY_GIFTS: 'Gifts',
  501. NY_GIFTS_TITLE: 'Open all New Year\'s gifts',
  502. NY_NO_GIFTS: 'No gifts not received',
  503. NY_GIFTS_COLLECTED: '{count} gifts collected',
  504. CHANGE_MAP: 'Island map',
  505. CHANGE_MAP_TITLE: 'Change island map',
  506. SELECT_ISLAND_MAP: 'Select an island map:',
  507. FIRST_MAP: 'First map',
  508. SECOND_MAP: 'Second map',
  509. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  510. SHOPS: 'Shops',
  511. SHOPS_DEFAULT: 'Default',
  512. SHOPS_DEFAULT_TITLE: 'Default stores',
  513. SHOPS_LIST: 'Shops {number}',
  514. SHOPS_LIST_TITLE: 'List of shops {number}',
  515. SHOPS_WARNING: 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  516. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  517. FAST_SEASON: 'Fast season',
  518. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  519. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  520. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  521. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  522. IMPROVED_LEVELS: 'Improved levels: {count}',
  523. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  524. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  525. SKINS_UPGRADE: 'Skins Upgrade',
  526. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  527. HINT: '<br>Hint: ',
  528. PICTURE: '<br>Picture: ',
  529. ANSWER: '<br>Answer: ',
  530. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  531. },
  532. ru: {
  533. /* Чекбоксы */
  534. SKIP_FIGHTS: 'Пропуск боев',
  535. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  536. ENDLESS_CARDS: 'Бесконечные карты',
  537. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  538. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  539. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  540. CANCEL_FIGHT: 'Отмена боя',
  541. CANCEL_FIGHT_TITLE: 'Возможность отмены боя на ВГ, СМ и в Асгарде',
  542. GIFTS: 'Подарки',
  543. GIFTS_TITLE: 'Собирать подарки автоматически',
  544. BATTLE_RECALCULATION: 'Прерасчет боя',
  545. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  546. BATTLE_FISHING: 'Добивание',
  547. BATTLE_FISHING_TITLE: 'Добивание в чате команды из последнего реплея',
  548. BATTLE_TRENING: 'Тренировка',
  549. BATTLE_TRENING_TITLE: 'Тренировочный бой в чате против команды из последнего реплея',
  550. QUANTITY_CONTROL: 'Контроль кол-ва',
  551. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  552. REPEAT_CAMPAIGN: 'Повтор в компании',
  553. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  554. DISABLE_DONAT: 'Отключить донат',
  555. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  556. DAILY_QUESTS: 'Квесты',
  557. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  558. AUTO_QUIZ: 'АвтоВикторина',
  559. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  560. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  561. HIDE_SERVERS: 'Свернуть сервера',
  562. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  563. /* Поля ввода */
  564. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  565. COMBAT_SPEED: 'Множитель ускорения боя',
  566. HOW_REPEAT_CAMPAIGN: 'Сколько повторов миссий', //тест добавил
  567. NUMBER_OF_TEST: 'Количество тестовых боев',
  568. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  569. USER_ID_TITLE: 'Введите айди игрока',
  570. AMOUNT: 'Количество отправляемых подарков',
  571. GIFT_NUM: 'Номер подарка, 1 - развитие героев, 2 - питомцы, 3 - света, 4 - тьмы, 5 - вознесения, 6 - облик',
  572. /* Кнопки */
  573. RUN_SCRIPT: 'Запустить скрипт',
  574. STOP_SCRIPT: 'Остановить скрипт',
  575. TO_DO_EVERYTHING: 'Сделать все',
  576. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  577. OUTLAND: 'Запределье',
  578. OUTLAND_TITLE: 'Собрать Запределье',
  579. TITAN_ARENA: 'Турнир Стихий',
  580. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  581. DUNGEON: 'Подземелье',
  582. DUNGEON_TITLE: 'Автопрохождение подземелья',
  583. DUNGEON2: 'Подземелье фулл',
  584. DUNGEON_FULL_TITLE: 'Подземелье для фуловых титанов',
  585. STOP_DUNGEON: 'Стоп подземка',
  586. STOP_DUNGEON_TITLE: 'Остановить копание подземелья',
  587. SEER: 'Провидец',
  588. SEER_TITLE: 'Покрутить Провидца',
  589. TOWER: 'Башня',
  590. TOWER_TITLE: 'Автопрохождение башни',
  591. EXPEDITIONS: 'Экспедиции',
  592. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  593. SYNC: 'Синхронизация',
  594. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  595. ARCHDEMON: 'Архидемон',
  596. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  597. CRUCIBLE_SOULS: 'Горнило душ',
  598. CRUCIBLE_SOULS_TITLE:'Набить килов в горниле душ',
  599. ESTER_EGGS: 'Пасхалки',
  600. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  601. REWARDS: 'Награды',
  602. REWARDS_TITLE: 'Собрать все награды за задания',
  603. MAIL: 'Почта',
  604. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  605. MINIONS: 'Прислужники',
  606. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  607. ADVENTURE: 'Приключение',
  608. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  609. STORM: 'Буря',
  610. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  611. SANCTUARY: 'Святилище',
  612. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  613. GUILD_WAR: 'Война гильдий',
  614. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  615. SECRET_WEALTH: 'Тайное богатство',
  616. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  617. /* Разное */
  618. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 1000 1000" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="50%" y1="0%" x2="50%" y2="99.2583404%" id="linearGradient-1"><stop stop-color="#2AABEE" offset="0%"></stop><stop stop-color="#229ED9" offset="100%"></stop></linearGradient></defs><g id="Artboard" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><circle id="Oval" fill="url(#linearGradient-1)" cx="500" cy="500" r="500"></circle><path d="M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z" id="Path-3" fill="#FFFFFF"></path></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg style="margin: 2px;" width="20" height="20" viewBox="0 0 101 100" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0_2_40)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#0077FF"/><path d="M53.7085 72.042C30.9168 72.042 17.9169 56.417 17.3752 30.417H28.7919C29.1669 49.5003 37.5834 57.5836 44.25 59.2503V30.417H55.0004V46.8752C61.5837 46.1669 68.4995 38.667 70.8329 30.417H81.5832C79.7915 40.5837 72.2915 48.0836 66.9582 51.1669C72.2915 53.6669 80.8336 60.2086 84.0836 72.042H72.2499C69.7082 64.1253 63.3754 58.0003 55.0004 57.1669V72.042H53.7085Z" fill="white"/></g><defs><clipPath id="clip0_2_40"><rect width="100" height="100" fill="white" transform="translate(0.5)"/></clipPath></defs></svg></a>',
  619. GIFTS_SENT: 'Подарки отправлены!',
  620. DO_YOU_WANT: "Вы действительно хотите это сделать?",
  621. BTN_RUN: 'Запускай',
  622. BTN_CANCEL: 'Отмена',
  623. BTN_OK: 'Ок',
  624. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  625. BTN_AUTO: 'Авто',
  626. MSG_YOU_APPLIED: 'Вы нанесли',
  627. MSG_DAMAGE: 'урона',
  628. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  629. MSG_REPEAT_MISSION: 'Повторить миссию?',
  630. BTN_REPEAT: 'Повторить',
  631. BTN_NO: 'Нет',
  632. MSG_SPECIFY_QUANT: 'Указать количество:',
  633. BTN_OPEN: 'Открыть',
  634. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  635. ANSWER_KNOWN: 'Ответ известен',
  636. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  637. BEING_RECALC: 'Идет прерасчет боя',
  638. THIS_TIME: 'На этот раз',
  639. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  640. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  641. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  642. OPEN_DOLLS: 'матрешек рекурсивно',
  643. SENT_QUESTION: 'Вопрос отправлен',
  644. SETTINGS: 'Настройки',
  645. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  646. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  647. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  648. VALUES: 'Значения',
  649. SAVING: 'Сохранка',
  650. USER_ID: 'айди пользователя',
  651. SEND_GIFT: 'Подарок отправлен',
  652. EXPEDITIONS_SENT: 'Экспедиции отправлены',
  653. TITANIT: 'Титанит',
  654. COMPLETED: 'завершено',
  655. FLOOR: 'Этаж',
  656. LEVEL: 'Уровень',
  657. BATTLES: 'бои',
  658. EVENT: 'Эвент',
  659. NOT_AVAILABLE: 'недоступен',
  660. NO_HEROES: 'Нет героев',
  661. DAMAGE_AMOUNT: 'Количество урона',
  662. NOTHING_TO_COLLECT: 'Нечего собирать',
  663. COLLECTED: 'Собрано',
  664. REWARD: 'наград',
  665. REMAINING_ATTEMPTS: 'Осталось попыток',
  666. BATTLES_CANCELED: 'Битв отменено',
  667. MINION_RAID: 'Рейд прислужников',
  668. STOPPED: 'Остановлено',
  669. REPETITIONS: 'Повторений',
  670. MISSIONS_PASSED: 'Миссий пройдено',
  671. STOP: 'остановить',
  672. TOTAL_OPEN: 'Всего открыто',
  673. OPEN: 'Открыто',
  674. ROUND_STAT: 'Статистика урона за',
  675. BATTLE: 'боев',
  676. MINIMUM: 'Минимальный',
  677. MAXIMUM: 'Максимальный',
  678. AVERAGE: 'Средний',
  679. NOT_THIS_TIME: 'Не в этот раз',
  680. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  681. SUCCESS: 'Успех',
  682. RECEIVED: 'Получено',
  683. LETTERS: 'писем',
  684. PORTALS: 'порталов',
  685. ATTEMPTS: 'попыток',
  686. QUEST_10001: 'Улучши умения героев 3 раза',
  687. QUEST_10002: 'Пройди 10 миссий',
  688. QUEST_10003: 'Пройди 3 героические миссии',
  689. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  690. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  691. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  692. QUEST_10016: 'Отправь подарки согильдийцам',
  693. QUEST_10018: 'Используй зелье опыта',
  694. QUEST_10019: 'Открой 1 сундук в Башне',
  695. QUEST_10020: 'Открой 3 сундука в Запределье',
  696. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  697. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  698. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  699. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  700. QUEST_10025: 'Начни 1 Экспедицию',
  701. QUEST_10026: 'Начни 4 Экспедиции',
  702. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  703. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  704. QUEST_10029: 'Открой сферу артефактов титанов',
  705. QUEST_10030: 'Улучши облик любого героя 1 раз',
  706. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  707. QUEST_10043: 'Начни или присоеденись к Приключению',
  708. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  709. QUEST_10046: 'Открой 3 сундука в Приключениях',
  710. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  711. NOTHING_TO_DO: 'Нечего выполнять',
  712. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  713. BTN_DO_IT: 'Выполняй',
  714. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  715. COMPLETED_QUESTS: 'Выполнено квестов',
  716. /* everything button */
  717. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  718. PASS_THE_TOWER: 'Пройти башню',
  719. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  720. COMPLETE_TOE: 'Пройти Турнир Стихий',
  721. COMPLETE_DUNGEON: 'Пройти подземелье',
  722. COMPLETE_DUNGEON_FULL: 'Пройти подземелье фулл',
  723. COLLECT_MAIL: 'Собрать почту',
  724. COLLECT_MISC: 'Собрать всякую херню',
  725. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  726. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  727. MAKE_A_SYNC: 'Сделать синхронизацю',
  728.  
  729. RUN_FUNCTION: 'Выполнить следующие функции?',
  730. BTN_GO: 'Погнали!',
  731. PERFORMED: 'Выполняется',
  732. DONE: 'Выполнено',
  733. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  734. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  735. BTN_YES: 'Да',
  736. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  737.  
  738. UNKNOWN: 'Неизвестно',
  739. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  740. START_ADVENTURE: 'Начать приключение по этому пути!',
  741. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  742. BTN_CANCELED: 'Отменено',
  743. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  744. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  745. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  746. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  747. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  748. YES_CONTINUE: 'Да, продолжай!',
  749. NOT_ENOUGH_AP: 'Попыток не достаточно',
  750. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  751. MOVES: 'Ходы',
  752. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  753. BATTLE_END_ERROR: 'Ошибка завершения боя',
  754. AUTOBOT: 'АвтоБой',
  755. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  756. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  757. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  758. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  759. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  760. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  761. FIND_COEFF: 'Поиск коэффициента больше чем',
  762. BTN_PASS: 'ПРОПУСК',
  763. BRAWLS: 'Потасовки',
  764. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  765. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  766. LOSSES: 'Поражений',
  767. WINS: 'Побед',
  768. FIGHTS: 'Боев',
  769. STAGE: 'Стадия',
  770. DONT_HAVE_LIVES: 'У Вас нет жизней',
  771. LIVES: 'Жизни',
  772. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  773. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  774. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  775. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  776. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  777. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  778. DAILY_BONUS: 'Ежедневная награда',
  779. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  780. ACTIONS: 'Действия',
  781. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  782. OTHERS: 'Разное',
  783. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  784. CHOOSE_ACTION: 'Выберите действие',
  785. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  786. STAMINA: 'Энергия',
  787. BOXES_OVER: 'Ящики закончились',
  788. NO_BOXES: 'Нет ящиков',
  789. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  790. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  791. GET_ACTIVITY: 'Получить активность',
  792. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  793. ACTIVITY_RECEIVED: 'Получено активности',
  794. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  795. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  796. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  797. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  798. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  799. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  800. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  801. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  802. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  803. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  804. GET_ENERGY: 'Получить энергию',
  805. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  806. ITEM_EXCHANGE: 'Обмен предметов',
  807. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  808. BUY_SOULS: 'Купить души',
  809. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  810. BUY_OUTLAND: 'Купить Запределье',
  811. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  812. RAID: 'Рейд',
  813. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  814. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  815. CLAN_STAT: 'Клановая статистика',
  816. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  817. BTN_AUTO_F5: 'Авто (F5)',
  818. BOSS_DAMAGE: 'Урон по боссу: ',
  819. NOTHING_BUY: 'Нечего покупать',
  820. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  821. BUY_FOR_GOLD: 'Скупить за золото',
  822. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  823. REWARDS_AND_MAIL: 'Награды и почта',
  824. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  825. New_Year_Clan: 'подарок другу',
  826. New_Year_Clan_TITLE: 'Новогодние подарки друзьям',
  827. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  828. TIMER_ALREADY: 'Таймер уже запущен {time}',
  829. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  830. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  831. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  832. EPIC_BRAWL: 'Вселенская битва',
  833. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  834. RELOAD_GAME: 'Перезагрузить игру',
  835. TIMER: 'Таймер:',
  836. SHOW_ERRORS: 'Отображать ошибки',
  837. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  838. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  839. EVENT_AUTO_BOSS: 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  840. BEST_SLOW: 'Лучший (медленее)',
  841. FIRST_FAST: 'Первый (быстрее)',
  842. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  843. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  844. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  845. BEST_PACK: 'Наилучший пак: ',
  846. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  847. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  848. BOSS_VICTORY_IMPOSSIBLE: 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях? <p style="color:red;">Использование этой функции может быть расценено как DDoS атака или HTTP-флуд и привести к перманентному бану</p>',
  849. BOSS_HAS_BEEN_DEF_TEXT: 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  850. MAP: 'Карта: ',
  851. PLAYER_POS: 'Позиции игроков:',
  852. NY_GIFTS: 'Подарки',
  853. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  854. NY_NO_GIFTS: 'Нет не полученных подарков',
  855. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  856. CHANGE_MAP: 'Карта острова',
  857. CHANGE_MAP_TITLE: 'Сменить карту острова',
  858. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  859. FIRST_MAP: 'Первая карта',
  860. SECOND_MAP: 'Вторая карта',
  861. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  862. SHOPS: 'Магазины',
  863. SHOPS_DEFAULT: 'Стандартные',
  864. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  865. SHOPS_LIST: 'Магазины {number}',
  866. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  867. SHOPS_WARNING: 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  868. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  869. FAST_SEASON: 'Быстрый сезон',
  870. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  871. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  872. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  873. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  874. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  875. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  876. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  877. SKINS_UPGRADE: 'Улучшение обликов',
  878. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  879. HINT: '<br>Подсказка: ',
  880. PICTURE: '<br>На картинке: ',
  881. ANSWER: '<br>Ответ: ',
  882. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  883. }
  884. }
  885.  
  886. function getLang() {
  887. let lang = '';
  888. if (typeof NXFlashVars !== 'undefined') {
  889. lang = NXFlashVars.interface_lang
  890. }
  891. if (!lang) {
  892. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  893. }
  894. if (lang == 'ru') {
  895. return lang;
  896. }
  897. return 'en';
  898. }
  899.  
  900. this.I18N = function (constant, replace) {
  901. const selectLang = getLang();
  902. if (constant && constant in i18nLangData[selectLang]) {
  903. const result = i18nLangData[selectLang][constant];
  904. if (replace) {
  905. return result.sprintf(replace);
  906. }
  907. return result;
  908. }
  909. return `% ${constant} %`;
  910. };
  911.  
  912. String.prototype.sprintf = String.prototype.sprintf ||
  913. function () {
  914. "use strict";
  915. var str = this.toString();
  916. if (arguments.length) {
  917. var t = typeof arguments[0];
  918. var key;
  919. var args = ("string" === t || "number" === t) ?
  920. Array.prototype.slice.call(arguments)
  921. : arguments[0];
  922.  
  923. for (key in args) {
  924. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  925. }
  926. }
  927.  
  928. return str;
  929. };
  930.  
  931. /**
  932. * Checkboxes
  933. *
  934. * Чекбоксы
  935. */
  936. const checkboxes = {
  937. passBattle: {
  938. label: I18N('SKIP_FIGHTS'),
  939. cbox: null,
  940. title: I18N('SKIP_FIGHTS_TITLE'),
  941. default: false
  942. },
  943. /*endlessCards: {
  944. label: I18N('ENDLESS_CARDS'),
  945. cbox: null,
  946. title: I18N('ENDLESS_CARDS_TITLE'),
  947. default: true
  948. },*/
  949. /*sendExpedition: {
  950. label: I18N('AUTO_EXPEDITION'),
  951. cbox: null,
  952. title: I18N('AUTO_EXPEDITION_TITLE'),
  953. default: false
  954. },*/ //тест сдедал экспедиции на авто в сделать все
  955. cancelBattle: {
  956. label: I18N('CANCEL_FIGHT'),
  957. cbox: null,
  958. title: I18N('CANCEL_FIGHT_TITLE'),
  959. default: false,
  960. },
  961. preCalcBattle: {
  962. label: I18N('BATTLE_RECALCULATION'),
  963. cbox: null,
  964. title: I18N('BATTLE_RECALCULATION_TITLE'),
  965. default: false
  966. },
  967. finishingBattle: {
  968. label: I18N('BATTLE_FISHING'),
  969. cbox: null,
  970. title: I18N('BATTLE_FISHING_TITLE'),
  971. default: false
  972. },
  973. treningBattle: {
  974. label: I18N('BATTLE_TRENING'),
  975. cbox: null,
  976. title: I18N('BATTLE_TRENING_TITLE'),
  977. default: false
  978. },
  979. countControl: {
  980. label: I18N('QUANTITY_CONTROL'),
  981. cbox: null,
  982. title: I18N('QUANTITY_CONTROL_TITLE'),
  983. default: true
  984. },
  985. isRepeatMission: {
  986. label: I18N('REPEAT_CAMPAIGN'),
  987. cbox: null,
  988. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  989. default: false
  990. },
  991. noOfferDonat: {
  992. label: I18N('DISABLE_DONAT'),
  993. cbox: null,
  994. title: I18N('DISABLE_DONAT_TITLE'),
  995. /**
  996. * A crutch to get the field before getting the character id
  997. *
  998. * Костыль чтоб получать поле до получения id персонажа
  999. */
  1000. default: (() => {
  1001. $result = false;
  1002. try {
  1003. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  1004. } catch(e) {
  1005. $result = false;
  1006. }
  1007. return $result || false;
  1008. })(),
  1009. },
  1010. dailyQuests: {
  1011. label: I18N('DAILY_QUESTS'),
  1012. cbox: null,
  1013. title: I18N('DAILY_QUESTS_TITLE'),
  1014. default: false
  1015. },
  1016. // Потасовки
  1017. autoBrawls: {
  1018. label: I18N('BRAWLS'),
  1019. cbox: null,
  1020. title: I18N('BRAWLS_TITLE'),
  1021. default: (() => {
  1022. $result = false;
  1023. try {
  1024. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  1025. } catch (e) {
  1026. $result = false;
  1027. }
  1028. return $result || false;
  1029. })(),
  1030. hide: false,
  1031. },
  1032. getAnswer: {
  1033. label: I18N('AUTO_QUIZ'),
  1034. cbox: null,
  1035. title: I18N('AUTO_QUIZ_TITLE'),
  1036. default: false,
  1037. hide: true,
  1038. },
  1039. showErrors: {
  1040. label: I18N('SHOW_ERRORS'),
  1041. cbox: null,
  1042. title: I18N('SHOW_ERRORS_TITLE'),
  1043. default: true
  1044. },
  1045. buyForGold: {
  1046. label: I18N('BUY_FOR_GOLD'),
  1047. cbox: null,
  1048. title: I18N('BUY_FOR_GOLD_TITLE'),
  1049. default: false
  1050. },
  1051. hideServers: {
  1052. label: I18N('HIDE_SERVERS'),
  1053. cbox: null,
  1054. title: I18N('HIDE_SERVERS_TITLE'),
  1055. default: false
  1056. },
  1057. fastSeason: {
  1058. label: I18N('FAST_SEASON'),
  1059. cbox: null,
  1060. title: I18N('FAST_SEASON_TITLE'),
  1061. default: false
  1062. },
  1063. };
  1064. /**
  1065. * Get checkbox state
  1066. *
  1067. * Получить состояние чекбокса
  1068. */
  1069. function isChecked(checkBox) {
  1070. if (!(checkBox in checkboxes)) {
  1071. return false;
  1072. }
  1073. return checkboxes[checkBox].cbox?.checked;
  1074. }
  1075. /**
  1076. * Input fields
  1077. *
  1078. * Поля ввода
  1079. */
  1080. const inputs = {
  1081. countTitanit: {
  1082. input: null,
  1083. title: I18N('HOW_MUCH_TITANITE'),
  1084. default: 150,
  1085. },
  1086. speedBattle: {
  1087. input: null,
  1088. title: I18N('COMBAT_SPEED'),
  1089. default: 5,
  1090. },
  1091. //тест повтор компании
  1092. countRaid: {
  1093. input: null,
  1094. title: I18N('HOW_REPEAT_CAMPAIGN'),
  1095. default: 5,
  1096. },
  1097. countTestBattle: {
  1098. input: null,
  1099. title: I18N('NUMBER_OF_TEST'),
  1100. default: 10,
  1101. },
  1102. countAutoBattle: {
  1103. input: null,
  1104. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1105. default: 10,
  1106. },
  1107. FPS: {
  1108. input: null,
  1109. title: 'FPS',
  1110. default: 60,
  1111. }
  1112. }
  1113. //сохранка тест
  1114. const inputs2 = {
  1115. countBattle: {
  1116. input: null,
  1117. title: '-1 сохраняет защиту, -2 атаку противника с Replay',
  1118. default: 1,
  1119. },
  1120. needResource: {
  1121. input: null,
  1122. title: 'Мощь противника мин.(тыс.)/урона(млн.)',
  1123. default: 300,
  1124. },
  1125. needResource2: {
  1126. input: null,
  1127. title: 'Мощь противника макс./тип бафа',
  1128. default: 1500,
  1129. },
  1130. }
  1131. //новогодние подарки игрокам других гильдий
  1132. const inputs3 = {
  1133. userID: { // айди игрока посмотреть открыв его инфо
  1134. input: null,
  1135. title: I18N('USER_ID_TITLE'),
  1136. default: 111111,
  1137. },
  1138. GiftNum: { // номер подарка считаем слева направо от 1 до 6, под 1 это за 750 новогодних игрушек
  1139. input: null,
  1140. title: I18N('GIFT_NUM'),
  1141. default: 10,
  1142. },
  1143. AmontID: { // количество ресурсов от 1 до бесконечности
  1144. input: null,
  1145. title: I18N('AMOUNT'),
  1146. default: 1,
  1147. },
  1148. }
  1149. /**
  1150. * Checks the checkbox
  1151. *
  1152. * Поплучить данные поля ввода
  1153. */
  1154. /*function getInput(inputName) {
  1155. return inputs[inputName]?.input?.value;
  1156. }*/
  1157. function getInput(inputName) {
  1158. if (inputName in inputs){return inputs[inputName]?.input?.value;}
  1159. else if (inputName in inputs2){return inputs2[inputName]?.input?.value;}
  1160. //else if (inputName in inputs3){return inputs3[inputName]?.input?.value;}
  1161. else return null
  1162. }
  1163.  
  1164. //тест рейд
  1165. /** Автоповтор миссии */
  1166. let isRepeatMission = false;
  1167. /** Вкл/Выкл автоповтор миссии */
  1168. this.switchRepeatMission = function() {
  1169. isRepeatMission = !isRepeatMission;
  1170. console.log(isRepeatMission);
  1171. }
  1172.  
  1173. /**
  1174. * Control FPS
  1175. *
  1176. * Контроль FPS
  1177. */
  1178. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1179. this.requestAnimationFrame = async function (e) {
  1180. const FPS = Number(getInput('FPS')) || -1;
  1181. const delay = Math.min(1e3 / FPS, 1e3);
  1182. if (delay > 0) {
  1183. await new Promise((e) => setTimeout(e, delay));
  1184. }
  1185. oldRequestAnimationFrame(e);
  1186. }
  1187.  
  1188. /**
  1189. * Button List
  1190. *
  1191. * Список кнопочек
  1192. */
  1193. const buttons = {
  1194. getOutland: {
  1195. name: I18N('TO_DO_EVERYTHING'),
  1196. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1197. func: testDoYourBest,
  1198. },
  1199. /*
  1200. doActions: {
  1201. name: I18N('ACTIONS'),
  1202. title: I18N('ACTIONS_TITLE'),
  1203. func: async function () {
  1204. const popupButtons = [
  1205. {
  1206. msg: I18N('OUTLAND'),
  1207. result: function () {
  1208. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1209. },
  1210. title: I18N('OUTLAND_TITLE'),
  1211. },
  1212. {
  1213. msg: I18N('TOWER'),
  1214. result: function () {
  1215. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1216. },
  1217. title: I18N('TOWER_TITLE'),
  1218. },
  1219. {
  1220. msg: I18N('EXPEDITIONS'),
  1221. result: function () {
  1222. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1223. },
  1224. title: I18N('EXPEDITIONS_TITLE'),
  1225. },
  1226. {
  1227. msg: I18N('MINIONS'),
  1228. result: function () {
  1229. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1230. },
  1231. title: I18N('MINIONS_TITLE'),
  1232. },
  1233. {
  1234. msg: I18N('ESTER_EGGS'),
  1235. result: function () {
  1236. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1237. },
  1238. title: I18N('ESTER_EGGS_TITLE'),
  1239. },
  1240. {
  1241. msg: I18N('STORM'),
  1242. result: function () {
  1243. testAdventure('solo');
  1244. },
  1245. title: I18N('STORM_TITLE'),
  1246. },
  1247. {
  1248. msg: I18N('REWARDS'),
  1249. result: function () {
  1250. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1251. },
  1252. title: I18N('REWARDS_TITLE'),
  1253. },
  1254. {
  1255. msg: I18N('MAIL'),
  1256. result: function () {
  1257. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1258. },
  1259. title: I18N('MAIL_TITLE'),
  1260. },
  1261. {
  1262. msg: I18N('SEER'),
  1263. result: function () {
  1264. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1265. },
  1266. title: I18N('SEER_TITLE'),
  1267. },
  1268. {
  1269. msg: I18N('NY_GIFTS'),
  1270. result: getGiftNewYear,
  1271. title: I18N('NY_GIFTS_TITLE'),
  1272. },
  1273. ];
  1274. popupButtons.push({ result: false, isClose: true })
  1275. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1276. if (typeof answer === 'function') {
  1277. answer();
  1278. }
  1279. }
  1280. },*/
  1281. doOthers: {
  1282. name: I18N('OTHERS'),
  1283. title: I18N('OTHERS_TITLE'),
  1284. func: async function () {
  1285. const popupButtons = [
  1286. /*
  1287. {
  1288. msg: I18N('GET_ENERGY'),
  1289. result: farmStamina,
  1290. title: I18N('GET_ENERGY_TITLE'),
  1291. },
  1292. {
  1293. msg: I18N('ITEM_EXCHANGE'),
  1294. result: fillActive,
  1295. title: I18N('ITEM_EXCHANGE_TITLE'),
  1296. },
  1297. {
  1298. msg: I18N('BUY_SOULS'),
  1299. result: function () {
  1300. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1301. },
  1302. title: I18N('BUY_SOULS_TITLE'),
  1303. },
  1304. {
  1305. msg: I18N('BUY_FOR_GOLD'),
  1306. result: function () {
  1307. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1308. },
  1309. title: I18N('BUY_FOR_GOLD_TITLE'),
  1310. },
  1311. {
  1312. msg: I18N('BUY_OUTLAND'),
  1313. result: function () {
  1314. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1315. },
  1316. title: I18N('BUY_OUTLAND_TITLE'),
  1317. },
  1318. {
  1319. msg: I18N('AUTO_RAID_ADVENTURE'),
  1320. result: autoRaidAdventure,
  1321. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1322. },
  1323. {
  1324. msg: I18N('CLAN_STAT'),
  1325. result: clanStatistic,
  1326. title: I18N('CLAN_STAT_TITLE'),
  1327. },
  1328. {
  1329. msg: I18N('EPIC_BRAWL'),
  1330. result: async function () {
  1331. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1332. const brawl = new epicBrawl;
  1333. brawl.start();
  1334. });
  1335. },
  1336. title: I18N('EPIC_BRAWL_TITLE'),
  1337. },*/
  1338. {
  1339. msg: I18N('ARTIFACTS_UPGRADE'),
  1340. result: updateArtifacts,
  1341. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1342. },
  1343. {
  1344. msg: I18N('SKINS_UPGRADE'),
  1345. result: updateSkins,
  1346. title: I18N('SKINS_UPGRADE_TITLE'),
  1347. },
  1348. {
  1349. msg: I18N('CHANGE_MAP'),
  1350. result: async function () {
  1351. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1352. { msg: I18N('FIRST_MAP'), result: 1 },
  1353. { msg: I18N('SECOND_MAP'), result: 2 },
  1354. { result: false, isClose: true },
  1355. ]
  1356. );
  1357. if (result) {
  1358. cheats.changeIslandMap(result);
  1359. }
  1360. },
  1361. title: I18N('CHANGE_MAP_TITLE'),
  1362. },
  1363. {
  1364. msg: I18N('SHOPS'),
  1365. result: async function () {
  1366. const shopButtons = [{
  1367. msg: I18N('SHOPS_DEFAULT'),
  1368. result: function () {
  1369. cheats.goDefaultShops();
  1370. },
  1371. title: I18N('SHOPS_DEFAULT_TITLE'),
  1372. }, {
  1373. msg: I18N('SECRET_WEALTH'),
  1374. result: function () {
  1375. cheats.goSecretWealthShops();
  1376. },
  1377. title: I18N('SECRET_WEALTH'),
  1378. }];
  1379. for (let i = 0; i < 4; i++) {
  1380. const number = i + 1;
  1381. shopButtons.push({
  1382. msg: I18N('SHOPS_LIST', { number }),
  1383. result: function () {
  1384. cheats.goCustomShops(i);
  1385. },
  1386. title: I18N('SHOPS_LIST_TITLE', { number }),
  1387. })
  1388. }
  1389. shopButtons.push({ result: false, isClose: true })
  1390. const answer = await popup.confirm(I18N('SHOPS_WARNING'), shopButtons);
  1391. if (typeof answer === 'function') {
  1392. answer();
  1393. }
  1394. },
  1395. title: I18N('SHOPS'),
  1396. },
  1397. ];
  1398.  
  1399. popupButtons.push({ result: false, isClose: true })
  1400. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1401. if (typeof answer === 'function') {
  1402. answer();
  1403. }
  1404. }
  1405. },
  1406. testTitanArena: {
  1407. name: I18N('TITAN_ARENA'),
  1408. title: I18N('TITAN_ARENA_TITLE'),
  1409. func: function () {
  1410. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1411. },
  1412. },
  1413. /* тест подземка есть в сделать все
  1414. testDungeon: {
  1415. name: I18N('DUNGEON'),
  1416. title: I18N('DUNGEON_TITLE'),
  1417. func: function () {
  1418. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1419. },
  1420. hide: true,
  1421. },*/
  1422. //тест подземка 2
  1423. DungeonFull: {
  1424. name: I18N('DUNGEON2'),
  1425. title: I18N('DUNGEON_FULL_TITLE'),
  1426. func: function () {
  1427. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON_FULL_TITLE')}?`, DungeonFull);
  1428. },
  1429. },
  1430. //остановить подземелье
  1431. stopDungeon: {
  1432. name: I18N('STOP_DUNGEON'),
  1433. title: I18N('STOP_DUNGEON_TITLE'),
  1434. func: function () {
  1435. confShow(`${I18N('STOP_SCRIPT')} ${I18N('STOP_DUNGEON_TITLE')}?`, stopDungeon);
  1436. },
  1437. },
  1438. /*
  1439. autoBoss: {
  1440. name: 'autoBoss',
  1441. title: 'autoBoss',
  1442. func: function () {
  1443. (new executeEventAutoBoss()).start()
  1444. },
  1445. },
  1446. */
  1447. // Архидемон
  1448. bossRatingEvent: {
  1449. name: I18N('ARCHDEMON'),
  1450. title: I18N('ARCHDEMON_TITLE'),
  1451. func: function () {
  1452. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1453. },
  1454. hide: true,
  1455. },
  1456. /*
  1457. // Горнило душ
  1458. bossRatingEvent: {
  1459. name: I18N('CRUCIBLE_SOULS'),
  1460. title: I18N('CRUCIBLE_SOULS_TITLE'),
  1461. func: function () {
  1462. confShow(`${I18N('RUN_SCRIPT')} ${I18N('CRUCIBLE_SOULS')}?`, bossRatingEventSouls);
  1463. },
  1464. },*/
  1465. /* Буря
  1466. testAdventure2: {
  1467. name: I18N('STORM'),
  1468. title: I18N('STORM_TITLE'),
  1469. func: () => {
  1470. testAdventure2('solo');
  1471. },
  1472. },*/
  1473. rewardsAndMailFarm: {
  1474. name: I18N('REWARDS_AND_MAIL'),
  1475. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1476. func: function () {
  1477. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1478. },
  1479. },
  1480. //тест прислужники
  1481. testRaidNodes: {
  1482. name: I18N('MINIONS'),
  1483. title: I18N('MINIONS_TITLE'),
  1484. func: function () {
  1485. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1486. },
  1487. },
  1488. testAdventure: {
  1489. name: I18N('ADVENTURE'),
  1490. title: I18N('ADVENTURE_TITLE'),
  1491. func: () => {
  1492. testAdventure();
  1493. },
  1494. },
  1495. goToSanctuary: {
  1496. name: I18N('SANCTUARY'),
  1497. title: I18N('SANCTUARY_TITLE'),
  1498. func: cheats.goSanctuary,
  1499. },
  1500. goToClanWar: {
  1501. name: I18N('GUILD_WAR'),
  1502. title: I18N('GUILD_WAR_TITLE'),
  1503. func: cheats.goClanWar,
  1504. },
  1505. dailyQuests: {
  1506. name: I18N('DAILY_QUESTS'),
  1507. title: I18N('DAILY_QUESTS_TITLE'),
  1508. func: async function () {
  1509. const quests = new dailyQuests(() => { }, () => { });
  1510. await quests.autoInit();
  1511. quests.start();
  1512. },
  1513. },
  1514. //подарок др
  1515. /*NewYearGift_Clan: {
  1516. name: I18N('New_Year_Clan'),
  1517. title: I18N('New_Year_Clan_TITLE'),
  1518. func: function () {
  1519. confShow(`${I18N('RUN_SCRIPT')} ${I18N('New_Year_Clan_TITLE')}?`, NewYearGift_Clan);
  1520. },
  1521. },*/
  1522. newDay: {
  1523. name: I18N('SYNC'),
  1524. title: I18N('SYNC_TITLE'),
  1525. func: function () {
  1526. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1527. },
  1528. },
  1529. }
  1530. /**
  1531. * Display buttons
  1532. *
  1533. * Вывести кнопочки
  1534. */
  1535. function addControlButtons() {
  1536. for (let name in buttons) {
  1537. button = buttons[name];
  1538. if (button.hide) {
  1539. continue;
  1540. }
  1541. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1542. }
  1543. }
  1544. /**
  1545. * Adds links
  1546. *
  1547. * Добавляет ссылки
  1548. */
  1549. function addBottomUrls() {
  1550. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1551. }
  1552. /**
  1553. * Stop repetition of the mission
  1554. *
  1555. * Остановить повтор миссии
  1556. */
  1557. let isStopSendMission = false;
  1558. /**
  1559. * There is a repetition of the mission
  1560. *
  1561. * Идет повтор миссии
  1562. */
  1563. let isSendsMission = false;
  1564. /**
  1565. * Data on the past mission
  1566. *
  1567. * Данные о прошедшей мисии
  1568. */
  1569. let lastMissionStart = {}
  1570. /**
  1571. * Start time of the last battle in the company
  1572. *
  1573. * Время начала последнего боя в кампании
  1574. */
  1575. let lastMissionBattleStart = 0;
  1576. /**
  1577. * Data on the past attack on the boss
  1578. *
  1579. * Данные о прошедшей атаке на босса
  1580. */
  1581. let lastBossBattle = {}
  1582. /**
  1583. * Data for calculating the last battle with the boss
  1584. *
  1585. * Данные для расчете последнего боя с боссом
  1586. */
  1587. let lastBossBattleInfo = null;
  1588. /**
  1589. * Ability to cancel the battle in Asgard
  1590. *
  1591. * Возможность отменить бой в Астгарде
  1592. */
  1593. let isCancalBossBattle = true;
  1594. /**
  1595. * Information about the last battle
  1596. *
  1597. * Данные о прошедшей битве
  1598. */
  1599. let lastBattleArg = {}
  1600. /**
  1601. * The name of the function of the beginning of the battle
  1602. *
  1603. * Имя функции начала боя
  1604. */
  1605. let nameFuncStartBattle = '';
  1606. /**
  1607. * The name of the function of the end of the battle
  1608. *
  1609. * Имя функции конца боя
  1610. */
  1611. let nameFuncEndBattle = '';
  1612. /**
  1613. * Data for calculating the last battle
  1614. *
  1615. * Данные для расчета последнего боя
  1616. */
  1617. let lastBattleInfo = null;
  1618. /**
  1619. * The ability to cancel the battle
  1620. *
  1621. * Возможность отменить бой
  1622. */
  1623. let isCancalBattle = true;
  1624.  
  1625. /**
  1626. * Certificator of the last open nesting doll
  1627. *
  1628. * Идетификатор последней открытой матрешки
  1629. */
  1630. let lastRussianDollId = null;
  1631. /**
  1632. * Cancel the training guide
  1633. *
  1634. * Отменить обучающее руководство
  1635. */
  1636. this.isCanceledTutorial = false;
  1637.  
  1638. /**
  1639. * Data from the last question of the quiz
  1640. *
  1641. * Данные последнего вопроса викторины
  1642. */
  1643. let lastQuestion = null;
  1644. /**
  1645. * Answer to the last question of the quiz
  1646. *
  1647. * Ответ на последний вопрос викторины
  1648. */
  1649. let lastAnswer = null;
  1650. /**
  1651. * Flag for opening keys or titan artifact spheres
  1652. *
  1653. * Флаг открытия ключей или сфер артефактов титанов
  1654. */
  1655. let artifactChestOpen = false;
  1656. /**
  1657. * The name of the function to open keys or orbs of titan artifacts
  1658. *
  1659. * Имя функции открытия ключей или сфер артефактов титанов
  1660. */
  1661. let artifactChestOpenCallName = '';
  1662. let correctShowOpenArtifact = 0;
  1663. /**
  1664. * Data for the last battle in the dungeon
  1665. * (Fix endless cards)
  1666. *
  1667. * Данные для последнего боя в подземке
  1668. * (Исправление бесконечных карт)
  1669. */
  1670. let lastDungeonBattleData = null;
  1671. /**
  1672. * Start time of the last battle in the dungeon
  1673. *
  1674. * Время начала последнего боя в подземелье
  1675. */
  1676. let lastDungeonBattleStart = 0;
  1677. /**
  1678. * Subscription end time
  1679. *
  1680. * Время окончания подписки
  1681. */
  1682. let subEndTime = 0;
  1683. /**
  1684. * Number of prediction cards
  1685. *
  1686. * Количество карт предсказаний
  1687. */
  1688. let countPredictionCard = 0;
  1689.  
  1690. /**
  1691. * Brawl pack
  1692. *
  1693. * Пачка для потасовок
  1694. */
  1695. let brawlsPack = null;
  1696. /**
  1697. * Autobrawl started
  1698. *
  1699. * Автопотасовка запущена
  1700. */
  1701. let isBrawlsAutoStart = false;
  1702. /**
  1703. * Copies the text to the clipboard
  1704. *
  1705. * Копирует тест в буфер обмена
  1706. * @param {*} text copied text // копируемый текст
  1707. */
  1708. function copyText(text) {
  1709. let copyTextarea = document.createElement("textarea");
  1710. copyTextarea.style.opacity = "0";
  1711. copyTextarea.textContent = text;
  1712. document.body.appendChild(copyTextarea);
  1713. copyTextarea.select();
  1714. document.execCommand("copy");
  1715. document.body.removeChild(copyTextarea);
  1716. delete copyTextarea;
  1717. }
  1718. /**
  1719. * Returns the history of requests
  1720. *
  1721. * Возвращает историю запросов
  1722. */
  1723. this.getRequestHistory = function() {
  1724. return requestHistory;
  1725. }
  1726. /**
  1727. * Generates a random integer from min to max
  1728. *
  1729. * Гененирует случайное целое число от min до max
  1730. */
  1731. const random = function (min, max) {
  1732. return Math.floor(Math.random() * (max - min + 1) + min);
  1733. }
  1734. /**
  1735. * Clearing the request history
  1736. *
  1737. * Очистка истоии запросов
  1738. */
  1739. setInterval(function () {
  1740. let now = Date.now();
  1741. for (let i in requestHistory) {
  1742. if (now - i > 300000) {
  1743. delete requestHistory[i];
  1744. }
  1745. }
  1746. }, 300000);
  1747. /**
  1748. * DOM Loading Event page
  1749. *
  1750. * Событие загрузки DOM дерева страницы
  1751. */
  1752. document.addEventListener("DOMContentLoaded", () => {
  1753. /**
  1754. * Create the script interface
  1755. *
  1756. * Создание интерфеса скрипта
  1757. */
  1758. createInterface();
  1759. });
  1760. /**
  1761. * Gift codes collecting and sending codes
  1762. *
  1763. * Сбор и отправка кодов подарков
  1764. */
  1765. function sendCodes() {
  1766. return;
  1767. let codes = [], count = 0;
  1768. if (!localStorage['giftSendIds']) {
  1769. localStorage['giftSendIds'] = '';
  1770. }
  1771. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  1772. let url = e?.href;
  1773. if (!url) return;
  1774. url = new URL(url);
  1775. let giftId = url.searchParams.get('gift_id');
  1776. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  1777. localStorage['giftSendIds'] += ';' + giftId;
  1778. codes.push(giftId);
  1779. count++;
  1780. });
  1781.  
  1782. if (codes.length) {
  1783. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  1784. sendGiftsCodes(codes);
  1785. }
  1786.  
  1787. if (!count) {
  1788. setTimeout(sendCodes, 2000);
  1789. }
  1790. }
  1791. /**
  1792. * Checking sent codes
  1793. *
  1794. * Проверка отправленных кодов
  1795. */
  1796. function checkSendGifts() {
  1797. if (!freebieCheckInfo) {
  1798. return;
  1799. }
  1800.  
  1801. let giftId = freebieCheckInfo.args.giftId;
  1802. let valName = 'giftSendIds_' + userInfo.id;
  1803. localStorage[valName] = localStorage[valName] ?? '';
  1804. if (!localStorage[valName].includes(giftId)) {
  1805. localStorage[valName] += ';' + giftId;
  1806. sendGiftsCodes([giftId]);
  1807. }
  1808. }
  1809. /**
  1810. * Sending codes
  1811. *
  1812. * Отправка кодов
  1813. */
  1814. function sendGiftsCodes(codes) {
  1815. return;
  1816. fetch('https://zingery.ru/heroes/setGifts.php', {
  1817. method: 'POST',
  1818. body: JSON.stringify(codes)
  1819. }).then(
  1820. response => response.json()
  1821. ).then(
  1822. data => {
  1823. if (data.result) {
  1824. console.log(I18N('GIFTS_SENT'));
  1825. }
  1826. }
  1827. )
  1828. }
  1829. /**
  1830. * Displays the dialog box
  1831. *
  1832. * Отображает диалоговое окно
  1833. */
  1834. function confShow(message, yesCallback, noCallback) {
  1835. let buts = [];
  1836. message = message || I18N('DO_YOU_WANT');
  1837. noCallback = noCallback || (() => {});
  1838. if (yesCallback) {
  1839. buts = [
  1840. { msg: I18N('BTN_RUN'), result: true},
  1841. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1842. ]
  1843. } else {
  1844. yesCallback = () => {};
  1845. buts = [
  1846. { msg: I18N('BTN_OK'), result: true},
  1847. ];
  1848. }
  1849. popup.confirm(message, buts).then((e) => {
  1850. // dialogPromice = null;
  1851. if (e) {
  1852. yesCallback();
  1853. } else {
  1854. noCallback();
  1855. }
  1856. });
  1857. }
  1858. /**
  1859. * Override/proxy the method for creating a WS package send
  1860. *
  1861. * Переопределяем/проксируем метод создания отправки WS пакета
  1862. */
  1863. WebSocket.prototype.send = function (data) {
  1864. if (!this.isSetOnMessage) {
  1865. const oldOnmessage = this.onmessage;
  1866. this.onmessage = function (event) {
  1867. try {
  1868. const data = JSON.parse(event.data);
  1869. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1870. this.isWebSocketLogin = true;
  1871. } else if (data.result.type == "iframeEvent.login") {
  1872. return;
  1873. }
  1874. } catch (e) { }
  1875. return oldOnmessage.apply(this, arguments);
  1876. }
  1877. this.isSetOnMessage = true;
  1878. }
  1879. original.SendWebSocket.call(this, data);
  1880. }
  1881. /**
  1882. * Overriding/Proxying the Ajax Request Creation Method
  1883. *
  1884. * Переопределяем/проксируем метод создания Ajax запроса
  1885. */
  1886. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1887. this.uniqid = Date.now();
  1888. this.errorRequest = false;
  1889. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1890. if (!apiUrl) {
  1891. apiUrl = url;
  1892. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1893. console.log(socialInfo);
  1894. }
  1895. requestHistory[this.uniqid] = {
  1896. method,
  1897. url,
  1898. error: [],
  1899. headers: {},
  1900. request: null,
  1901. response: null,
  1902. signature: [],
  1903. calls: {},
  1904. };
  1905. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1906. this.errorRequest = true;
  1907. }
  1908. return original.open.call(this, method, url, async, user, password);
  1909. };
  1910. /**
  1911. * Overriding/Proxying the header setting method for the AJAX request
  1912. *
  1913. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1914. */
  1915. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1916. if (this.uniqid in requestHistory) {
  1917. requestHistory[this.uniqid].headers[name] = value;
  1918. } else {
  1919. check = true;
  1920. }
  1921.  
  1922. if (name == 'X-Auth-Signature') {
  1923. requestHistory[this.uniqid].signature.push(value);
  1924. if (!check) {
  1925. return;
  1926. }
  1927. }
  1928.  
  1929. return original.setRequestHeader.call(this, name, value);
  1930. };
  1931. /**
  1932. * Overriding/Proxying the AJAX Request Sending Method
  1933. *
  1934. * Переопределяем/проксируем метод отправки AJAX запроса
  1935. */
  1936. XMLHttpRequest.prototype.send = async function (sourceData) {
  1937. if (this.uniqid in requestHistory) {
  1938. let tempData = null;
  1939. if (getClass(sourceData) == "ArrayBuffer") {
  1940. tempData = decoder.decode(sourceData);
  1941. } else {
  1942. tempData = sourceData;
  1943. }
  1944. requestHistory[this.uniqid].request = tempData;
  1945. let headers = requestHistory[this.uniqid].headers;
  1946. lastHeaders = Object.assign({}, headers);
  1947. /**
  1948. * Game loading event
  1949. *
  1950. * Событие загрузки игры
  1951. */
  1952. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1953. isLoadGame = true;
  1954. await lib.load();
  1955. addControls();
  1956. addControlButtons();
  1957. addBottomUrls();
  1958.  
  1959. //if (isChecked('sendExpedition')) {
  1960. checkExpedition(); //экспедиции на авто при входе в игру
  1961. //}
  1962.  
  1963. checkSendGifts();
  1964. getAutoGifts();
  1965.  
  1966. cheats.activateHacks();
  1967.  
  1968. justInfo();
  1969. if (isChecked('dailyQuests')) {
  1970. testDailyQuests();
  1971. }
  1972.  
  1973. if (isChecked('buyForGold')) {
  1974. buyInStoreForGold();
  1975. }
  1976. }
  1977. /**
  1978. * Outgoing request data processing
  1979. *
  1980. * Обработка данных исходящего запроса
  1981. */
  1982. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1983. /**
  1984. * Handling incoming request data
  1985. *
  1986. * Обработка данных входящего запроса
  1987. */
  1988. const oldReady = this.onreadystatechange;
  1989. this.onreadystatechange = async function (e) {
  1990. if(this.readyState == 4 && this.status == 200) {
  1991. isTextResponse = this.responseType === "text" || this.responseType === "";
  1992. let response = isTextResponse ? this.responseText : this.response;
  1993. requestHistory[this.uniqid].response = response;
  1994. /**
  1995. * Replacing incoming request data
  1996. *
  1997. * Заменна данных входящего запроса
  1998. */
  1999. if (isTextResponse) {
  2000. await checkChangeResponse.call(this, response);
  2001. }
  2002. /**
  2003. * A function to run after the request is executed
  2004. *
  2005. * Функция запускаемая после выполения запроса
  2006. */
  2007. if (typeof this.onReadySuccess == 'function') {
  2008. setTimeout(this.onReadySuccess, 500);
  2009. }
  2010. }
  2011. if (oldReady) {
  2012. return oldReady.apply(this, arguments);
  2013. }
  2014. }
  2015. }
  2016. if (this.errorRequest) {
  2017. const oldReady = this.onreadystatechange;
  2018. this.onreadystatechange = function () {
  2019. Object.defineProperty(this, 'status', {
  2020. writable: true
  2021. });
  2022. this.status = 200;
  2023. Object.defineProperty(this, 'readyState', {
  2024. writable: true
  2025. });
  2026. this.readyState = 4;
  2027. Object.defineProperty(this, 'responseText', {
  2028. writable: true
  2029. });
  2030. this.responseText = JSON.stringify({
  2031. "result": true
  2032. });
  2033. return oldReady.apply(this, arguments);
  2034. }
  2035. this.onreadystatechange();
  2036. } else {
  2037. try {
  2038. return original.send.call(this, sourceData);
  2039. } catch(e) {
  2040. debugger;
  2041. }
  2042.  
  2043. }
  2044. };
  2045. /**
  2046. * Processing and substitution of outgoing data
  2047. *
  2048. * Обработка и подмена исходящих данных
  2049. */
  2050. async function checkChangeSend(sourceData, tempData) {
  2051. try {
  2052. /**
  2053. * A function that replaces battle data with incorrect ones to cancel combatя
  2054. *
  2055. * Функция заменяющая данные боя на неверные для отмены боя
  2056. */
  2057. const fixBattle = function (heroes) {
  2058. for (const ids in heroes) {
  2059. hero = heroes[ids];
  2060. hero.energy = random(1, 999);
  2061. if (hero.hp > 0) {
  2062. hero.hp = random(1, hero.hp);
  2063. }
  2064. }
  2065. }
  2066. /**
  2067. * Dialog window 2
  2068. *
  2069. * Диалоговое окно 2
  2070. */
  2071. const showMsg = async function (msg, ansF, ansS) {
  2072. if (typeof popup == 'object') {
  2073. return await popup.confirm(msg, [
  2074. {msg: ansF, result: false},
  2075. {msg: ansS, result: true},
  2076. ]);
  2077. } else {
  2078. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2079. }
  2080. }
  2081. /**
  2082. * Dialog window 3
  2083. *
  2084. * Диалоговое окно 3
  2085. */
  2086. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2087. return await popup.confirm(msg, [
  2088. {msg: ansF, result: 0},
  2089. {msg: ansS, result: 1},
  2090. {msg: ansT, result: 2},
  2091. ]);
  2092. }
  2093.  
  2094. let changeRequest = false;
  2095. testData = JSON.parse(tempData);
  2096. for (const call of testData.calls) {
  2097. if (!artifactChestOpen) {
  2098. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2099. }
  2100. /**
  2101. * Сбор подарка
  2102. */
  2103. /*
  2104. if (call.name == 'registration') {
  2105. if (!call.args?.giftId) {
  2106. const giftId = await getGiftCode();
  2107. if (giftId) {
  2108. call.args.giftId = giftId;
  2109. changeRequest = true;
  2110. }
  2111. } else {
  2112. sendGiftsCodes([call.args.giftId])
  2113. }
  2114. }
  2115. */
  2116. /**
  2117. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2118. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2119. */
  2120. if ((call.name == 'adventure_endBattle' ||
  2121. call.name == 'adventureSolo_endBattle' ||
  2122. call.name == 'clanWarEndBattle' &&
  2123. isChecked('cancelBattle') ||
  2124. call.name == 'crossClanWar_endBattle' &&
  2125. isChecked('cancelBattle') ||
  2126. call.name == 'brawl_endBattle' ||
  2127. call.name == 'towerEndBattle' ||
  2128. call.name == 'invasion_bossEnd' ||
  2129. call.name == 'bossEndBattle' ||
  2130. call.name == 'clanRaid_endNodeBattle') &&
  2131. isCancalBattle) {
  2132. nameFuncEndBattle = call.name;
  2133. if (!call.args.result.win) {
  2134. let resultPopup = false;
  2135. if (call.name == 'adventure_endBattle' ||
  2136. call.name == 'invasion_bossEnd' ||
  2137. call.name == 'bossEndBattle' ||
  2138. call.name == 'adventureSolo_endBattle') {
  2139. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2140. } else if (call.name == 'clanWarEndBattle' ||
  2141. call.name == 'crossClanWar_endBattle') {
  2142. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2143. } else {
  2144. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2145. }
  2146. if (resultPopup) {
  2147. fixBattle(call.args.progress[0].attackers.heroes);
  2148. fixBattle(call.args.progress[0].defenders.heroes);
  2149. changeRequest = true;
  2150. if (resultPopup > 1) {
  2151. this.onReadySuccess = testAutoBattle;
  2152. // setTimeout(bossBattle, 1000);
  2153. }
  2154. }
  2155. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2156. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2157. if (resultPopup) {
  2158. fixBattle(call.args.progress[0].attackers.heroes);
  2159. fixBattle(call.args.progress[0].defenders.heroes);
  2160. changeRequest = true;
  2161. if (resultPopup > 1) {
  2162. this.onReadySuccess = testAutoBattle;
  2163. }
  2164. }
  2165. }
  2166. // Потасовки
  2167. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {
  2168. if (await popup.confirm(I18N('START_AUTO_BRAWLS'), [
  2169. { msg: I18N('BTN_NO'), result: false },
  2170. { msg: I18N('BTN_YES'), result: true },
  2171. ])) {
  2172. this.onReadySuccess = testBrawls;
  2173. isBrawlsAutoStart = true;
  2174. }
  2175. }
  2176. }
  2177. /**
  2178. * Save pack for Brawls
  2179. *
  2180. * Сохраняем пачку для потасовок
  2181. */
  2182. if (call.name == 'brawl_startBattle') {
  2183. console.log(JSON.stringify(call.args));
  2184. brawlsPack = call.args;
  2185. }
  2186. /**
  2187. * Canceled fight in Asgard
  2188. * Отмена боя в Асгарде
  2189. */
  2190. if (call.name == 'clanRaid_endBossBattle' &&
  2191. isCancalBossBattle &&
  2192. isChecked('cancelBattle')) {
  2193. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2194. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2195. let resultPopup = await showMsgs(
  2196. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2197. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  2198. if (resultPopup) {
  2199. fixBattle(call.args.progress[0].attackers.heroes);
  2200. fixBattle(call.args.progress[0].defenders.heroes);
  2201. changeRequest = true;
  2202. if (resultPopup > 1) {
  2203. this.onReadySuccess = testBossBattle;
  2204. // setTimeout(bossBattle, 1000);
  2205. }
  2206. }
  2207. }
  2208. /**
  2209. * Save the Asgard Boss Attack Pack
  2210. * Сохраняем пачку для атаки босса Асгарда
  2211. */
  2212. if (call.name == 'clanRaid_startBossBattle') {
  2213. lastBossBattle = call.args;
  2214. }
  2215. /**
  2216. * Saving the request to start the last battle
  2217. * Сохранение запроса начала последнего боя
  2218. */
  2219. if (call.name == 'clanWarAttack' ||
  2220. call.name == 'crossClanWar_startBattle' ||
  2221. call.name == 'adventure_turnStartBattle' ||
  2222. call.name == 'bossAttack' ||
  2223. call.name == 'invasion_bossStart' ||
  2224. call.name == 'towerStartBattle') {
  2225. nameFuncStartBattle = call.name;
  2226. lastBattleArg = call.args;
  2227. }
  2228. /**
  2229. * Disable spending divination cards
  2230. * Отключить трату карт предсказаний
  2231. */
  2232. if (call.name == 'dungeonEndBattle') {
  2233. if (call.args.isRaid) {
  2234. if (countPredictionCard <= 0) {
  2235. delete call.args.isRaid;
  2236. changeRequest = true;
  2237. } else if (countPredictionCard > 0) {
  2238. countPredictionCard--;
  2239. }
  2240. }
  2241. console.log(`Cards: ${countPredictionCard}`);
  2242. /**
  2243. * Fix endless cards
  2244. * Исправление бесконечных карт
  2245. */
  2246. const lastBattle = lastDungeonBattleData;
  2247. if (lastBattle && !call.args.isRaid) {
  2248. if (changeRequest) {
  2249. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2250. } else {
  2251. lastBattle.progress = call.args.progress;
  2252. }
  2253. const result = await Calc(lastBattle);
  2254.  
  2255. if (changeRequest) {
  2256. call.args.progress = result.progress;
  2257. call.args.result = result.result;
  2258. }
  2259.  
  2260. let timer = getTimer(result.battleTime);
  2261. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2262. console.log(timer, period);
  2263. if (period < timer) {
  2264. timer = timer - period;
  2265. await countdownTimer(timer);
  2266. }
  2267. }
  2268. }
  2269. /**
  2270. * Quiz Answer
  2271. * Ответ на викторину
  2272. */
  2273. if (call.name == 'quizAnswer') {
  2274. /**
  2275. * Automatically changes the answer to the correct one if there is one.
  2276. * Автоматически меняет ответ на правильный если он есть
  2277. */
  2278. if (lastAnswer && isChecked('getAnswer')) {
  2279. call.args.answerId = lastAnswer;
  2280. lastAnswer = null;
  2281. changeRequest = true;
  2282. }
  2283. }
  2284. /**
  2285. * Present
  2286. * Подарки
  2287. */
  2288. if (call.name == 'freebieCheck') {
  2289. freebieCheckInfo = call;
  2290. }
  2291. /** missionTimer */
  2292. if (call.name == 'missionEnd' && missionBattle) {
  2293. missionBattle.progress = call.args.progress;
  2294. missionBattle.result = call.args.result;
  2295. const result = await Calc(missionBattle);
  2296.  
  2297. let timer = getTimer(result.battleTime) + 5;
  2298. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2299. if (period < timer) {
  2300. timer = timer - period;
  2301. await countdownTimer(timer);
  2302. }
  2303. missionBattle = null;
  2304. }
  2305. /**
  2306. * Getting mission data for auto-repeat
  2307. * Получение данных миссии для автоповтора
  2308. */
  2309. if ((isRepeatMission || isChecked('isRepeatMission')) &&
  2310. call.name == 'missionEnd') {
  2311. let missionInfo = {
  2312. id: call.args.id,
  2313. result: call.args.result,
  2314. heroes: call.args.progress[0].attackers.heroes,
  2315. count: 0,
  2316. }
  2317. setTimeout(async () => {
  2318. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2319. { msg: I18N('BTN_REPEAT'), result: true},
  2320. { msg: I18N('BTN_NO'), result: false},
  2321. ])) {
  2322. isStopSendMission = false;
  2323. isSendsMission = true;
  2324. sendsMission(missionInfo);
  2325. }
  2326. }, 0);
  2327. }
  2328. /**
  2329. * Getting mission data
  2330. * Получение данных миссии
  2331. * missionTimer
  2332. */
  2333. if (call.name == 'missionStart') {
  2334. lastMissionStart = call.args;
  2335. lastMissionBattleStart = Date.now();
  2336. }
  2337.  
  2338. /**
  2339. * Specify the quantity for Titan Orbs and Pet Eggs
  2340. * Указать количество для сфер титанов и яиц петов
  2341. */
  2342. if (isChecked('countControl') &&
  2343. (call.name == 'pet_chestOpen' ||
  2344. call.name == 'titanUseSummonCircle') &&
  2345. call.args.amount > 1) {
  2346. call.args.amount = 1;
  2347. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2348. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2349. ]);
  2350. if (result) {
  2351. call.args.amount = result;
  2352. changeRequest = true;
  2353. }
  2354. }
  2355. /**
  2356. * Specify the amount for keys and spheres of titan artifacts
  2357. * Указать колличество для ключей и сфер артефактов титанов
  2358. */
  2359. if (isChecked('countControl') &&
  2360. (call.name == 'artifactChestOpen' ||
  2361. call.name == 'titanArtifactChestOpen') &&
  2362. call.args.amount > 1 &&
  2363. call.args.free &&
  2364. !changeRequest) {
  2365. artifactChestOpenCallName = call.name;
  2366. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2367. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2368. ]);
  2369. if (result) {
  2370. let sphere = result < 10 ? 1 : 10;
  2371.  
  2372. call.args.amount = sphere;
  2373. result -= sphere;
  2374.  
  2375. for (let count = result; count > 0; count -= sphere) {
  2376. if (count < 10) sphere = 1;
  2377. const ident = artifactChestOpenCallName + "_" + count;
  2378. testData.calls.push({
  2379. name: artifactChestOpenCallName,
  2380. args: {
  2381. amount: sphere,
  2382. free: true,
  2383. },
  2384. ident: ident
  2385. });
  2386. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2387. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2388. }
  2389. requestHistory[this.uniqid].calls[call.name].push(ident);
  2390. }
  2391.  
  2392. artifactChestOpen = true;
  2393. changeRequest = true;
  2394. }
  2395. }
  2396. if (call.name == 'consumableUseLootBox') {
  2397. lastRussianDollId = call.args.libId;
  2398. /**
  2399. * Specify quantity for gold caskets
  2400. * Указать количество для золотых шкатулок
  2401. */
  2402. if (isChecked('countControl') &&
  2403. call.args.libId == 148 &&
  2404. call.args.amount > 1) {
  2405. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2406. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2407. ]);
  2408. call.args.amount = result;
  2409. changeRequest = true;
  2410. }
  2411. }
  2412. /**
  2413. * Changing the maximum number of raids in the campaign
  2414. * Изменение максимального количества рейдов в кампании
  2415. */
  2416. // if (call.name == 'missionRaid') {
  2417. // if (isChecked('countControl') && call.args.times > 1) {
  2418. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2419. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2420. // ]));
  2421. // call.args.times = result > call.args.times ? call.args.times : result;
  2422. // changeRequest = true;
  2423. // }
  2424. // }
  2425. }
  2426.  
  2427. let headers = requestHistory[this.uniqid].headers;
  2428. if (changeRequest) {
  2429. sourceData = JSON.stringify(testData);
  2430. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2431. }
  2432.  
  2433. let signature = headers['X-Auth-Signature'];
  2434. if (signature) {
  2435. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2436. }
  2437. } catch (err) {
  2438. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2439. }
  2440. return sourceData;
  2441. }
  2442. /**
  2443. * Processing and substitution of incoming data
  2444. *
  2445. * Обработка и подмена входящих данных
  2446. */
  2447. async function checkChangeResponse(response) {
  2448. try {
  2449. isChange = false;
  2450. let nowTime = Math.round(Date.now() / 1000);
  2451. callsIdent = requestHistory[this.uniqid].calls;
  2452. respond = JSON.parse(response);
  2453. /**
  2454. * If the request returned an error removes the error (removes synchronization errors)
  2455. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2456. */
  2457. if (respond.error) {
  2458. isChange = true;
  2459. console.error(respond.error);
  2460. if (isChecked('showErrors')) {
  2461. popup.confirm(I18N('ERROR_MSG', {
  2462. name: respond.error.name,
  2463. description: respond.error.description,
  2464. }));
  2465. }
  2466. delete respond.error;
  2467. respond.results = [];
  2468. }
  2469. let mainReward = null;
  2470. const allReward = {};
  2471. let countTypeReward = 0;
  2472. let readQuestInfo = false;
  2473. for (const call of respond.results) {
  2474. /**
  2475. * Obtaining initial data for completing quests
  2476. * Получение исходных данных для выполнения квестов
  2477. */
  2478. if (readQuestInfo) {
  2479. questsInfo[call.ident] = call.result.response;
  2480. }
  2481. /**
  2482. * Getting a user ID
  2483. * Получение идетификатора пользователя
  2484. */
  2485. if (call.ident == callsIdent['registration']) {
  2486. userId = call.result.response.userId;
  2487. if (localStorage['userId'] != userId) {
  2488. localStorage['newGiftSendIds'] = '';
  2489. localStorage['userId'] = userId;
  2490. }
  2491. await openOrMigrateDatabase(userId);
  2492. readQuestInfo = true;
  2493. }
  2494. /**
  2495. * Hiding donation offers 1
  2496. * Скрываем предложения доната 1
  2497. */
  2498. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2499. const billings = call.result.response?.billings;
  2500. const bundle = call.result.response?.bundle;
  2501. if (billings && bundle) {
  2502. call.result.response.billings = [];
  2503. call.result.response.bundle = [];
  2504. isChange = true;
  2505. }
  2506. }
  2507. /**
  2508. * Hiding donation offers 2
  2509. * Скрываем предложения доната 2
  2510. */
  2511. if (getSaveVal('noOfferDonat') &&
  2512. (call.ident == callsIdent['offerGetAll'] ||
  2513. call.ident == callsIdent['specialOffer_getAll'])) {
  2514. let offers = call.result.response;
  2515. if (offers) {
  2516. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2517. isChange = true;
  2518. }
  2519. }
  2520. /**
  2521. * Hiding donation offers 3
  2522. * Скрываем предложения доната 3
  2523. */
  2524. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2525. delete call.result.bundleUpdate;
  2526. isChange = true;
  2527. }
  2528. /**
  2529. * Copies a quiz question to the clipboard
  2530. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2531. */
  2532. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2533. let quest = call.result.response;
  2534. console.log(quest.question);
  2535. copyText(quest.question);
  2536. setProgress(I18N('QUESTION_COPY'), true);
  2537. quest.lang = null;
  2538. if (typeof NXFlashVars !== 'undefined') {
  2539. quest.lang = NXFlashVars.interface_lang;
  2540. }
  2541. lastQuestion = quest;
  2542. if (isChecked('getAnswer')) {
  2543. const answer = await getAnswer(lastQuestion);
  2544. let showText = '';
  2545. if (answer) {
  2546. lastAnswer = answer;
  2547. console.log(answer);
  2548. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2549. } else {
  2550. showText = I18N('ANSWER_NOT_KNOWN');
  2551. }
  2552.  
  2553. try {
  2554. const hint = hintQuest(quest);
  2555. if (hint) {
  2556. showText += I18N('HINT') + hint;
  2557. }
  2558. } catch(e) {}
  2559.  
  2560. setProgress(showText, true);
  2561. }
  2562. }
  2563. /**
  2564. * Submits a question with an answer to the database
  2565. * Отправляет вопрос с ответом в базу данных
  2566. */
  2567. if (call.ident == callsIdent['quizAnswer']) {
  2568. const answer = call.result.response;
  2569. if (lastQuestion) {
  2570. const answerInfo = {
  2571. answer,
  2572. question: lastQuestion,
  2573. lang: null,
  2574. }
  2575. if (typeof NXFlashVars !== 'undefined') {
  2576. answerInfo.lang = NXFlashVars.interface_lang;
  2577. }
  2578. lastQuestion = null;
  2579. setTimeout(sendAnswerInfo, 0, answerInfo);
  2580. }
  2581. }
  2582. /**
  2583. * Get user data
  2584. * Получить даныне пользователя
  2585. */
  2586. if (call.ident == callsIdent['userGetInfo']) {
  2587. let user = call.result.response;
  2588. userInfo = Object.assign({}, user);
  2589. delete userInfo.refillable;
  2590. if (!questsInfo['userGetInfo']) {
  2591. questsInfo['userGetInfo'] = user;
  2592. }
  2593. }
  2594. /**
  2595. * Start of the battle for recalculation
  2596. * Начало боя для прерасчета
  2597. */
  2598. if (call.ident == callsIdent['clanWarAttack'] ||
  2599. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2600. call.ident == callsIdent['bossAttack'] ||
  2601. call.ident == callsIdent['battleGetReplay'] ||
  2602. call.ident == callsIdent['brawl_startBattle'] ||
  2603. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2604. call.ident == callsIdent['invasion_bossStart'] ||
  2605. call.ident == callsIdent['towerStartBattle'] ||
  2606. call.ident == callsIdent['adventure_turnStartBattle']) {
  2607. let battle = call.result.response.battle || call.result.response.replay;
  2608. if (call.ident == callsIdent['brawl_startBattle'] ||
  2609. call.ident == callsIdent['bossAttack'] ||
  2610. call.ident == callsIdent['towerStartBattle'] ||
  2611. call.ident == callsIdent['invasion_bossStart']) {
  2612. battle = call.result.response;
  2613. }
  2614. lastBattleInfo = battle;
  2615. if (!isChecked('preCalcBattle')) {
  2616. continue;
  2617. }
  2618. setProgress(I18N('BEING_RECALC'));
  2619. let battleDuration = 120;
  2620. try {
  2621. const typeBattle = getBattleType(battle.type);
  2622. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2623. } catch (e) { }
  2624. //console.log(battle.type);
  2625. function getBattleInfo(battle, isRandSeed) {
  2626. return new Promise(function (resolve) {
  2627. if (isRandSeed) {
  2628. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2629. }
  2630. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2631. });
  2632. }
  2633. let actions = [getBattleInfo(battle, false)]
  2634. const countTestBattle = getInput('countTestBattle');
  2635. if (call.ident == callsIdent['battleGetReplay']) {
  2636. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2637. }
  2638. for (let i = 0; i < countTestBattle; i++) {
  2639. actions.push(getBattleInfo(battle, true));
  2640. }
  2641. Promise.all(actions)
  2642. .then(e => {
  2643. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2644. let firstBattle = e.shift();
  2645. const timer = Math.floor(battleDuration - firstBattle.time);
  2646. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2647. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2648. const countWin = e.reduce((w, s) => w + s.win, 0);
  2649. setProgress(`${I18N('THIS_TIME')} ${(firstBattle.win ? I18N('VICTORY') : I18N('DEFEAT'))} ${I18N('CHANCE_TO_WIN')}: ${Math.floor(countWin / e.length * 100)}% (${e.length}), ${min}:${sec}`, false, hideProgress)
  2650. });
  2651. }
  2652. //тест сохранки
  2653. /** Запоминаем команды в реплее*/
  2654. if (call.ident == callsIdent['battleGetReplay']) {
  2655. let battle = call.result.response.replay;
  2656. repleyBattle.attackers = battle.attackers;
  2657. repleyBattle.defenders = battle.defenders[0];
  2658. repleyBattle.effects = battle.effects.defenders;
  2659. repleyBattle.state = battle.progress[0].defenders.heroes;
  2660. repleyBattle.seed = battle.seed;
  2661. }
  2662. /** Нападение в турнире*/
  2663. if (call.ident == callsIdent['titanArenaStartBattle']) {
  2664. let bestBattle = getInput('countBattle');
  2665. let unrandom = getInput('needResource');
  2666. let maxPower = getInput('needResource2');
  2667. if (bestBattle * unrandom * maxPower == 0) {
  2668. let battle = call.result.response.battle;
  2669. if (bestBattle == 0) {
  2670. battle.progress = bestLordBattle[battle.typeId]?.progress;
  2671. }
  2672. if (unrandom == 0 && !!repleyBattle.seed) {
  2673. battle.seed = repleyBattle.seed;
  2674. }
  2675. if (maxPower == 0) {
  2676. battle.attackers = getTitansPack(Object.keys(battle.attackers));
  2677. }
  2678. isChange = true;
  2679. }
  2680. }
  2681. /** Тест боев с усилениями команд защиты*/
  2682. if (call.ident == callsIdent['chatAcceptChallenge']) {
  2683. let battle = call.result.response.battle;
  2684. addBuff(battle);
  2685. let testType = getInput('countBattle');
  2686. if (testType.slice(0, 1) == "-") {
  2687. testType = parseInt(testType.slice(1), 10);
  2688. switch (testType) {
  2689. case 1:
  2690. battle.defenders[0] = repleyBattle.defenders;
  2691. break; //наша атака против защиты из реплея
  2692. case 2:
  2693. battle.defenders[0] = repleyBattle.attackers;
  2694. break; //наша атака против атаки из реплея
  2695. case 3:
  2696. battle.attackers = repleyBattle.attackers;
  2697. break; //атака из реплея против защиты в чате
  2698. case 4:
  2699. battle.attackers = repleyBattle.defenders;
  2700. break; //защита из реплея против защиты в чате
  2701. case 5:
  2702. battle.attackers = repleyBattle.attackers;
  2703. battle.defenders[0] = repleyBattle.defenders;
  2704. break; //атака из реплея против защиты из реплея
  2705. case 6:
  2706. battle.attackers = repleyBattle.defenders;
  2707. battle.defenders[0] = repleyBattle.attackers;
  2708. break; //защита из реплея против атаки из реплея
  2709. case 7:
  2710. battle.attackers = repleyBattle.attackers;
  2711. battle.defenders[0] = repleyBattle.attackers;
  2712. break; //атака из реплея против атаки из реплея
  2713. case 8:
  2714. battle.attackers = repleyBattle.defenders;
  2715. battle.defenders[0] = repleyBattle.defenders;
  2716. break; //защита из реплея против защиты из реплея
  2717. }
  2718. }
  2719.  
  2720. isChange = true;
  2721. }
  2722. /** Тест боев с усилениями команд защиты тренировках*/
  2723. if (call.ident == callsIdent['demoBattles_startBattle']) {
  2724. let battle = call.result.response.battle;
  2725. addBuff(battle);
  2726. let testType = getInput('countBattle');
  2727. if (testType.slice(0, 1) == "-") {
  2728. testType = parseInt(testType.slice(1), 10);
  2729. switch (testType) {
  2730. case 1:
  2731. battle.defenders[0] = repleyBattle.defenders;
  2732. break; //наша атака против защиты из реплея
  2733. case 2:
  2734. battle.defenders[0] = repleyBattle.attackers;
  2735. break; //наша атака против атаки из реплея
  2736. case 3:
  2737. battle.attackers = repleyBattle.attackers;
  2738. break; //атака из реплея против защиты в чате
  2739. case 4:
  2740. battle.attackers = repleyBattle.defenders;
  2741. break; //защита из реплея против защиты в чате
  2742. case 5:
  2743. battle.attackers = repleyBattle.attackers;
  2744. battle.defenders[0] = repleyBattle.defenders;
  2745. break; //атака из реплея против защиты из реплея
  2746. case 6:
  2747. battle.attackers = repleyBattle.defenders;
  2748. battle.defenders[0] = repleyBattle.attackers;
  2749. break; //защита из реплея против атаки из реплея
  2750. case 7:
  2751. battle.attackers = repleyBattle.attackers;
  2752. battle.defenders[0] = repleyBattle.attackers;
  2753. break; //атака из реплея против атаки из реплея
  2754. case 8:
  2755. battle.attackers = repleyBattle.defenders;
  2756. battle.defenders[0] = repleyBattle.defenders;
  2757. break; //защита из реплея против защиты из реплея
  2758. }
  2759. }
  2760.  
  2761. isChange = true;
  2762. }
  2763. //тест сохранки
  2764. /**
  2765. * Start of the Asgard boss fight
  2766. * Начало боя с боссом Асгарда
  2767. */
  2768. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2769. lastBossBattleInfo = call.result.response.battle;
  2770. if (isChecked('preCalcBattle')) {
  2771. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2772. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2773. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2774. }
  2775. }
  2776. /**
  2777. * Cancel tutorial
  2778. * Отмена туториала
  2779. */
  2780. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2781. let chains = call.result.response.chains;
  2782. for (let n in chains) {
  2783. chains[n] = 9999;
  2784. }
  2785. isChange = true;
  2786. }
  2787. /**
  2788. * Opening keys and spheres of titan artifacts
  2789. * Открытие ключей и сфер артефактов титанов
  2790. */
  2791. if (artifactChestOpen &&
  2792. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2793. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2794. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2795.  
  2796. reward.forEach(e => {
  2797. for (let f in e) {
  2798. if (!allReward[f]) {
  2799. allReward[f] = {};
  2800. }
  2801. for (let o in e[f]) {
  2802. if (!allReward[f][o]) {
  2803. allReward[f][o] = e[f][o];
  2804. countTypeReward++;
  2805. } else {
  2806. allReward[f][o] += e[f][o];
  2807. }
  2808. }
  2809. }
  2810. });
  2811.  
  2812. if (!call.ident.includes(artifactChestOpenCallName)) {
  2813. mainReward = call.result.response;
  2814. }
  2815. }
  2816.  
  2817. if (countTypeReward > 20) {
  2818. correctShowOpenArtifact = 3;
  2819. } else {
  2820. correctShowOpenArtifact = 0;
  2821. }
  2822.  
  2823. /**
  2824. * Sum the result of opening Pet Eggs
  2825. * Суммирование результата открытия яиц питомцев
  2826. */
  2827. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2828. const rewards = call.result.response.rewards;
  2829. rewards.forEach(e => {
  2830. for (let f in e) {
  2831. if (!allReward[f]) {
  2832. allReward[f] = {};
  2833. }
  2834. for (let o in e[f]) {
  2835. if (!allReward[f][o]) {
  2836. allReward[f][o] = e[f][o];
  2837. } else {
  2838. allReward[f][o] += e[f][o];
  2839. }
  2840. }
  2841. }
  2842. });
  2843. call.result.response.rewards = [allReward];
  2844. isChange = true;
  2845. }
  2846. /**
  2847. * Auto-repeat opening matryoshkas
  2848. * АвтоПовтор открытия матрешек
  2849. */
  2850. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2851. let lootBox = call.result.response;
  2852. let newCount = 0;
  2853. for (let n of lootBox) {
  2854. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2855. newCount += n.consumable[lastRussianDollId]
  2856. }
  2857. }
  2858. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2859. { msg: I18N('BTN_OPEN'), result: true},
  2860. { msg: I18N('BTN_NO'), result: false},
  2861. ])) {
  2862. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2863. lootBox = [...lootBox, ...recursionResult];
  2864. }
  2865.  
  2866. /** Объединение результата лутбоксов */
  2867. const allLootBox = {};
  2868. lootBox.forEach(e => {
  2869. for (let f in e) {
  2870. if (!allLootBox[f]) {
  2871. if (typeof e[f] == 'object') {
  2872. allLootBox[f] = {};
  2873. } else {
  2874. allLootBox[f] = 0;
  2875. }
  2876. }
  2877. if (typeof e[f] == 'object') {
  2878. for (let o in e[f]) {
  2879. if (newCount && o == lastRussianDollId) {
  2880. continue;
  2881. }
  2882. if (!allLootBox[f][o]) {
  2883. allLootBox[f][o] = e[f][o];
  2884. } else {
  2885. allLootBox[f][o] += e[f][o];
  2886. }
  2887. }
  2888. } else {
  2889. allLootBox[f] += e[f];
  2890. }
  2891. }
  2892. });
  2893. /** Разбитие результата */
  2894. const output = [];
  2895. const maxCount = 5;
  2896. let currentObj = {};
  2897. let count = 0;
  2898. for (let f in allLootBox) {
  2899. if (!currentObj[f]) {
  2900. if (typeof allLootBox[f] == 'object') {
  2901. for (let o in allLootBox[f]) {
  2902. currentObj[f] ||= {}
  2903. if (!currentObj[f][o]) {
  2904. currentObj[f][o] = allLootBox[f][o];
  2905. count++;
  2906. if (count === maxCount) {
  2907. output.push(currentObj);
  2908. currentObj = {};
  2909. count = 0;
  2910. }
  2911. }
  2912. }
  2913. } else {
  2914. currentObj[f] = allLootBox[f];
  2915. count++;
  2916. if (count === maxCount) {
  2917. output.push(currentObj);
  2918. currentObj = {};
  2919. count = 0;
  2920. }
  2921. }
  2922. }
  2923. }
  2924. if (count > 0) {
  2925. output.push(currentObj);
  2926. }
  2927.  
  2928. console.log(output);
  2929. call.result.response = output;
  2930. isChange = true;
  2931. }
  2932. /**
  2933. * Dungeon recalculation (fix endless cards)
  2934. * Прерасчет подземки (исправление бесконечных карт)
  2935. */
  2936. if (call.ident == callsIdent['dungeonStartBattle']) {
  2937. lastDungeonBattleData = call.result.response;
  2938. lastDungeonBattleStart = Date.now();
  2939. }
  2940. /**
  2941. * Getting the number of prediction cards
  2942. * Получение количества карт предсказаний
  2943. */
  2944. if (call.ident == callsIdent['inventoryGet']) {
  2945. countPredictionCard = call.result.response.consumable[81] || 0;
  2946. }
  2947. /**
  2948. * Getting subscription status
  2949. * Получение состояния подписки
  2950. */
  2951. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2952. const subscription = call.result.response.subscription;
  2953. if (subscription) {
  2954. subEndTime = subscription.endTime * 1000;
  2955. }
  2956. }
  2957. /**
  2958. * Getting prediction cards
  2959. * Получение карт предсказаний
  2960. */
  2961. if (call.ident == callsIdent['questFarm']) {
  2962. const consumable = call.result.response?.consumable;
  2963. if (consumable && consumable[81]) {
  2964. countPredictionCard += consumable[81];
  2965. console.log(`Cards: ${countPredictionCard}`);
  2966. }
  2967. }
  2968. /**
  2969. * Hiding extra servers
  2970. * Скрытие лишних серверов
  2971. */
  2972. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2973. let servers = call.result.response.users.map(s => s.serverId)
  2974. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2975. isChange = true;
  2976. }
  2977. /**
  2978. * Displays player positions in the adventure
  2979. * Отображает позиции игроков в приключении
  2980. */
  2981. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2982. const users = Object.values(call.result.response.users);
  2983. const mapIdent = call.result.response.mapIdent;
  2984. const adventureId = call.result.response.adventureId;
  2985. const maps = {
  2986. adv_strongford_3pl_hell: 9,
  2987. adv_valley_3pl_hell: 10,
  2988. adv_ghirwil_3pl_hell: 11,
  2989. adv_angels_3pl_hell: 12,
  2990. }
  2991. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  2992. msg += '<br>' + I18N('PLAYER_POS');
  2993. for (const user of users) {
  2994. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2995. }
  2996. setProgress(msg, false, hideProgress);
  2997. }
  2998. /**
  2999. * Automatic launch of a raid at the end of the adventure
  3000. * Автоматический запуск рейда при окончании приключения
  3001. */
  3002. if (call.ident == callsIdent['adventure_end']) {
  3003. autoRaidAdventure()
  3004. }
  3005. /** Удаление лавки редкостей */
  3006. if (call.ident == callsIdent['missionRaid']) {
  3007. if (call.result?.heroesMerchant) {
  3008. delete call.result.heroesMerchant;
  3009. isChange = true;
  3010. }
  3011. }
  3012. /** missionTimer */
  3013. if (call.ident == callsIdent['missionStart']) {
  3014. missionBattle = call.result.response;
  3015. }
  3016. }
  3017.  
  3018. if (mainReward && artifactChestOpen) {
  3019. console.log(allReward);
  3020. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3021. artifactChestOpen = false;
  3022. artifactChestOpenCallName = '';
  3023. isChange = true;
  3024. }
  3025. } catch(err) {
  3026. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3027. }
  3028.  
  3029. if (isChange) {
  3030. Object.defineProperty(this, 'responseText', {
  3031. writable: true
  3032. });
  3033. this.responseText = JSON.stringify(respond);
  3034. }
  3035. }
  3036.  
  3037. /** Добавляет в бой эффекты усиления*/
  3038. function addBuff(battle) {
  3039. let effects = battle.effects;
  3040. let buffType = getInput('needResource2');
  3041. if (-1 < buffType && buffType < 7) {
  3042. let percentBuff = getInput('needResource');
  3043. effects.defenders = {};
  3044. effects.defenders[buffs[buffType]] = percentBuff;
  3045. } else if (buffType.slice(0, 1) == "-" || isChecked('treningBattle')) {
  3046. buffType = parseInt(buffType.slice(1), 10);
  3047. effects.defenders = repleyBattle.effects;
  3048. battle.defenders[0] = repleyBattle.defenders;
  3049. let def = battle.defenders[0];
  3050. if (buffType == 1) {
  3051. for (let i in def) {
  3052. let state = def[i].state;
  3053. state.hp = state.maxHp;
  3054. state.energy = 0;
  3055. state.isDead = false;
  3056. }
  3057. } else if (buffType == 2 || isChecked('finishingBattle')) {
  3058. for (let i in def) {
  3059. let state = def[i].state;
  3060. let rState = repleyBattle.state[i];
  3061. if (!!rState) {
  3062. state.hp = rState.hp;
  3063. state.energy = rState.energy;
  3064. state.isDead = rState.isDead;
  3065. } else {
  3066. state.hp = 0;
  3067. state.energy = 0;
  3068. state.isDead = true;
  3069. }
  3070. }
  3071. }
  3072. }
  3073. }
  3074. const buffs = ['percentBuffAll_allAttacks', 'percentBuffAll_armor', 'percentBuffAll_magicResist', 'percentBuffAll_physicalAttack', 'percentBuffAll_magicPower', 'percentDamageBuff_dot', 'percentBuffAll_healing', 'percentBuffAllForFallenAllies', 'percentBuffAll_energyIncrease', 'percentIncomeDamageReduce_any', 'percentIncomeDamageReduce_physical', 'percentIncomeDamageReduce_magic', 'percentIncomeDamageReduce_dot', 'percentBuffHp', 'percentBuffByPerk_energyIncrease_8', 'percentBuffByPerk_energyIncrease_5', 'percentBuffByPerk_energyIncrease_4', 'percentBuffByPerk_allAttacks_5', 'percentBuffByPerk_allAttacks_4', 'percentBuffByPerk_allAttacks_9', 'percentBuffByPerk_castSpeed_7', 'percentBuffByPerk_castSpeed_6', 'percentBuffByPerk_castSpeed_10', 'percentBuffByPerk_armorPenetration_6', 'percentBuffByPerk_physicalAttack_6', 'percentBuffByPerk_armorPenetration_10', 'percentBuffByPerk_physicalAttack_10', 'percentBuffByPerk_magicPower_7', 'percentDamageBuff_any','percentDamageBuff_physical','percentDamageBuff_magic','corruptedBoss_25_80_1_100_10','tutorialPetUlt_1.2','tutorialBossPercentDamage_1','corruptedBoss_50_80_1_100_10','corruptedBoss_75_80_1_100_10','corruptedBoss_80_80_1_100_10','percentBuffByPerk_castSpeed_4','percentBuffByPerk_energyIncrease_7','percentBuffByPerk_castSpeed_9','percentBuffByPerk_castSpeed_8','bossStageBuff_1000000_20000','bossStageBuff_1500000_30000','bossStageBuff_2000000_40000','bossStageBuff_3000000_50000','bossStageBuff_4000000_60000','bossStageBuff_5000000_70000','bossStageBuff_7500000_80000','bossStageBuff_11000000_90000','bossStageBuff_15000000_100000','bossStageBuff_20000000_120000','bossStageBuff_30000000_150000','bossStageBuff_40000000_200000','bossStageBuff_50000000_250000','percentBuffPet_strength','percentBuffPet_castSpeed','percentBuffPet_petEnergyIncrease','stormPowerBuff_100_1000','stormPowerBuff_100','changeStarSphereIncomingDamage_any','changeBlackHoleDamage','buffSpeedWhenStarfall','changeTeamStartEnergy','decreaseStarSphereDamage','avoidAllBlackholeDamageOnce','groveKeeperAvoidBlackholeDamageChance_3','undeadPreventsNightmares_3','engeneerIncreaseStarMachineIncomingDamage_3','overloadHealDamageStarSphere','nightmareDeathGiveLifesteal_100','starfallIncreaseAllyHeal_9_100','decreaseStarSphereDamage_4','increaseNightmaresIncomingDamageByCount','debuffNightmareOnSpawnFrom_7_hp','damageNightmareGiveEnergy','ultEnergyCompensationOnPlanetParade_6','bestDamagerBeforeParadeGetsImprovedBuff_any','starSphereDeathGiveEnergy','bestDamagerOnParadeBecomesImmortal_any','preventNightmare','buffStatWithHealing_physicalAttack_magic_100','buffStatWithHealing_magicPower_physical_100','buffStatWithHealing_hp_dot_100','replaceHealingWithDamage_magic','critWithRetaliation_10_dot','posessionWithBuffStat_25_20_5_10','energyBurnDamageWithEffect_magic_Silence_5_5','percentBuffHp','percentBuffAll_energyIncrease','percentBuffAll_magicResist','percentBuffAll_armor','percentIncomeDamageReduce_any','percentBuffAll_healing','percentIncomeDamageReduce_any','percentBuffHp','percentBuffAll_energyIncrease','percentIncomeDamageReduce_any','percentBuffHp','percentBuffByPerk_castSpeed_All','percentBuffAll_castSpeed'];
  3075.  
  3076. /**
  3077. * Request an answer to a question
  3078. *
  3079. * Запрос ответа на вопрос
  3080. */
  3081. async function getAnswer(question) {
  3082. const now = Date.now();
  3083. const body = JSON.stringify({ ...question, now });
  3084. const signature = window['\x73\x69\x67\x6e'](now);
  3085. return new Promise((resolve, reject) => {
  3086. fetch('https://zingery.ru/heroes/getAnswer.php', {
  3087. method: 'POST',
  3088. headers: {
  3089. 'X-Request-Signature': signature,
  3090. 'X-Script-Name': GM_info.script.name,
  3091. 'X-Script-Version': GM_info.script.version,
  3092. 'X-Script-Author': GM_info.script.author,
  3093. },
  3094. body,
  3095. }).then(
  3096. response => response.json()
  3097. ).then(
  3098. data => {
  3099. if (data.result) {
  3100. resolve(data.result);
  3101. } else {
  3102. resolve(false);
  3103. }
  3104. }
  3105. ).catch((error) => {
  3106. console.error(error);
  3107. resolve(false);
  3108. });
  3109. })
  3110. }
  3111.  
  3112. /**
  3113. * Submitting a question and answer to a database
  3114. *
  3115. * Отправка вопроса и ответа в базу данных
  3116. */
  3117. function sendAnswerInfo(answerInfo) {
  3118. fetch('https://zingery.ru/heroes/setAnswer.php', {
  3119. method: 'POST',
  3120. body: JSON.stringify(answerInfo)
  3121. }).then(
  3122. response => response.json()
  3123. ).then(
  3124. data => {
  3125. if (data.result) {
  3126. console.log(I18N('SENT_QUESTION'));
  3127. }
  3128. }
  3129. )
  3130. }
  3131.  
  3132. /**
  3133. * Returns the battle type by preset type
  3134. *
  3135. * Возвращает тип боя по типу пресета
  3136. */
  3137. function getBattleType(strBattleType) {
  3138. if (strBattleType.includes("invasion")) {
  3139. return "get_invasion";
  3140. }
  3141. if (strBattleType.includes("boss")) {
  3142. return "get_boss";
  3143. }
  3144. switch (strBattleType) {
  3145. case "invasion":
  3146. return "get_invasion";
  3147. case "titan_pvp_manual":
  3148. return "get_titanPvpManual";
  3149. case "titan_pvp":
  3150. return "get_titanPvp";
  3151. case "titan_clan_pvp":
  3152. case "clan_pvp_titan":
  3153. case "clan_global_pvp_titan":
  3154. case "brawl_titan":
  3155. case "challenge_titan":
  3156. return "get_titanClanPvp";
  3157. case "clan_raid": // Asgard Boss // Босс асгарда
  3158. case "adventure": // Adventures // Приключения
  3159. case "clan_global_pvp":
  3160. case "clan_pvp":
  3161. return "get_clanPvp";
  3162. case "dungeon_titan":
  3163. case "titan_tower":
  3164. return "get_titan";
  3165. case "tower":
  3166. case "clan_dungeon":
  3167. return "get_tower";
  3168. case "pve":
  3169. return "get_pve";
  3170. case "pvp_manual":
  3171. return "get_pvpManual";
  3172. case "grand":
  3173. case "arena":
  3174. case "pvp":
  3175. case "challenge":
  3176. return "get_pvp";
  3177. case "core":
  3178. return "get_core";
  3179. case "boss_10":
  3180. case "boss_11":
  3181. case "boss_12":
  3182. return "get_boss";
  3183. default:
  3184. return "get_clanPvp";
  3185. }
  3186. }
  3187. /**
  3188. * Returns the class name of the passed object
  3189. *
  3190. * Возвращает название класса переданного объекта
  3191. */
  3192. function getClass(obj) {
  3193. return {}.toString.call(obj).slice(8, -1);
  3194. }
  3195. /**
  3196. * Calculates the request signature
  3197. *
  3198. * Расчитывает сигнатуру запроса
  3199. */
  3200. this.getSignature = function(headers, data) {
  3201. const sign = {
  3202. signature: '',
  3203. length: 0,
  3204. add: function (text) {
  3205. this.signature += text;
  3206. if (this.length < this.signature.length) {
  3207. this.length = 3 * (this.signature.length + 1) >> 1;
  3208. }
  3209. },
  3210. }
  3211. sign.add(headers["X-Request-Id"]);
  3212. sign.add(':');
  3213. sign.add(headers["X-Auth-Token"]);
  3214. sign.add(':');
  3215. sign.add(headers["X-Auth-Session-Id"]);
  3216. sign.add(':');
  3217. sign.add(data);
  3218. sign.add(':');
  3219. sign.add('LIBRARY-VERSION=1');
  3220. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3221.  
  3222. return md5(sign.signature);
  3223. }
  3224. /**
  3225. * Creates an interface
  3226. *
  3227. * Создает интерфейс
  3228. */
  3229. function createInterface() {
  3230. scriptMenu.init({
  3231. showMenu: true
  3232. });
  3233. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3234. scriptMenu.addHeader('v' + GM_info.script.version);
  3235. }
  3236.  
  3237. function addControls() {
  3238. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3239. for (let name in checkboxes) {
  3240. if (checkboxes[name].hide) {
  3241. continue;
  3242. }
  3243. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3244. /**
  3245. * Getting the state of checkboxes from storage
  3246. * Получаем состояние чекбоксов из storage
  3247. */
  3248. let val = storage.get(name, null);
  3249. if (val != null) {
  3250. checkboxes[name].cbox.checked = val;
  3251. } else {
  3252. storage.set(name, checkboxes[name].default);
  3253. checkboxes[name].cbox.checked = checkboxes[name].default;
  3254. }
  3255. /**
  3256. * Tracing the change event of the checkbox for writing to storage
  3257. * Отсеживание события изменения чекбокса для записи в storage
  3258. */
  3259. checkboxes[name].cbox.dataset['name'] = name;
  3260. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3261. const nameCheckbox = this.dataset['name'];
  3262. /*
  3263. if (this.checked && nameCheckbox == 'cancelBattle') {
  3264. this.checked = false;
  3265. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3266. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3267. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3268. ])) {
  3269. return;
  3270. }
  3271. this.checked = true;
  3272. }
  3273. */
  3274. storage.set(nameCheckbox, this.checked);
  3275. })
  3276. }
  3277.  
  3278. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3279. for (let name in inputs) {
  3280. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3281. /**
  3282. * Get inputText state from storage
  3283. * Получаем состояние inputText из storage
  3284. */
  3285. let val = storage.get(name, null);
  3286. if (val != null) {
  3287. inputs[name].input.value = val;
  3288. } else {
  3289. storage.set(name, inputs[name].default);
  3290. inputs[name].input.value = inputs[name].default;
  3291. }
  3292. /**
  3293. * Tracing a field change event for a record in storage
  3294. * Отсеживание события изменения поля для записи в storage
  3295. */
  3296. inputs[name].input.dataset['name'] = name;
  3297. inputs[name].input.addEventListener('input', function () {
  3298. const inputName = this.dataset['name'];
  3299. let value = +this.value;
  3300. if (!value || Number.isNaN(value)) {
  3301. value = storage.get(inputName, inputs[inputName].default);
  3302. inputs[name].input.value = value;
  3303. }
  3304. storage.set(inputName, value);
  3305. })
  3306. }
  3307. const inputDetails2 = scriptMenu.addDetails(I18N('SAVING'));
  3308. for (let name in inputs2) {
  3309. inputs2[name].input = scriptMenu.addInputText(inputs2[name].title, false, inputDetails2);
  3310. /**
  3311. * Get inputText state from storage
  3312. * Получаем состояние inputText из storage
  3313. */
  3314. let val = storage.get(name, null);
  3315. if (val != null) {
  3316. inputs2[name].input.value = val;
  3317. } else {
  3318. storage.set(name, inputs2[name].default);
  3319. inputs2[name].input.value = inputs2[name].default;
  3320. }
  3321. /**
  3322. * Tracing a field change event for a record in storage
  3323. * Отсеживание события изменения поля для записи в storage
  3324. */
  3325. inputs2[name].input.dataset['name'] = name;
  3326. inputs2[name].input.addEventListener('input', function () {
  3327. const inputName = this.dataset['name'];
  3328. let value = +this.value;
  3329. if (!value || Number.isNaN(value)) {
  3330. value = storage.get(inputName, inputs2[inputName].default);
  3331. inputs2[name].input.value = value;
  3332. }
  3333. storage.set(inputName, value);
  3334. })
  3335. }
  3336. /* const inputDetails3 = scriptMenu.addDetails(I18N('USER_ID'));
  3337. for (let name in inputs3) {
  3338. inputs3[name].input = scriptMenu.addInputText(inputs3[name].title, false, inputDetails3);
  3339. /**
  3340. * Get inputText state from storage
  3341. * Получаем состояние inputText из storage
  3342. *
  3343. let val = storage.get(name, null);
  3344. if (val != null) {
  3345. inputs3[name].input.value = val;
  3346. } else {
  3347. storage.set(name, inputs3[name].default);
  3348. inputs3[name].input.value = inputs3[name].default;
  3349. }
  3350. /**
  3351. * Tracing a field change event for a record in storage
  3352. * Отсеживание события изменения поля для записи в storage
  3353. *
  3354. inputs3[name].input.dataset['name'] = name;
  3355. inputs3[name].input.addEventListener('input', function () {
  3356. const inputName = this.dataset['name'];
  3357. let value = +this.value;
  3358. if (!value || Number.isNaN(value)) {
  3359. value = storage.get(inputName, inputs3[inputName].default);
  3360. inputs3[name].input.value = value;
  3361. }
  3362. storage.set(inputName, value);
  3363. })
  3364. }*/
  3365. }
  3366.  
  3367. /**
  3368. * Sending a request
  3369. *
  3370. * Отправка запроса
  3371. */
  3372. function send(json, callback, pr) {
  3373. if (typeof json == 'string') {
  3374. json = JSON.parse(json);
  3375. }
  3376. for (const call of json.calls) {
  3377. if (!call?.context?.actionTs) {
  3378. call.context = {
  3379. actionTs: performance.now()
  3380. }
  3381. }
  3382. }
  3383. json = JSON.stringify(json);
  3384. /**
  3385. * We get the headlines of the previous intercepted request
  3386. * Получаем заголовки предыдущего перехваченого запроса
  3387. */
  3388. let headers = lastHeaders;
  3389. /**
  3390. * We increase the header of the query Certifier by 1
  3391. * Увеличиваем заголовок идетификатора запроса на 1
  3392. */
  3393. headers["X-Request-Id"]++;
  3394. /**
  3395. * We calculate the title with the signature
  3396. * Расчитываем заголовок с сигнатурой
  3397. */
  3398. headers["X-Auth-Signature"] = getSignature(headers, json);
  3399. /**
  3400. * Create a new ajax request
  3401. * Создаем новый AJAX запрос
  3402. */
  3403. let xhr = new XMLHttpRequest;
  3404. /**
  3405. * Indicate the previously saved URL for API queries
  3406. * Указываем ранее сохраненный URL для API запросов
  3407. */
  3408. xhr.open('POST', apiUrl, true);
  3409. /**
  3410. * Add the function to the event change event
  3411. * Добавляем функцию к событию смены статуса запроса
  3412. */
  3413. xhr.onreadystatechange = function() {
  3414. /**
  3415. * If the result of the request is obtained, we call the flask function
  3416. * Если результат запроса получен вызываем колбек функцию
  3417. */
  3418. if(xhr.readyState == 4) {
  3419. let randTimeout = Math.random() * 200 + 200;
  3420. setTimeout(callback, randTimeout, xhr.response, pr);
  3421. }
  3422. };
  3423. /**
  3424. * Indicate the type of request
  3425. * Указываем тип запроса
  3426. */
  3427. xhr.responseType = 'json';
  3428. /**
  3429. * We set the request headers
  3430. * Задаем заголовки запроса
  3431. */
  3432. for(let nameHeader in headers) {
  3433. let head = headers[nameHeader];
  3434. xhr.setRequestHeader(nameHeader, head);
  3435. }
  3436. /**
  3437. * Sending a request
  3438. * Отправляем запрос
  3439. */
  3440. xhr.send(json);
  3441. }
  3442.  
  3443. let hideTimeoutProgress = 0;
  3444. /**
  3445. * Hide progress
  3446. *
  3447. * Скрыть прогресс
  3448. */
  3449. function hideProgress(timeout) {
  3450. timeout = timeout || 0;
  3451. clearTimeout(hideTimeoutProgress);
  3452. hideTimeoutProgress = setTimeout(function () {
  3453. scriptMenu.setStatus('');
  3454. }, timeout);
  3455. }
  3456. /**
  3457. * Progress display
  3458. *
  3459. * Отображение прогресса
  3460. */
  3461. function setProgress(text, hide, onclick) {
  3462. scriptMenu.setStatus(text, onclick);
  3463. hide = hide || false;
  3464. if (hide) {
  3465. hideProgress(3000);
  3466. }
  3467. }
  3468.  
  3469. /**
  3470. * Returns the timer value depending on the subscription
  3471. *
  3472. * Возвращает значение таймера в зависимости от подписки
  3473. */
  3474. function getTimer(time) {
  3475. let speedDiv = 5;
  3476. if (subEndTime < Date.now()) {
  3477. speedDiv = 1.5;
  3478. }
  3479. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3480. }
  3481.  
  3482. /**
  3483. * Calculates HASH MD5 from string
  3484. *
  3485. * Расчитывает HASH MD5 из строки
  3486. *
  3487. * [js-md5]{@link https://github.com/emn178/js-md5}
  3488. *
  3489. * @namespace md5
  3490. * @version 0.7.3
  3491. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3492. * @copyright Chen, Yi-Cyuan 2014-2017
  3493. * @license MIT
  3494. */
  3495. !function(){"use strict";function t(t){if(t)d[0]=d[16]=d[1]=d[2]=d[3]=d[4]=d[5]=d[6]=d[7]=d[8]=d[9]=d[10]=d[11]=d[12]=d[13]=d[14]=d[15]=0,this.blocks=d,this.buffer8=l;else if(a){var r=new ArrayBuffer(68);this.buffer8=new Uint8Array(r),this.blocks=new Uint32Array(r)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var r="input is invalid type",e="object"==typeof window,i=e?window:{};i.JS_MD5_NO_WINDOW&&(e=!1);var s=!e&&"object"==typeof self,h=!i.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;h?i=global:s&&(i=self);var f=!i.JS_MD5_NO_COMMON_JS&&"object"==typeof module&&module.exports,o="function"==typeof define&&define.amd,a=!i.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,n="0123456789abcdef".split(""),u=[128,32768,8388608,-2147483648],y=[0,8,16,24],c=["hex","array","digest","buffer","arrayBuffer","base64"],p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),d=[],l;if(a){var A=new ArrayBuffer(68);l=new Uint8Array(A),d=new Uint32Array(A)}!i.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),!a||!i.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(t){return"object"==typeof t&&t.buffer&&t.buffer.constructor===ArrayBuffer});var b=function(r){return function(e){return new t(!0).update(e)[r]()}},v=function(){var r=b("hex");h&&(r=w(r)),r.create=function(){return new t},r.update=function(t){return r.create().update(t)};for(var e=0;e<c.length;++e){var i=c[e];r[i]=b(i)}return r},w=function(t){var e=eval("require('crypto')"),i=eval("require('buffer').Buffer"),s=function(s){if("string"==typeof s)return e.createHash("md5").update(s,"utf8").digest("hex");if(null===s||void 0===s)throw r;return s.constructor===ArrayBuffer&&(s=new Uint8Array(s)),Array.isArray(s)||ArrayBuffer.isView(s)||s.constructor===i?e.createHash("md5").update(new i(s)).digest("hex"):t(s)};return s};t.prototype.update=function(t){if(!this.finalized){var e,i=typeof t;if("string"!==i){if("object"!==i)throw r;if(null===t)throw r;if(a&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!(Array.isArray(t)||a&&ArrayBuffer.isView(t)))throw r;e=!0}for(var s,h,f=0,o=t.length,n=this.blocks,u=this.buffer8;f<o;){if(this.hashed&&(this.hashed=!1,n[0]=n[16],n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),e)if(a)for(h=this.start;f<o&&h<64;++f)u[h++]=t[f];else for(h=this.start;f<o&&h<64;++f)n[h>>2]|=t[f]<<y[3&h++];else if(a)for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?u[h++]=s:s<2048?(u[h++]=192|s>>6,u[h++]=128|63&s):s<55296||s>=57344?(u[h++]=224|s>>12,u[h++]=128|s>>6&63,u[h++]=128|63&s):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),u[h++]=240|s>>18,u[h++]=128|s>>12&63,u[h++]=128|s>>6&63,u[h++]=128|63&s);else for(h=this.start;f<o&&h<64;++f)(s=t.charCodeAt(f))<128?n[h>>2]|=s<<y[3&h++]:s<2048?(n[h>>2]|=(192|s>>6)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):s<55296||s>=57344?(n[h>>2]|=(224|s>>12)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]):(s=65536+((1023&s)<<10|1023&t.charCodeAt(++f)),n[h>>2]|=(240|s>>18)<<y[3&h++],n[h>>2]|=(128|s>>12&63)<<y[3&h++],n[h>>2]|=(128|s>>6&63)<<y[3&h++],n[h>>2]|=(128|63&s)<<y[3&h++]);this.lastByteIndex=h,this.bytes+=h-this.start,h>=64?(this.start=h-64,this.hash(),this.hashed=!0):this.start=h}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},t.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,r=this.lastByteIndex;t[r>>2]|=u[3&r],r>=56&&(this.hashed||this.hash(),t[0]=t[16],t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.bytes<<3,t[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},t.prototype.hash=function(){var t,r,e,i,s,h,f=this.blocks;this.first?r=((r=((t=((t=f[0]-680876937)<<7|t>>>25)-271733879<<0)^(e=((e=(-271733879^(i=((i=(-1732584194^2004318071&t)+f[1]-117830708)<<12|i>>>20)+t<<0)&(-271733879^t))+f[2]-1126478375)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1316259209)<<22|r>>>10)+e<<0:(t=this.h0,r=this.h1,e=this.h2,r=((r+=((t=((t+=((i=this.h3)^r&(e^i))+f[0]-680876936)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[1]-389564586)<<12|i>>>20)+t<<0)&(t^r))+f[2]+606105819)<<17|e>>>15)+i<<0)&(i^t))+f[3]-1044525330)<<22|r>>>10)+e<<0),r=((r+=((t=((t+=(i^r&(e^i))+f[4]-176418897)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[5]+1200080426)<<12|i>>>20)+t<<0)&(t^r))+f[6]-1473231341)<<17|e>>>15)+i<<0)&(i^t))+f[7]-45705983)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[8]+1770035416)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[9]-1958414417)<<12|i>>>20)+t<<0)&(t^r))+f[10]-42063)<<17|e>>>15)+i<<0)&(i^t))+f[11]-1990404162)<<22|r>>>10)+e<<0,r=((r+=((t=((t+=(i^r&(e^i))+f[12]+1804603682)<<7|t>>>25)+r<<0)^(e=((e+=(r^(i=((i+=(e^t&(r^e))+f[13]-40341101)<<12|i>>>20)+t<<0)&(t^r))+f[14]-1502002290)<<17|e>>>15)+i<<0)&(i^t))+f[15]+1236535329)<<22|r>>>10)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[1]-165796510)<<5|t>>>27)+r<<0)^r))+f[6]-1069501632)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[11]+643717713)<<14|e>>>18)+i<<0)^i))+f[0]-373897302)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[5]-701558691)<<5|t>>>27)+r<<0)^r))+f[10]+38016083)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[15]-660478335)<<14|e>>>18)+i<<0)^i))+f[4]-405537848)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[9]+568446438)<<5|t>>>27)+r<<0)^r))+f[14]-1019803690)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[3]-187363961)<<14|e>>>18)+i<<0)^i))+f[8]+1163531501)<<20|r>>>12)+e<<0,r=((r+=((i=((i+=(r^e&((t=((t+=(e^i&(r^e))+f[13]-1444681467)<<5|t>>>27)+r<<0)^r))+f[2]-51403784)<<9|i>>>23)+t<<0)^t&((e=((e+=(t^r&(i^t))+f[7]+1735328473)<<14|e>>>18)+i<<0)^i))+f[12]-1926607734)<<20|r>>>12)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[5]-378558)<<4|t>>>28)+r<<0))+f[8]-2022574463)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[11]+1839030562)<<16|e>>>16)+i<<0))+f[14]-35309556)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[1]-1530992060)<<4|t>>>28)+r<<0))+f[4]+1272893353)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[7]-155497632)<<16|e>>>16)+i<<0))+f[10]-1094730640)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[13]+681279174)<<4|t>>>28)+r<<0))+f[0]-358537222)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[3]-722521979)<<16|e>>>16)+i<<0))+f[6]+76029189)<<23|r>>>9)+e<<0,r=((r+=((h=(i=((i+=((s=r^e)^(t=((t+=(s^i)+f[9]-640364487)<<4|t>>>28)+r<<0))+f[12]-421815835)<<11|i>>>21)+t<<0)^t)^(e=((e+=(h^r)+f[15]+530742520)<<16|e>>>16)+i<<0))+f[2]-995338651)<<23|r>>>9)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[0]-198630844)<<6|t>>>26)+r<<0)|~e))+f[7]+1126891415)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[14]-1416354905)<<15|e>>>17)+i<<0)|~t))+f[5]-57434055)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[12]+1700485571)<<6|t>>>26)+r<<0)|~e))+f[3]-1894986606)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[10]-1051523)<<15|e>>>17)+i<<0)|~t))+f[1]-2054922799)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[8]+1873313359)<<6|t>>>26)+r<<0)|~e))+f[15]-30611744)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[6]-1560198380)<<15|e>>>17)+i<<0)|~t))+f[13]+1309151649)<<21|r>>>11)+e<<0,r=((r+=((i=((i+=(r^((t=((t+=(e^(r|~i))+f[4]-145523070)<<6|t>>>26)+r<<0)|~e))+f[11]-1120210379)<<10|i>>>22)+t<<0)^((e=((e+=(t^(i|~r))+f[2]+718787259)<<15|e>>>17)+i<<0)|~t))+f[9]-343485551)<<21|r>>>11)+e<<0,this.first?(this.h0=t+1732584193<<0,this.h1=r-271733879<<0,this.h2=e-1732584194<<0,this.h3=i+271733878<<0,this.first=!1):(this.h0=this.h0+t<<0,this.h1=this.h1+r<<0,this.h2=this.h2+e<<0,this.h3=this.h3+i<<0)},t.prototype.hex=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return n[t>>4&15]+n[15&t]+n[t>>12&15]+n[t>>8&15]+n[t>>20&15]+n[t>>16&15]+n[t>>28&15]+n[t>>24&15]+n[r>>4&15]+n[15&r]+n[r>>12&15]+n[r>>8&15]+n[r>>20&15]+n[r>>16&15]+n[r>>28&15]+n[r>>24&15]+n[e>>4&15]+n[15&e]+n[e>>12&15]+n[e>>8&15]+n[e>>20&15]+n[e>>16&15]+n[e>>28&15]+n[e>>24&15]+n[i>>4&15]+n[15&i]+n[i>>12&15]+n[i>>8&15]+n[i>>20&15]+n[i>>16&15]+n[i>>28&15]+n[i>>24&15]},t.prototype.toString=t.prototype.hex,t.prototype.digest=function(){this.finalize();var t=this.h0,r=this.h1,e=this.h2,i=this.h3;return[255&t,t>>8&255,t>>16&255,t>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&e,e>>8&255,e>>16&255,e>>24&255,255&i,i>>8&255,i>>16&255,i>>24&255]},t.prototype.array=t.prototype.digest,t.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(16),r=new Uint32Array(t);return r[0]=this.h0,r[1]=this.h1,r[2]=this.h2,r[3]=this.h3,t},t.prototype.buffer=t.prototype.arrayBuffer,t.prototype.base64=function(){for(var t,r,e,i="",s=this.array(),h=0;h<15;)t=s[h++],r=s[h++],e=s[h++],i+=p[t>>>2]+p[63&(t<<4|r>>>4)]+p[63&(r<<2|e>>>6)]+p[63&e];return t=s[h],i+=p[t>>>2]+p[t<<4&63]+"=="};var _=v();f?module.exports=_:(i.md5=_,o&&define(function(){return _}))}();
  3496.  
  3497. /**
  3498. * Script for beautiful dialog boxes
  3499. *
  3500. * Скрипт для красивых диалоговых окошек
  3501. */
  3502. const popup = new (function () {
  3503. this.popUp,
  3504. this.downer,
  3505. this.middle,
  3506. this.msgText,
  3507. this.buttons = [];
  3508. this.checkboxes = [];
  3509. this.dialogPromice = null;
  3510.  
  3511. function init() {
  3512. addStyle();
  3513. addBlocks();
  3514. addEventListeners();
  3515. }
  3516.  
  3517. const addEventListeners = () => {
  3518. document.addEventListener('keyup', (e) => {
  3519. if (e.key == 'Escape') {
  3520. if (this.dialogPromice) {
  3521. const { func, result } = this.dialogPromice;
  3522. this.dialogPromice = null;
  3523. popup.hide();
  3524. func(result);
  3525. }
  3526. }
  3527. });
  3528. }
  3529.  
  3530. const addStyle = () => {
  3531. let style = document.createElement('style');
  3532. style.innerText = `
  3533. .PopUp_ {
  3534. position: absolute;
  3535. min-width: 300px;
  3536. max-width: 500px;
  3537. max-height: 600px;
  3538. background-color: #190e08e6;
  3539. z-index: 10001;
  3540. top: 169px;
  3541. left: 345px;
  3542. border: 3px #ce9767 solid;
  3543. border-radius: 10px;
  3544. display: flex;
  3545. flex-direction: column;
  3546. justify-content: space-around;
  3547. padding: 15px 9px;
  3548. box-sizing: border-box;
  3549. }
  3550.  
  3551. .PopUp_back {
  3552. position: absolute;
  3553. background-color: #00000066;
  3554. width: 100%;
  3555. height: 100%;
  3556. z-index: 10000;
  3557. top: 0;
  3558. left: 0;
  3559. }
  3560.  
  3561. .PopUp_close {
  3562. width: 40px;
  3563. height: 40px;
  3564. position: absolute;
  3565. right: -18px;
  3566. top: -18px;
  3567. border: 3px solid #c18550;
  3568. border-radius: 20px;
  3569. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3570. background-position-y: 3px;
  3571. box-shadow: -1px 1px 3px black;
  3572. cursor: pointer;
  3573. box-sizing: border-box;
  3574. }
  3575.  
  3576. .PopUp_close:hover {
  3577. filter: brightness(1.2);
  3578. }
  3579.  
  3580. .PopUp_crossClose {
  3581. width: 100%;
  3582. height: 100%;
  3583. background-size: 65%;
  3584. background-position: center;
  3585. background-repeat: no-repeat;
  3586. 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")
  3587. }
  3588.  
  3589. .PopUp_blocks {
  3590. width: 100%;
  3591. height: 50%;
  3592. display: flex;
  3593. justify-content: space-evenly;
  3594. align-items: center;
  3595. flex-wrap: wrap;
  3596. justify-content: center;
  3597. }
  3598.  
  3599. .PopUp_blocks:last-child {
  3600. margin-top: 25px;
  3601. }
  3602.  
  3603. .PopUp_buttons {
  3604. display: flex;
  3605. margin: 7px 10px;
  3606. flex-direction: column;
  3607. }
  3608.  
  3609. .PopUp_button {
  3610. background-color: #52A81C;
  3611. border-radius: 5px;
  3612. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3613. cursor: pointer;
  3614. padding: 4px 12px 6px;
  3615. }
  3616.  
  3617. .PopUp_input {
  3618. text-align: center;
  3619. font-size: 16px;
  3620. height: 27px;
  3621. border: 1px solid #cf9250;
  3622. border-radius: 9px 9px 0px 0px;
  3623. background: transparent;
  3624. color: #fce1ac;
  3625. padding: 1px 10px;
  3626. box-sizing: border-box;
  3627. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3628. }
  3629.  
  3630. .PopUp_checkboxes {
  3631. display: flex;
  3632. flex-direction: column;
  3633. margin: 15px 15px -5px 15px;
  3634. align-items: flex-start;
  3635. }
  3636.  
  3637. .PopUp_ContCheckbox {
  3638. margin: 2px 0px;
  3639. }
  3640.  
  3641. .PopUp_checkbox {
  3642. position: absolute;
  3643. z-index: -1;
  3644. opacity: 0;
  3645. }
  3646. .PopUp_checkbox+label {
  3647. display: inline-flex;
  3648. align-items: center;
  3649. user-select: none;
  3650.  
  3651. font-size: 15px;
  3652. font-family: sans-serif;
  3653. font-weight: 600;
  3654. font-stretch: condensed;
  3655. letter-spacing: 1px;
  3656. color: #fce1ac;
  3657. text-shadow: 0px 0px 1px;
  3658. }
  3659. .PopUp_checkbox+label::before {
  3660. content: '';
  3661. display: inline-block;
  3662. width: 20px;
  3663. height: 20px;
  3664. border: 1px solid #cf9250;
  3665. border-radius: 7px;
  3666. margin-right: 7px;
  3667. }
  3668. .PopUp_checkbox:checked+label::before {
  3669. 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");
  3670. }
  3671.  
  3672. .PopUp_input::placeholder {
  3673. color: #fce1ac75;
  3674. }
  3675.  
  3676. .PopUp_input:focus {
  3677. outline: 0;
  3678. }
  3679.  
  3680. .PopUp_input + .PopUp_button {
  3681. border-radius: 0px 0px 5px 5px;
  3682. padding: 2px 18px 5px;
  3683. }
  3684.  
  3685. .PopUp_button:hover {
  3686. filter: brightness(1.2);
  3687. }
  3688.  
  3689. .PopUp_button:active {
  3690. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3691. }
  3692.  
  3693. .PopUp_text {
  3694. font-size: 22px;
  3695. font-family: sans-serif;
  3696. font-weight: 600;
  3697. font-stretch: condensed;
  3698. white-space: pre-wrap;
  3699. letter-spacing: 1px;
  3700. text-align: center;
  3701. }
  3702.  
  3703. .PopUp_buttonText {
  3704. color: #E4FF4C;
  3705. text-shadow: 0px 1px 2px black;
  3706. }
  3707.  
  3708. .PopUp_msgText {
  3709. color: #FDE5B6;
  3710. text-shadow: 0px 0px 2px;
  3711. }
  3712.  
  3713. .PopUp_hideBlock {
  3714. display: none;
  3715. }
  3716. `;
  3717. document.head.appendChild(style);
  3718. }
  3719.  
  3720. const addBlocks = () => {
  3721. this.back = document.createElement('div');
  3722. this.back.classList.add('PopUp_back');
  3723. this.back.classList.add('PopUp_hideBlock');
  3724. document.body.append(this.back);
  3725.  
  3726. this.popUp = document.createElement('div');
  3727. this.popUp.classList.add('PopUp_');
  3728. this.back.append(this.popUp);
  3729.  
  3730. let upper = document.createElement('div')
  3731. upper.classList.add('PopUp_blocks');
  3732. this.popUp.append(upper);
  3733.  
  3734. this.middle = document.createElement('div')
  3735. this.middle.classList.add('PopUp_blocks');
  3736. this.middle.classList.add('PopUp_checkboxes');
  3737. this.popUp.append(this.middle);
  3738.  
  3739. this.downer = document.createElement('div')
  3740. this.downer.classList.add('PopUp_blocks');
  3741. this.popUp.append(this.downer);
  3742.  
  3743. this.msgText = document.createElement('div');
  3744. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3745. upper.append(this.msgText);
  3746. }
  3747.  
  3748. this.showBack = function () {
  3749. this.back.classList.remove('PopUp_hideBlock');
  3750. }
  3751.  
  3752. this.hideBack = function () {
  3753. this.back.classList.add('PopUp_hideBlock');
  3754. }
  3755.  
  3756. this.show = function () {
  3757. if (this.checkboxes.length) {
  3758. this.middle.classList.remove('PopUp_hideBlock');
  3759. }
  3760. this.showBack();
  3761. this.popUp.classList.remove('PopUp_hideBlock');
  3762. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3763. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3764. }
  3765.  
  3766. this.hide = function () {
  3767. this.hideBack();
  3768. this.popUp.classList.add('PopUp_hideBlock');
  3769. }
  3770.  
  3771. this.addAnyButton = (option) => {
  3772. const contButton = document.createElement('div');
  3773. contButton.classList.add('PopUp_buttons');
  3774. this.downer.append(contButton);
  3775.  
  3776. let inputField = {
  3777. value: option.result || option.default
  3778. }
  3779. if (option.isInput) {
  3780. inputField = document.createElement('input');
  3781. inputField.type = 'text';
  3782. if (option.placeholder) {
  3783. inputField.placeholder = option.placeholder;
  3784. }
  3785. if (option.default) {
  3786. inputField.value = option.default;
  3787. }
  3788. inputField.classList.add('PopUp_input');
  3789. contButton.append(inputField);
  3790. }
  3791.  
  3792. const button = document.createElement('div');
  3793. button.classList.add('PopUp_button');
  3794. button.title = option.title || '';
  3795. contButton.append(button);
  3796.  
  3797. const buttonText = document.createElement('div');
  3798. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3799. buttonText.innerText = option.msg;
  3800. button.append(buttonText);
  3801.  
  3802. return { button, contButton, inputField };
  3803. }
  3804.  
  3805. this.addCloseButton = () => {
  3806. let button = document.createElement('div')
  3807. button.classList.add('PopUp_close');
  3808. this.popUp.append(button);
  3809.  
  3810. let crossClose = document.createElement('div')
  3811. crossClose.classList.add('PopUp_crossClose');
  3812. button.append(crossClose);
  3813.  
  3814. return { button, contButton: button };
  3815. }
  3816.  
  3817. this.addButton = (option, buttonClick) => {
  3818.  
  3819. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3820. if (option.isClose) {
  3821. this.dialogPromice = {func: buttonClick, result: option.result};
  3822. }
  3823. button.addEventListener('click', () => {
  3824. let result = '';
  3825. if (option.isInput) {
  3826. result = inputField.value;
  3827. }
  3828. if (option.isClose || option.isCancel) {
  3829. this.dialogPromice = null;
  3830. }
  3831. buttonClick(result);
  3832. });
  3833.  
  3834. this.buttons.push(contButton);
  3835. }
  3836.  
  3837. this.clearButtons = () => {
  3838. while (this.buttons.length) {
  3839. this.buttons.pop().remove();
  3840. }
  3841. }
  3842.  
  3843. this.addCheckBox = (checkBox) => {
  3844. const contCheckbox = document.createElement('div');
  3845. contCheckbox.classList.add('PopUp_ContCheckbox');
  3846. this.middle.append(contCheckbox);
  3847.  
  3848. const checkbox = document.createElement('input');
  3849. checkbox.type = 'checkbox';
  3850. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3851. checkbox.dataset.name = checkBox.name;
  3852. checkbox.checked = checkBox.checked;
  3853. checkbox.label = checkBox.label;
  3854. checkbox.title = checkBox.title || '';
  3855. checkbox.classList.add('PopUp_checkbox');
  3856. contCheckbox.appendChild(checkbox)
  3857.  
  3858. const checkboxLabel = document.createElement('label');
  3859. checkboxLabel.innerText = checkBox.label;
  3860. checkboxLabel.title = checkBox.title || '';
  3861. checkboxLabel.setAttribute('for', checkbox.id);
  3862. contCheckbox.appendChild(checkboxLabel);
  3863.  
  3864. this.checkboxes.push(checkbox);
  3865. }
  3866.  
  3867. this.clearCheckBox = () => {
  3868. this.middle.classList.add('PopUp_hideBlock');
  3869. while (this.checkboxes.length) {
  3870. this.checkboxes.pop().parentNode.remove();
  3871. }
  3872. }
  3873.  
  3874. this.setMsgText = (text) => {
  3875. this.msgText.innerHTML = text;
  3876. }
  3877.  
  3878. this.getCheckBoxes = () => {
  3879. const checkBoxes = [];
  3880.  
  3881. for (const checkBox of this.checkboxes) {
  3882. checkBoxes.push({
  3883. name: checkBox.dataset.name,
  3884. label: checkBox.label,
  3885. checked: checkBox.checked
  3886. });
  3887. }
  3888.  
  3889. return checkBoxes;
  3890. }
  3891.  
  3892. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3893. this.clearButtons();
  3894. this.clearCheckBox();
  3895. return new Promise((complete, failed) => {
  3896. this.setMsgText(msg);
  3897. if (!buttOpt) {
  3898. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3899. }
  3900. for (const checkBox of checkBoxes) {
  3901. this.addCheckBox(checkBox);
  3902. }
  3903. for (let butt of buttOpt) {
  3904. this.addButton(butt, (result) => {
  3905. result = result || butt.result;
  3906. complete(result);
  3907. popup.hide();
  3908. });
  3909. if (butt.isCancel) {
  3910. this.dialogPromice = {func: complete, result: butt.result};
  3911. }
  3912. }
  3913. this.show();
  3914. });
  3915. }
  3916.  
  3917. document.addEventListener('DOMContentLoaded', init);
  3918. });
  3919.  
  3920. /**
  3921. * Script control panel
  3922. *
  3923. * Панель управления скриптом
  3924. */
  3925. const scriptMenu = new (function () {
  3926.  
  3927. this.mainMenu,
  3928. this.buttons = [],
  3929. this.checkboxes = [];
  3930. this.option = {
  3931. showMenu: false,
  3932. showDetails: {}
  3933. };
  3934.  
  3935. this.init = function (option = {}) {
  3936. this.option = Object.assign(this.option, option);
  3937. this.option.showDetails = this.loadShowDetails();
  3938. addStyle();
  3939. addBlocks();
  3940. }
  3941.  
  3942. const addStyle = () => {
  3943. style = document.createElement('style');
  3944. style.innerText = `
  3945. .scriptMenu_status {
  3946. position: absolute;
  3947. z-index: 10001;
  3948. white-space: pre-wrap; //тест для выравнивания кнопок
  3949. /* max-height: 30px; */
  3950. top: -1px;
  3951. left: 30%;
  3952. cursor: pointer;
  3953. border-radius: 0px 0px 10px 10px;
  3954. background: #190e08e6;
  3955. border: 1px #ce9767 solid;
  3956. font-size: 18px;
  3957. font-family: sans-serif;
  3958. font-weight: 600;
  3959. font-stretch: condensed;
  3960. letter-spacing: 1px;
  3961. color: #fce1ac;
  3962. text-shadow: 0px 0px 1px;
  3963. transition: 0.5s;
  3964. padding: 2px 10px 3px;
  3965. }
  3966. .scriptMenu_statusHide {
  3967. top: -35px;
  3968. height: 30px;
  3969. overflow: hidden;
  3970. }
  3971. .scriptMenu_label {
  3972. position: absolute;
  3973. top: 30%;
  3974. left: -4px;
  3975. z-index: 9999;
  3976. cursor: pointer;
  3977. width: 30px;
  3978. height: 30px;
  3979. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3980. border: 1px solid #1a2f04;
  3981. border-radius: 5px;
  3982. box-shadow:
  3983. inset 0px 2px 4px #83ce26,
  3984. inset 0px -4px 6px #1a2f04,
  3985. 0px 0px 2px black,
  3986. 0px 0px 0px 2px #ce9767;
  3987. }
  3988. .scriptMenu_label:hover {
  3989. filter: brightness(1.2);
  3990. }
  3991. .scriptMenu_arrowLabel {
  3992. width: 100%;
  3993. height: 100%;
  3994. background-size: 75%;
  3995. background-position: center;
  3996. background-repeat: no-repeat;
  3997. 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");
  3998. box-shadow: 0px 1px 2px #000;
  3999. border-radius: 5px;
  4000. filter: drop-shadow(0px 1px 2px #000D);
  4001. }
  4002. .scriptMenu_main {
  4003. position: absolute;
  4004. max-width: 285px;
  4005. z-index: 9999;
  4006. top: 50%;
  4007. transform: translateY(-40%);
  4008. background: #190e08e6;
  4009. border: 1px #ce9767 solid;
  4010. border-radius: 0px 10px 10px 0px;
  4011. border-left: none;
  4012. padding: 5px 10px 5px 5px;
  4013. box-sizing: border-box;
  4014. font-size: 15px;
  4015. font-family: sans-serif;
  4016. font-weight: 600;
  4017. font-stretch: condensed;
  4018. letter-spacing: 1px;
  4019. color: #fce1ac;
  4020. text-shadow: 0px 0px 1px;
  4021. transition: 1s;
  4022. display: flex;
  4023. flex-direction: column;
  4024. flex-wrap: nowrap;
  4025. }
  4026. .scriptMenu_showMenu {
  4027. display: none;
  4028. }
  4029. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4030. left: 0px;
  4031. }
  4032. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4033. left: -300px;
  4034. }
  4035. .scriptMenu_divInput {
  4036. margin: 2px;
  4037. }
  4038. .scriptMenu_divInputText {
  4039. margin: 2px;
  4040. align-self: center;
  4041. display: flex;
  4042. }
  4043. .scriptMenu_checkbox {
  4044. position: absolute;
  4045. z-index: -1;
  4046. opacity: 0;
  4047. }
  4048. .scriptMenu_checkbox+label {
  4049. display: inline-flex;
  4050. align-items: center;
  4051. user-select: none;
  4052. }
  4053. .scriptMenu_checkbox+label::before {
  4054. content: '';
  4055. display: inline-block;
  4056. width: 20px;
  4057. height: 20px;
  4058. border: 1px solid #cf9250;
  4059. border-radius: 7px;
  4060. margin-right: 7px;
  4061. }
  4062. .scriptMenu_checkbox:checked+label::before {
  4063. 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");
  4064. }
  4065. .scriptMenu_close {
  4066. width: 40px;
  4067. height: 40px;
  4068. position: absolute;
  4069. right: -18px;
  4070. top: -18px;
  4071. border: 3px solid #c18550;
  4072. border-radius: 20px;
  4073. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4074. background-position-y: 3px;
  4075. box-shadow: -1px 1px 3px black;
  4076. cursor: pointer;
  4077. box-sizing: border-box;
  4078. }
  4079. .scriptMenu_close:hover {
  4080. filter: brightness(1.2);
  4081. }
  4082. .scriptMenu_crossClose {
  4083. width: 100%;
  4084. height: 100%;
  4085. background-size: 65%;
  4086. background-position: center;
  4087. background-repeat: no-repeat;
  4088. 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")
  4089. }
  4090. .scriptMenu_button {
  4091. user-select: none;
  4092. border-radius: 5px;
  4093. cursor: pointer;
  4094. padding: 5px 14px 8px;
  4095. margin: 4px;
  4096. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4097. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4098. }
  4099. .scriptMenu_button:hover {
  4100. filter: brightness(1.2);
  4101. }
  4102. .scriptMenu_button:active {
  4103. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4104. }
  4105. .scriptMenu_buttonText {
  4106. color: #fce5b7;
  4107. text-shadow: 0px 1px 2px black;
  4108. text-align: center;
  4109. }
  4110. .scriptMenu_header {
  4111. text-align: center;
  4112. align-self: center;
  4113. font-size: 15px;
  4114. margin: 0px 15px;
  4115. }
  4116. .scriptMenu_header a {
  4117. color: #fce5b7;
  4118. text-decoration: none;
  4119. }
  4120. .scriptMenu_InputText {
  4121. text-align: center;
  4122. width: 130px;
  4123. height: 24px;
  4124. border: 1px solid #cf9250;
  4125. border-radius: 9px;
  4126. background: transparent;
  4127. color: #fce1ac;
  4128. padding: 0px 10px;
  4129. box-sizing: border-box;
  4130. }
  4131. .scriptMenu_InputText:focus {
  4132. filter: brightness(1.2);
  4133. outline: 0;
  4134. }
  4135. .scriptMenu_InputText::placeholder {
  4136. color: #fce1ac75;
  4137. }
  4138. .scriptMenu_Summary {
  4139. cursor: pointer;
  4140. margin-left: 7px;
  4141. }
  4142. .scriptMenu_Details {
  4143. align-self: center;
  4144. }
  4145. `;
  4146. document.head.appendChild(style);
  4147. }
  4148.  
  4149. const addBlocks = () => {
  4150. const main = document.createElement('div');
  4151. document.body.appendChild(main);
  4152.  
  4153. this.status = document.createElement('div');
  4154. this.status.classList.add('scriptMenu_status');
  4155. this.setStatus('');
  4156. main.appendChild(this.status);
  4157.  
  4158. const label = document.createElement('label');
  4159. label.classList.add('scriptMenu_label');
  4160. label.setAttribute('for', 'checkbox_showMenu');
  4161. main.appendChild(label);
  4162.  
  4163. const arrowLabel = document.createElement('div');
  4164. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4165. label.appendChild(arrowLabel);
  4166.  
  4167. const checkbox = document.createElement('input');
  4168. checkbox.type = 'checkbox';
  4169. checkbox.id = 'checkbox_showMenu';
  4170. checkbox.checked = this.option.showMenu;
  4171. checkbox.classList.add('scriptMenu_showMenu');
  4172. main.appendChild(checkbox);
  4173.  
  4174. this.mainMenu = document.createElement('div');
  4175. this.mainMenu.classList.add('scriptMenu_main');
  4176. main.appendChild(this.mainMenu);
  4177.  
  4178. const closeButton = document.createElement('label');
  4179. closeButton.classList.add('scriptMenu_close');
  4180. closeButton.setAttribute('for', 'checkbox_showMenu');
  4181. this.mainMenu.appendChild(closeButton);
  4182.  
  4183. const crossClose = document.createElement('div');
  4184. crossClose.classList.add('scriptMenu_crossClose');
  4185. closeButton.appendChild(crossClose);
  4186. }
  4187.  
  4188. this.setStatus = (text, onclick) => {
  4189. if (!text) {
  4190. this.status.classList.add('scriptMenu_statusHide');
  4191. } else {
  4192. this.status.classList.remove('scriptMenu_statusHide');
  4193. this.status.innerHTML = text;
  4194. }
  4195.  
  4196. if (typeof onclick == 'function') {
  4197. this.status.addEventListener("click", onclick, {
  4198. once: true
  4199. });
  4200. }
  4201. }
  4202.  
  4203. /**
  4204. * Adding a text element
  4205. *
  4206. * Добавление текстового элемента
  4207. * @param {String} text text // текст
  4208. * @param {Function} func Click function // функция по клику
  4209. * @param {HTMLDivElement} main parent // родитель
  4210. */
  4211. this.addHeader = (text, func, main) => {
  4212. main = main || this.mainMenu;
  4213. const header = document.createElement('div');
  4214. header.classList.add('scriptMenu_header');
  4215. header.innerHTML = text;
  4216. if (typeof func == 'function') {
  4217. header.addEventListener('click', func);
  4218. }
  4219. main.appendChild(header);
  4220. }
  4221.  
  4222. /**
  4223. * Adding a button
  4224. *
  4225. * Добавление кнопки
  4226. * @param {String} text
  4227. * @param {Function} func
  4228. * @param {String} title
  4229. * @param {HTMLDivElement} main parent // родитель
  4230. */
  4231. this.addButton = (text, func, title, main) => {
  4232. main = main || this.mainMenu;
  4233. const button = document.createElement('div');
  4234. button.classList.add('scriptMenu_button');
  4235. button.title = title;
  4236. button.addEventListener('click', func);
  4237. main.appendChild(button);
  4238.  
  4239. const buttonText = document.createElement('div');
  4240. buttonText.classList.add('scriptMenu_buttonText');
  4241. buttonText.innerText = text;
  4242. button.appendChild(buttonText);
  4243. this.buttons.push(button);
  4244.  
  4245. return button;
  4246. }
  4247.  
  4248. /**
  4249. * Adding checkbox
  4250. *
  4251. * Добавление чекбокса
  4252. * @param {String} label
  4253. * @param {String} title
  4254. * @param {HTMLDivElement} main parent // родитель
  4255. * @returns
  4256. */
  4257. this.addCheckbox = (label, title, main) => {
  4258. main = main || this.mainMenu;
  4259. const divCheckbox = document.createElement('div');
  4260. divCheckbox.classList.add('scriptMenu_divInput');
  4261. divCheckbox.title = title;
  4262. main.appendChild(divCheckbox);
  4263.  
  4264. const checkbox = document.createElement('input');
  4265. checkbox.type = 'checkbox';
  4266. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4267. checkbox.classList.add('scriptMenu_checkbox');
  4268. divCheckbox.appendChild(checkbox)
  4269.  
  4270. const checkboxLabel = document.createElement('label');
  4271. checkboxLabel.innerText = label;
  4272. checkboxLabel.setAttribute('for', checkbox.id);
  4273. divCheckbox.appendChild(checkboxLabel);
  4274.  
  4275. this.checkboxes.push(checkbox);
  4276. return checkbox;
  4277. }
  4278.  
  4279. /**
  4280. * Adding input field
  4281. *
  4282. * Добавление поля ввода
  4283. * @param {String} title
  4284. * @param {String} placeholder
  4285. * @param {HTMLDivElement} main parent // родитель
  4286. * @returns
  4287. */
  4288. this.addInputText = (title, placeholder, main) => {
  4289. main = main || this.mainMenu;
  4290. const divInputText = document.createElement('div');
  4291. divInputText.classList.add('scriptMenu_divInputText');
  4292. divInputText.title = title;
  4293. main.appendChild(divInputText);
  4294.  
  4295. const newInputText = document.createElement('input');
  4296. newInputText.type = 'text';
  4297. if (placeholder) {
  4298. newInputText.placeholder = placeholder;
  4299. }
  4300. newInputText.classList.add('scriptMenu_InputText');
  4301. divInputText.appendChild(newInputText)
  4302. return newInputText;
  4303. }
  4304.  
  4305. /**
  4306. * Adds a dropdown block
  4307. *
  4308. * Добавляет раскрывающийся блок
  4309. * @param {String} summary
  4310. * @param {String} name
  4311. * @returns
  4312. */
  4313. this.addDetails = (summaryText, name = null) => {
  4314. const details = document.createElement('details');
  4315. details.classList.add('scriptMenu_Details');
  4316. this.mainMenu.appendChild(details);
  4317.  
  4318. const summary = document.createElement('summary');
  4319. summary.classList.add('scriptMenu_Summary');
  4320. summary.innerText = summaryText;
  4321. if (name) {
  4322. const self = this;
  4323. details.open = this.option.showDetails[name];
  4324. details.dataset.name = name;
  4325. summary.addEventListener('click', () => {
  4326. self.option.showDetails[details.dataset.name] = !details.open;
  4327. self.saveShowDetails(self.option.showDetails);
  4328. });
  4329. }
  4330. details.appendChild(summary);
  4331.  
  4332. return details;
  4333. }
  4334.  
  4335. /**
  4336. * Saving the expanded state of the details blocks
  4337. *
  4338. * Сохранение состояния развенутости блоков details
  4339. * @param {*} value
  4340. */
  4341. this.saveShowDetails = (value) => {
  4342. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4343. }
  4344.  
  4345. /**
  4346. * Loading the state of expanded blocks details
  4347. *
  4348. * Загрузка состояния развенутости блоков details
  4349. * @returns
  4350. */
  4351. this.loadShowDetails = () => {
  4352. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4353.  
  4354. if (!showDetails) {
  4355. return {};
  4356. }
  4357.  
  4358. try {
  4359. showDetails = JSON.parse(showDetails);
  4360. } catch (e) {
  4361. return {};
  4362. }
  4363.  
  4364. return showDetails;
  4365. }
  4366. });
  4367.  
  4368. /**
  4369. * Пример использования
  4370. scriptMenu.init();
  4371. scriptMenu.addHeader('v1.508');
  4372. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4373. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4374. scriptMenu.addInputText('input подсказака');
  4375. */
  4376. /**
  4377. * Game Library
  4378. *
  4379. * Игровая библиотека
  4380. */
  4381. class Library {
  4382. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4383.  
  4384. constructor() {
  4385. if (!Library.instance) {
  4386. Library.instance = this;
  4387. }
  4388.  
  4389. return Library.instance;
  4390. }
  4391.  
  4392. async load() {
  4393. try {
  4394. await this.getUrlLib();
  4395. console.log(this.defaultLibUrl);
  4396. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4397. } catch (error) {
  4398. console.error('Не удалось загрузить библиотеку', error)
  4399. }
  4400. }
  4401.  
  4402. async getUrlLib() {
  4403. try {
  4404. const db = new Database('hw_cache', 'cache');
  4405. await db.open();
  4406. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4407. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4408. } catch(e) {}
  4409. }
  4410.  
  4411. getData(id) {
  4412. return this.data[id];
  4413. }
  4414. }
  4415.  
  4416. this.lib = new Library();
  4417. /**
  4418. * Database
  4419. *
  4420. * База данных
  4421. */
  4422. class Database {
  4423. constructor(dbName, storeName) {
  4424. this.dbName = dbName;
  4425. this.storeName = storeName;
  4426. this.db = null;
  4427. }
  4428.  
  4429. async open() {
  4430. return new Promise((resolve, reject) => {
  4431. const request = indexedDB.open(this.dbName);
  4432.  
  4433. request.onerror = () => {
  4434. reject(new Error(`Failed to open database ${this.dbName}`));
  4435. };
  4436.  
  4437. request.onsuccess = () => {
  4438. this.db = request.result;
  4439. resolve();
  4440. };
  4441.  
  4442. request.onupgradeneeded = (event) => {
  4443. const db = event.target.result;
  4444. if (!db.objectStoreNames.contains(this.storeName)) {
  4445. db.createObjectStore(this.storeName);
  4446. }
  4447. };
  4448. });
  4449. }
  4450.  
  4451. async set(key, value) {
  4452. return new Promise((resolve, reject) => {
  4453. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4454. const store = transaction.objectStore(this.storeName);
  4455. const request = store.put(value, key);
  4456.  
  4457. request.onerror = () => {
  4458. reject(new Error(`Failed to save value with key ${key}`));
  4459. };
  4460.  
  4461. request.onsuccess = () => {
  4462. resolve();
  4463. };
  4464. });
  4465. }
  4466.  
  4467. async get(key, def) {
  4468. return new Promise((resolve, reject) => {
  4469. const transaction = this.db.transaction([this.storeName], 'readonly');
  4470. const store = transaction.objectStore(this.storeName);
  4471. const request = store.get(key);
  4472.  
  4473. request.onerror = () => {
  4474. resolve(def);
  4475. };
  4476.  
  4477. request.onsuccess = () => {
  4478. resolve(request.result);
  4479. };
  4480. });
  4481. }
  4482.  
  4483. async delete(key) {
  4484. return new Promise((resolve, reject) => {
  4485. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4486. const store = transaction.objectStore(this.storeName);
  4487. const request = store.delete(key);
  4488.  
  4489. request.onerror = () => {
  4490. reject(new Error(`Failed to delete value with key ${key}`));
  4491. };
  4492.  
  4493. request.onsuccess = () => {
  4494. resolve();
  4495. };
  4496. });
  4497. }
  4498. }
  4499.  
  4500. /**
  4501. * Returns the stored value
  4502. *
  4503. * Возвращает сохраненное значение
  4504. */
  4505. function getSaveVal(saveName, def) {
  4506. const result = storage.get(saveName, def);
  4507. return result;
  4508. }
  4509.  
  4510. /**
  4511. * Stores value
  4512. *
  4513. * Сохраняет значение
  4514. */
  4515. function setSaveVal(saveName, value) {
  4516. storage.set(saveName, value);
  4517. }
  4518.  
  4519. /**
  4520. * Database initialization
  4521. *
  4522. * Инициализация базы данных
  4523. */
  4524. const db = new Database(GM_info.script.name, 'settings');
  4525.  
  4526. /**
  4527. * Data store
  4528. *
  4529. * Хранилище данных
  4530. */
  4531. const storage = {
  4532. userId: 0,
  4533. /**
  4534. * Default values
  4535. *
  4536. * Значения по умолчанию
  4537. */
  4538. values: [
  4539. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4540. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4541. ...Object.entries(inputs2).map(e => ({ [e[0]]: e[1].default })),
  4542. //...Object.entries(inputs3).map(e => ({ [e[0]]: e[1].default })),
  4543. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4544. name: GM_info.script.name,
  4545. get: function (key, def) {
  4546. if (key in this.values) {
  4547. return this.values[key];
  4548. }
  4549. return def;
  4550. },
  4551. set: function (key, value) {
  4552. this.values[key] = value;
  4553. db.set(this.userId, this.values).catch(
  4554. e => null
  4555. );
  4556. localStorage[this.name + ':' + key] = value;
  4557. },
  4558. delete: function (key) {
  4559. delete this.values[key];
  4560. db.set(this.userId, this.values);
  4561. delete localStorage[this.name + ':' + key];
  4562. }
  4563. }
  4564.  
  4565. /**
  4566. * Returns all keys from localStorage that start with prefix (for migration)
  4567. *
  4568. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4569. */
  4570. function getAllValuesStartingWith(prefix) {
  4571. const values = [];
  4572. for (let i = 0; i < localStorage.length; i++) {
  4573. const key = localStorage.key(i);
  4574. if (key.startsWith(prefix)) {
  4575. const val = localStorage.getItem(key);
  4576. const keyValue = key.split(':')[1];
  4577. values.push({ key: keyValue, val });
  4578. }
  4579. }
  4580. return values;
  4581. }
  4582.  
  4583. /**
  4584. * Opens or migrates to a database
  4585. *
  4586. * Открывает или мигрирует в базу данных
  4587. */
  4588. async function openOrMigrateDatabase(userId) {
  4589. storage.userId = userId;
  4590. try {
  4591. await db.open();
  4592. } catch(e) {
  4593. return;
  4594. }
  4595. let settings = await db.get(userId, false);
  4596.  
  4597. if (settings) {
  4598. storage.values = settings;
  4599. return;
  4600. }
  4601.  
  4602. const values = getAllValuesStartingWith(GM_info.script.name);
  4603. for (const value of values) {
  4604. let val = null;
  4605. try {
  4606. val = JSON.parse(value.val);
  4607. } catch {
  4608. break;
  4609. }
  4610. storage.values[value.key] = val;
  4611. }
  4612. await db.set(userId, storage.values);
  4613. }
  4614.  
  4615. /**
  4616. * Sending expeditions
  4617. *
  4618. * Отправка экспедиций
  4619. */
  4620. function checkExpedition() {
  4621. return new Promise((resolve, reject) => {
  4622. const expedition = new Expedition(resolve, reject);
  4623. expedition.start();
  4624. });
  4625. }
  4626.  
  4627. class Expedition {
  4628. checkExpedInfo = {
  4629. calls: [{
  4630. name: "expeditionGet",
  4631. args: {},
  4632. ident: "expeditionGet"
  4633. }, {
  4634. name: "heroGetAll",
  4635. args: {},
  4636. ident: "heroGetAll"
  4637. }]
  4638. }
  4639.  
  4640. constructor(resolve, reject) {
  4641. this.resolve = resolve;
  4642. this.reject = reject;
  4643. }
  4644.  
  4645. async start() {
  4646. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4647.  
  4648. const expedInfo = data.results[0].result.response;
  4649. const dataHeroes = data.results[1].result.response;
  4650. const dataExped = { useHeroes: [], exped: [] };
  4651. const calls = [];
  4652.  
  4653. /**
  4654. * Adding expeditions to collect
  4655. * Добавляем экспедиции для сбора
  4656. */
  4657. for (var n in expedInfo) {
  4658. const exped = expedInfo[n];
  4659. const dateNow = (Date.now() / 1000);
  4660. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4661. calls.push({
  4662. name: "expeditionFarm",
  4663. args: { expeditionId: exped.id },
  4664. ident: "expeditionFarm_" + exped.id
  4665. });
  4666. } else {
  4667. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4668. }
  4669. if (exped.status == 1) {
  4670. dataExped.exped.push({ id: exped.id, power: exped.power });
  4671. }
  4672. }
  4673. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  4674.  
  4675. /**
  4676. * Putting together a list of heroes
  4677. * Собираем список героев
  4678. */
  4679. const heroesArr = [];
  4680. for (let n in dataHeroes) {
  4681. const hero = dataHeroes[n];
  4682. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4683. heroesArr.push({ id: hero.id, power: hero.power })
  4684. }
  4685. }
  4686.  
  4687. /**
  4688. * Adding expeditions to send
  4689. * Добавляем экспедиции для отправки
  4690. */
  4691. heroesArr.sort((a, b) => (a.power - b.power));
  4692. for (const exped of dataExped.exped) {
  4693. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4694. if (heroesIds && heroesIds.length > 4) {
  4695. for (let q in heroesArr) {
  4696. if (heroesIds.includes(heroesArr[q].id)) {
  4697. delete heroesArr[q];
  4698. }
  4699. }
  4700. calls.push({
  4701. name: "expeditionSendHeroes",
  4702. args: {
  4703. expeditionId: exped.id,
  4704. heroes: heroesIds
  4705. },
  4706. ident: "expeditionSendHeroes_" + exped.id
  4707. });
  4708. }
  4709. }
  4710.  
  4711. await Send(JSON.stringify({ calls }));
  4712. this.end();
  4713. }
  4714.  
  4715. /**
  4716. * Selection of heroes for expeditions
  4717. *
  4718. * Подбор героев для экспедиций
  4719. */
  4720. selectionHeroes(heroes, power) {
  4721. const resultHeroers = [];
  4722. const heroesIds = [];
  4723. for (let q = 0; q < 5; q++) {
  4724. for (let i in heroes) {
  4725. let hero = heroes[i];
  4726. if (heroesIds.includes(hero.id)) {
  4727. continue;
  4728. }
  4729.  
  4730. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4731. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4732. if (hero.power > need) {
  4733. resultHeroers.push(hero);
  4734. heroesIds.push(hero.id);
  4735. break;
  4736. }
  4737. }
  4738. }
  4739.  
  4740. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4741. if (summ < power) {
  4742. return false;
  4743. }
  4744. return heroesIds;
  4745. }
  4746.  
  4747. /**
  4748. * Ends expedition script
  4749. *
  4750. * Завершает скрипт экспедиции
  4751. */
  4752. end() {
  4753. setProgress(I18N('EXPEDITIONS_SENT'), true);
  4754. this.resolve()
  4755. }
  4756. }
  4757.  
  4758. /**
  4759. * Walkthrough of the dungeon
  4760. *
  4761. * Прохождение подземелья
  4762. */
  4763. function testDungeon() {
  4764. return new Promise((resolve, reject) => {
  4765. const dung = new executeDungeon(resolve, reject);
  4766. const titanit = getInput('countTitanit');
  4767. dung.start(titanit);
  4768. });
  4769. }
  4770.  
  4771. /**
  4772. * Walkthrough of the dungeon
  4773. *
  4774. * Прохождение подземелья
  4775. */
  4776. function executeDungeon(resolve, reject) {
  4777. dungeonActivity = 0;
  4778. maxDungeonActivity = 150;
  4779.  
  4780. titanGetAll = [];
  4781.  
  4782. teams = {
  4783. heroes: [],
  4784. earth: [],
  4785. fire: [],
  4786. neutral: [],
  4787. water: [],
  4788. }
  4789.  
  4790. titanStats = [];
  4791.  
  4792. titansStates = {};
  4793.  
  4794. callsExecuteDungeon = {
  4795. calls: [{
  4796. name: "dungeonGetInfo",
  4797. args: {},
  4798. ident: "dungeonGetInfo"
  4799. }, {
  4800. name: "teamGetAll",
  4801. args: {},
  4802. ident: "teamGetAll"
  4803. }, {
  4804. name: "teamGetFavor",
  4805. args: {},
  4806. ident: "teamGetFavor"
  4807. }, {
  4808. name: "clanGetInfo",
  4809. args: {},
  4810. ident: "clanGetInfo"
  4811. }, {
  4812. name: "titanGetAll",
  4813. args: {},
  4814. ident: "titanGetAll"
  4815. }, {
  4816. name: "inventoryGet",
  4817. args: {},
  4818. ident: "inventoryGet"
  4819. }]
  4820. }
  4821.  
  4822. this.start = function(titanit) {
  4823. maxDungeonActivity = titanit || getInput('countTitanit');
  4824. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4825. }
  4826.  
  4827. /**
  4828. * Getting data on the dungeon
  4829. *
  4830. * Получаем данные по подземелью
  4831. */
  4832. function startDungeon(e) {
  4833. stopDung = false; // стоп подземка
  4834. res = e.results;
  4835. dungeonGetInfo = res[0].result.response;
  4836. if (!dungeonGetInfo) {
  4837. endDungeon('noDungeon', res);
  4838. return;
  4839. }
  4840. teamGetAll = res[1].result.response;
  4841. teamGetFavor = res[2].result.response;
  4842. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4843. titanGetAll = Object.values(res[4].result.response);
  4844. countPredictionCard = res[5].result.response.consumable[81];
  4845.  
  4846. teams.hero = {
  4847. favor: teamGetFavor.dungeon_hero,
  4848. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4849. teamNum: 0,
  4850. }
  4851. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4852. if (heroPet) {
  4853. teams.hero.pet = heroPet;
  4854. }
  4855.  
  4856. teams.neutral = {
  4857. favor: {},
  4858. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4859. teamNum: 0,
  4860. };
  4861. teams.water = {
  4862. favor: {},
  4863. heroes: getTitanTeam(titanGetAll, 'water'),
  4864. teamNum: 0,
  4865. };
  4866. teams.fire = {
  4867. favor: {},
  4868. heroes: getTitanTeam(titanGetAll, 'fire'),
  4869. teamNum: 0,
  4870. };
  4871. teams.earth = {
  4872. favor: {},
  4873. heroes: getTitanTeam(titanGetAll, 'earth'),
  4874. teamNum: 0,
  4875. };
  4876.  
  4877.  
  4878. checkFloor(dungeonGetInfo);
  4879. }
  4880.  
  4881. function getTitanTeam(titans, type) {
  4882. switch (type) {
  4883. case 'neutral':
  4884. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4885. case 'water':
  4886. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4887. case 'fire':
  4888. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4889. case 'earth':
  4890. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4891. }
  4892. }
  4893.  
  4894. function getNeutralTeam() {
  4895. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4896. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4897. }
  4898.  
  4899. function fixTitanTeam(titans) {
  4900. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4901. return titans;
  4902. }
  4903.  
  4904. /**
  4905. * Checking the floor
  4906. *
  4907. * Проверяем этаж
  4908. */
  4909. async function checkFloor(dungeonInfo) {
  4910. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4911. saveProgress();
  4912. return;
  4913. }
  4914. // console.log(dungeonInfo, dungeonActivity);
  4915. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4916. if (dungeonActivity >= maxDungeonActivity) {
  4917. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4918. return;
  4919. }
  4920. titansStates = dungeonInfo.states.titans;
  4921. titanStats = titanObjToArray(titansStates);
  4922. if (stopDung){
  4923. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  4924. return;
  4925. }
  4926. const floorChoices = dungeonInfo.floor.userData;
  4927. const floorType = dungeonInfo.floorType;
  4928. //const primeElement = dungeonInfo.elements.prime;
  4929. if (floorType == "battle") {
  4930. const calls = [];
  4931. for (let teamNum in floorChoices) {
  4932. attackerType = floorChoices[teamNum].attackerType;
  4933. const args = fixTitanTeam(teams[attackerType]);
  4934. if (attackerType == 'neutral') {
  4935. args.heroes = getNeutralTeam();
  4936. }
  4937. if (!args.heroes.length) {
  4938. continue;
  4939. }
  4940. args.teamNum = teamNum;
  4941. calls.push({
  4942. name: "dungeonStartBattle",
  4943. args,
  4944. ident: "body_" + teamNum
  4945. })
  4946. }
  4947. if (!calls.length) {
  4948. endDungeon('endDungeon', 'All Dead');
  4949. return;
  4950. }
  4951. const battleDatas = await Send(JSON.stringify({ calls }))
  4952. .then(e => e.results.map(n => n.result.response))
  4953. const battleResults = [];
  4954. for (n in battleDatas) {
  4955. battleData = battleDatas[n]
  4956. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4957. battleResults.push(await Calc(battleData).then(result => {
  4958. result.teamNum = n;
  4959. result.attackerType = floorChoices[n].attackerType;
  4960. return result;
  4961. }));
  4962. }
  4963. processingPromises(battleResults)
  4964. }
  4965. }
  4966.  
  4967. function processingPromises(results) {
  4968. let selectBattle = results[0];
  4969. if (results.length < 2) {
  4970. // console.log(selectBattle);
  4971. if (!selectBattle.result.win) {
  4972. endDungeon('dungeonEndBattle\n', selectBattle);
  4973. return;
  4974. }
  4975. endBattle(selectBattle);
  4976. return;
  4977. }
  4978.  
  4979. selectBattle = false;
  4980. let bestState = -1000;
  4981. for (const result of results) {
  4982. const recovery = getState(result);
  4983. if (recovery > bestState) {
  4984. bestState = recovery;
  4985. selectBattle = result
  4986. }
  4987. }
  4988. // console.log(selectBattle.teamNum, results);
  4989. if (!selectBattle || bestState <= -1000) {
  4990. endDungeon('dungeonEndBattle\n', results);
  4991. return;
  4992. }
  4993.  
  4994. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4995. .then(endBattle);
  4996. }
  4997.  
  4998. /**
  4999. * Let's start the fight
  5000. *
  5001. * Начинаем бой
  5002. */
  5003. function startBattle(teamNum, attackerType) {
  5004. return new Promise(function (resolve, reject) {
  5005. args = fixTitanTeam(teams[attackerType]);
  5006. args.teamNum = teamNum;
  5007. if (attackerType == 'neutral') {
  5008. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5009. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5010. }
  5011. startBattleCall = {
  5012. calls: [{
  5013. name: "dungeonStartBattle",
  5014. args,
  5015. ident: "body"
  5016. }]
  5017. }
  5018. send(JSON.stringify(startBattleCall), resultBattle, {
  5019. resolve,
  5020. teamNum,
  5021. attackerType
  5022. });
  5023. });
  5024. }
  5025. /**
  5026. * Returns the result of the battle in a promise
  5027. *
  5028. * Возращает резульат боя в промис
  5029. */
  5030. function resultBattle(resultBattles, args) {
  5031. battleData = resultBattles.results[0].result.response;
  5032. battleType = "get_tower";
  5033. if (battleData.type == "dungeon_titan") {
  5034. battleType = "get_titan";
  5035. }
  5036. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5037. BattleCalc(battleData, battleType, function (result) {
  5038. result.teamNum = args.teamNum;
  5039. result.attackerType = args.attackerType;
  5040. args.resolve(result);
  5041. });
  5042. }
  5043. /**
  5044. * Finishing the fight
  5045. *
  5046. * Заканчиваем бой
  5047. */
  5048. async function endBattle(battleInfo) {
  5049. if (battleInfo.result.win) {
  5050. const args = {
  5051. result: battleInfo.result,
  5052. progress: battleInfo.progress,
  5053. }
  5054. if (countPredictionCard > 0) {
  5055. args.isRaid = true;
  5056. } else {
  5057. const timer = getTimer(battleInfo.battleTime);
  5058. console.log(timer);
  5059. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  5060. }
  5061. const calls = [{
  5062. name: "dungeonEndBattle",
  5063. args,
  5064. ident: "body"
  5065. }];
  5066. lastDungeonBattleData = null;
  5067. send(JSON.stringify({ calls }), resultEndBattle);
  5068. } else {
  5069. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5070. }
  5071. }
  5072.  
  5073. /**
  5074. * Getting and processing battle results
  5075. *
  5076. * Получаем и обрабатываем результаты боя
  5077. */
  5078. function resultEndBattle(e) {
  5079. if ('error' in e) {
  5080. popup.confirm(I18N('ERROR_MSG', {
  5081. name: e.error.name,
  5082. description: e.error.description,
  5083. }));
  5084. endDungeon('errorRequest', e);
  5085. return;
  5086. }
  5087. battleResult = e.results[0].result.response;
  5088. if ('error' in battleResult) {
  5089. endDungeon('errorBattleResult', battleResult);
  5090. return;
  5091. }
  5092. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5093. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5094. checkFloor(dungeonGetInfo);
  5095. }
  5096.  
  5097. /**
  5098. * Returns the coefficient of condition of the
  5099. * difference in titanium before and after the battle
  5100. *
  5101. * Возвращает коэффициент состояния титанов после боя
  5102. */
  5103. function getState(result) {
  5104. if (!result.result.win) {
  5105. return -1000;
  5106. }
  5107.  
  5108. let beforeSumFactor = 0;
  5109. const beforeTitans = result.battleData.attackers;
  5110. for (let titanId in beforeTitans) {
  5111. const titan = beforeTitans[titanId];
  5112. const state = titan.state;
  5113. let factor = 1;
  5114. if (state) {
  5115. const hp = state.hp / titan.hp;
  5116. const energy = state.energy / 1e3;
  5117. factor = hp + energy / 20
  5118. }
  5119. beforeSumFactor += factor;
  5120. }
  5121.  
  5122. let afterSumFactor = 0;
  5123. const afterTitans = result.progress[0].attackers.heroes;
  5124. for (let titanId in afterTitans) {
  5125. const titan = afterTitans[titanId];
  5126. const hp = titan.hp / beforeTitans[titanId].hp;
  5127. const energy = titan.energy / 1e3;
  5128. const factor = hp + energy / 20;
  5129. afterSumFactor += factor;
  5130. }
  5131. return afterSumFactor - beforeSumFactor;
  5132. }
  5133.  
  5134. /**
  5135. * Converts an object with IDs to an array with IDs
  5136. *
  5137. * Преобразует объект с идетификаторами в массив с идетификаторами
  5138. */
  5139. function titanObjToArray(obj) {
  5140. let titans = [];
  5141. for (let id in obj) {
  5142. obj[id].id = id;
  5143. titans.push(obj[id]);
  5144. }
  5145. return titans;
  5146. }
  5147.  
  5148. function saveProgress() {
  5149. let saveProgressCall = {
  5150. calls: [{
  5151. name: "dungeonSaveProgress",
  5152. args: {},
  5153. ident: "body"
  5154. }]
  5155. }
  5156. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5157. }
  5158.  
  5159. function endDungeon(reason, info) {
  5160. console.warn(reason, info);
  5161. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5162. resolve();
  5163. }
  5164. }
  5165.  
  5166. /**
  5167. * Passing the tower
  5168. *
  5169. * Прохождение башни
  5170. */
  5171. function testTower() {
  5172. return new Promise((resolve, reject) => {
  5173. tower = new executeTower(resolve, reject);
  5174. tower.start();
  5175. });
  5176. }
  5177.  
  5178. /**
  5179. * Passing the tower
  5180. *
  5181. * Прохождение башни
  5182. */
  5183. function executeTower(resolve, reject) {
  5184. lastTowerInfo = {};
  5185.  
  5186. scullCoin = 0;
  5187.  
  5188. heroGetAll = [];
  5189.  
  5190. heroesStates = {};
  5191.  
  5192. argsBattle = {
  5193. heroes: [],
  5194. favor: {},
  5195. };
  5196.  
  5197. callsExecuteTower = {
  5198. calls: [{
  5199. name: "towerGetInfo",
  5200. args: {},
  5201. ident: "towerGetInfo"
  5202. }, {
  5203. name: "teamGetAll",
  5204. args: {},
  5205. ident: "teamGetAll"
  5206. }, {
  5207. name: "teamGetFavor",
  5208. args: {},
  5209. ident: "teamGetFavor"
  5210. }, {
  5211. name: "inventoryGet",
  5212. args: {},
  5213. ident: "inventoryGet"
  5214. }, {
  5215. name: "heroGetAll",
  5216. args: {},
  5217. ident: "heroGetAll"
  5218. }]
  5219. }
  5220.  
  5221. buffIds = [
  5222. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5223. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5224. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5225. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5226. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5227. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5228. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5229. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5230. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5231. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5232. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5233. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5234. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5235. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5236. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5237. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5238. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5239. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5240. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5241. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5242. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5243. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5244. ]
  5245.  
  5246. this.start = function () {
  5247. send(JSON.stringify(callsExecuteTower), startTower);
  5248. }
  5249.  
  5250. /**
  5251. * Getting data on the Tower
  5252. *
  5253. * Получаем данные по башне
  5254. */
  5255. function startTower(e) {
  5256. res = e.results;
  5257. towerGetInfo = res[0].result.response;
  5258. if (!towerGetInfo) {
  5259. endTower('noTower', res);
  5260. return;
  5261. }
  5262. teamGetAll = res[1].result.response;
  5263. teamGetFavor = res[2].result.response;
  5264. inventoryGet = res[3].result.response;
  5265. heroGetAll = Object.values(res[4].result.response);
  5266.  
  5267. scullCoin = inventoryGet.coin[7] ?? 0;
  5268.  
  5269. argsBattle.favor = teamGetFavor.tower;
  5270. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5271. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5272. if (pet) {
  5273. argsBattle.pet = pet;
  5274. }
  5275.  
  5276. checkFloor(towerGetInfo);
  5277. }
  5278.  
  5279. function fixHeroesTeam(argsBattle) {
  5280. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5281. if (fixHeroes.length < 5) {
  5282. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5283. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5284. Object.keys(argsBattle.favor).forEach(e => {
  5285. if (!fixHeroes.includes(+e)) {
  5286. delete argsBattle.favor[e];
  5287. }
  5288. })
  5289. }
  5290. argsBattle.heroes = fixHeroes;
  5291. return argsBattle;
  5292. }
  5293.  
  5294. /**
  5295. * Check the floor
  5296. *
  5297. * Проверяем этаж
  5298. */
  5299. function checkFloor(towerInfo) {
  5300. lastTowerInfo = towerInfo;
  5301. maySkipFloor = +towerInfo.maySkipFloor;
  5302. floorNumber = +towerInfo.floorNumber;
  5303. heroesStates = towerInfo.states.heroes;
  5304. floorInfo = towerInfo.floor;
  5305.  
  5306. /**
  5307. * Is there at least one chest open on the floor
  5308. * Открыт ли на этаже хоть один сундук
  5309. */
  5310. isOpenChest = false;
  5311. if (towerInfo.floorType == "chest") {
  5312. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5313. }
  5314.  
  5315. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5316. if (floorNumber > 49) {
  5317. if (isOpenChest) {
  5318. endTower('alreadyOpenChest 50 floor', floorNumber);
  5319. return;
  5320. }
  5321. }
  5322. /**
  5323. * If the chest is open and you can skip floors, then move on
  5324. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5325. */
  5326. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5327. if (isOpenChest) {
  5328. nextOpenChest(floorNumber);
  5329. } else {
  5330. nextChestOpen(floorNumber);
  5331. }
  5332. return;
  5333. }
  5334.  
  5335. // console.log(towerInfo, scullCoin);
  5336. switch (towerInfo.floorType) {
  5337. case "battle":
  5338. if (floorNumber <= maySkipFloor) {
  5339. skipFloor();
  5340. return;
  5341. }
  5342. if (floorInfo.state == 2) {
  5343. nextFloor();
  5344. return;
  5345. }
  5346. startBattle().then(endBattle);
  5347. return;
  5348. case "buff":
  5349. checkBuff(towerInfo);
  5350. return;
  5351. case "chest":
  5352. openChest(floorNumber);
  5353. return;
  5354. default:
  5355. console.log('!', towerInfo.floorType, towerInfo);
  5356. break;
  5357. }
  5358. }
  5359.  
  5360. /**
  5361. * Let's start the fight
  5362. *
  5363. * Начинаем бой
  5364. */
  5365. function startBattle() {
  5366. return new Promise(function (resolve, reject) {
  5367. towerStartBattle = {
  5368. calls: [{
  5369. name: "towerStartBattle",
  5370. args: fixHeroesTeam(argsBattle),
  5371. ident: "body"
  5372. }]
  5373. }
  5374. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5375. });
  5376. }
  5377. /**
  5378. * Returns the result of the battle in a promise
  5379. *
  5380. * Возращает резульат боя в промис
  5381. */
  5382. function resultBattle(resultBattles, resolve) {
  5383. battleData = resultBattles.results[0].result.response;
  5384. battleType = "get_tower";
  5385. BattleCalc(battleData, battleType, function (result) {
  5386. resolve(result);
  5387. });
  5388. }
  5389. /**
  5390. * Finishing the fight
  5391. *
  5392. * Заканчиваем бой
  5393. */
  5394. function endBattle(battleInfo) {
  5395. if (battleInfo.result.stars >= 3) {
  5396. endBattleCall = {
  5397. calls: [{
  5398. name: "towerEndBattle",
  5399. args: {
  5400. result: battleInfo.result,
  5401. progress: battleInfo.progress,
  5402. },
  5403. ident: "body"
  5404. }]
  5405. }
  5406. send(JSON.stringify(endBattleCall), resultEndBattle);
  5407. } else {
  5408. endTower('towerEndBattle win: false\n', battleInfo);
  5409. }
  5410. }
  5411.  
  5412. /**
  5413. * Getting and processing battle results
  5414. *
  5415. * Получаем и обрабатываем результаты боя
  5416. */
  5417. function resultEndBattle(e) {
  5418. battleResult = e.results[0].result.response;
  5419. if ('error' in battleResult) {
  5420. endTower('errorBattleResult', battleResult);
  5421. return;
  5422. }
  5423. if ('reward' in battleResult) {
  5424. scullCoin += battleResult.reward?.coin[7] ?? 0;
  5425. }
  5426. nextFloor();
  5427. }
  5428.  
  5429. function nextFloor() {
  5430. nextFloorCall = {
  5431. calls: [{
  5432. name: "towerNextFloor",
  5433. args: {},
  5434. ident: "body"
  5435. }]
  5436. }
  5437. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5438. }
  5439.  
  5440. function openChest(floorNumber) {
  5441. floorNumber = floorNumber || 0;
  5442. openChestCall = {
  5443. calls: [{
  5444. name: "towerOpenChest",
  5445. args: {
  5446. num: 2
  5447. },
  5448. ident: "body"
  5449. }]
  5450. }
  5451. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5452. }
  5453.  
  5454. function lastChest() {
  5455. endTower('openChest 50 floor', floorNumber);
  5456. }
  5457.  
  5458. function skipFloor() {
  5459. skipFloorCall = {
  5460. calls: [{
  5461. name: "towerSkipFloor",
  5462. args: {},
  5463. ident: "body"
  5464. }]
  5465. }
  5466. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5467. }
  5468.  
  5469. function checkBuff(towerInfo) {
  5470. buffArr = towerInfo.floor;
  5471. promises = [];
  5472. for (let buff of buffArr) {
  5473. buffInfo = buffIds[buff.id];
  5474. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5475. scullCoin -= buffInfo.cost;
  5476. promises.push(buyBuff(buff.id));
  5477. }
  5478. }
  5479. Promise.all(promises).then(nextFloor);
  5480. }
  5481.  
  5482. function buyBuff(buffId) {
  5483. return new Promise(function (resolve, reject) {
  5484. buyBuffCall = {
  5485. calls: [{
  5486. name: "towerBuyBuff",
  5487. args: {
  5488. buffId
  5489. },
  5490. ident: "body"
  5491. }]
  5492. }
  5493. send(JSON.stringify(buyBuffCall), resolve);
  5494. });
  5495. }
  5496.  
  5497. function checkDataFloor(result) {
  5498. towerInfo = result.results[0].result.response;
  5499. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5500. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5501. }
  5502. if ('tower' in towerInfo) {
  5503. towerInfo = towerInfo.tower;
  5504. }
  5505. if ('skullReward' in towerInfo) {
  5506. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5507. }
  5508. checkFloor(towerInfo);
  5509. }
  5510. /**
  5511. * Getting tower rewards
  5512. *
  5513. * Получаем награды башни
  5514. */
  5515. function farmTowerRewards(reason) {
  5516. let { pointRewards, points } = lastTowerInfo;
  5517. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5518. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5519. if (!farmPoints.length) {
  5520. return;
  5521. }
  5522. let farmTowerRewardsCall = {
  5523. calls: [{
  5524. name: "tower_farmPointRewards",
  5525. args: {
  5526. points: farmPoints
  5527. },
  5528. ident: "tower_farmPointRewards"
  5529. }]
  5530. }
  5531.  
  5532. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5533. farmTowerRewardsCall.calls.push({
  5534. name: "tower_farmSkullReward",
  5535. args: {},
  5536. ident: "tower_farmSkullReward"
  5537. });
  5538. }
  5539.  
  5540. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5541. }
  5542.  
  5543. function fullSkipTower() {
  5544. /**
  5545. * Next chest
  5546. *
  5547. * Следующий сундук
  5548. */
  5549. function nextChest(n) {
  5550. return {
  5551. name: "towerNextChest",
  5552. args: {},
  5553. ident: "group_" + n + "_body"
  5554. }
  5555. }
  5556. /**
  5557. * Open chest
  5558. *
  5559. * Открыть сундук
  5560. */
  5561. function openChest(n) {
  5562. return {
  5563. name: "towerOpenChest",
  5564. args: {
  5565. "num": 2
  5566. },
  5567. ident: "group_" + n + "_body"
  5568. }
  5569. }
  5570.  
  5571. const fullSkipTowerCall = {
  5572. calls: []
  5573. }
  5574.  
  5575. let n = 0;
  5576. for (let i = 0; i < 15; i++) {
  5577. fullSkipTowerCall.calls.push(nextChest(++n));
  5578. fullSkipTowerCall.calls.push(openChest(++n));
  5579. }
  5580.  
  5581. send(JSON.stringify(fullSkipTowerCall), data => {
  5582. data.results[0] = data.results[28];
  5583. checkDataFloor(data);
  5584. });
  5585. }
  5586.  
  5587. function nextChestOpen(floorNumber) {
  5588. const calls = [{
  5589. name: "towerOpenChest",
  5590. args: {
  5591. num: 2
  5592. },
  5593. ident: "towerOpenChest"
  5594. }];
  5595.  
  5596. Send(JSON.stringify({ calls })).then(e => {
  5597. nextOpenChest(floorNumber);
  5598. });
  5599. }
  5600.  
  5601. function nextOpenChest(floorNumber) {
  5602. if (floorNumber > 49) {
  5603. endTower('openChest 50 floor', floorNumber);
  5604. return;
  5605. }
  5606. if (floorNumber == 1) {
  5607. fullSkipTower();
  5608. return;
  5609. }
  5610.  
  5611. let nextOpenChestCall = {
  5612. calls: [{
  5613. name: "towerNextChest",
  5614. args: {},
  5615. ident: "towerNextChest"
  5616. }, {
  5617. name: "towerOpenChest",
  5618. args: {
  5619. num: 2
  5620. },
  5621. ident: "towerOpenChest"
  5622. }]
  5623. }
  5624. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5625. }
  5626.  
  5627. function endTower(reason, info) {
  5628. console.log(reason, info);
  5629. if (reason != 'noTower') {
  5630. farmTowerRewards(reason);
  5631. }
  5632. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5633. resolve();
  5634. }
  5635. }
  5636.  
  5637. /**
  5638. * Passage of the arena of the titans
  5639. *
  5640. * Прохождение арены титанов
  5641. */
  5642. function testTitanArena() {
  5643. return new Promise((resolve, reject) => {
  5644. titAren = new executeTitanArena(resolve, reject);
  5645. titAren.start();
  5646. });
  5647. }
  5648.  
  5649. /**
  5650. * Passage of the arena of the titans
  5651. *
  5652. * Прохождение арены титанов
  5653. */
  5654. function executeTitanArena(resolve, reject) {
  5655. let titan_arena = [];
  5656. let finishListBattle = [];
  5657. /**
  5658. * ID of the current batch
  5659. *
  5660. * Идетификатор текущей пачки
  5661. */
  5662. let currentRival = 0;
  5663. /**
  5664. * Number of attempts to finish off the pack
  5665. *
  5666. * Количество попыток добития пачки
  5667. */
  5668. let attempts = 0;
  5669. /**
  5670. * Was there an attempt to finish off the current shooting range
  5671. *
  5672. * Была ли попытка добития текущего тира
  5673. */
  5674. let isCheckCurrentTier = false;
  5675. /**
  5676. * Current shooting range
  5677. *
  5678. * Текущий тир
  5679. */
  5680. let currTier = 0;
  5681. /**
  5682. * Number of battles on the current dash
  5683. *
  5684. * Количество битв на текущем тире
  5685. */
  5686. let countRivalsTier = 0;
  5687.  
  5688. let callsStart = {
  5689. calls: [{
  5690. name: "titanArenaGetStatus",
  5691. args: {},
  5692. ident: "titanArenaGetStatus"
  5693. }, {
  5694. name: "teamGetAll",
  5695. args: {},
  5696. ident: "teamGetAll"
  5697. }]
  5698. }
  5699.  
  5700. this.start = function () {
  5701. send(JSON.stringify(callsStart), startTitanArena);
  5702. }
  5703.  
  5704. function startTitanArena(data) {
  5705. let titanArena = data.results[0].result.response;
  5706. if (titanArena.status == 'disabled') {
  5707. endTitanArena('disabled', titanArena);
  5708. return;
  5709. }
  5710.  
  5711. let teamGetAll = data.results[1].result.response;
  5712. titan_arena = teamGetAll.titan_arena;
  5713.  
  5714. checkTier(titanArena)
  5715. }
  5716.  
  5717. function checkTier(titanArena) {
  5718. if (titanArena.status == "peace_time") {
  5719. endTitanArena('Peace_time', titanArena);
  5720. return;
  5721. }
  5722. currTier = titanArena.tier;
  5723. if (currTier) {
  5724. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5725. }
  5726.  
  5727. if (titanArena.status == "completed_tier") {
  5728. titanArenaCompleteTier();
  5729. return;
  5730. }
  5731. /**
  5732. * Checking for the possibility of a raid
  5733. * Проверка на возможность рейда
  5734. */
  5735. if (titanArena.canRaid) {
  5736. titanArenaStartRaid();
  5737. return;
  5738. }
  5739. /**
  5740. * Check was an attempt to achieve the current shooting range
  5741. * Проверка была ли попытка добития текущего тира
  5742. */
  5743. if (!isCheckCurrentTier) {
  5744. checkRivals(titanArena.rivals);
  5745. return;
  5746. }
  5747.  
  5748. endTitanArena('Done or not canRaid', titanArena);
  5749. }
  5750. /**
  5751. * Submit dash information for verification
  5752. *
  5753. * Отправка информации о тире на проверку
  5754. */
  5755. function checkResultInfo(data) {
  5756. let titanArena = data.results[0].result.response;
  5757. checkTier(titanArena);
  5758. }
  5759. /**
  5760. * Finish the current tier
  5761. *
  5762. * Завершить текущий тир
  5763. */
  5764. function titanArenaCompleteTier() {
  5765. isCheckCurrentTier = false;
  5766. let calls = [{
  5767. name: "titanArenaCompleteTier",
  5768. args: {},
  5769. ident: "body"
  5770. }];
  5771. send(JSON.stringify({calls}), checkResultInfo);
  5772. }
  5773. /**
  5774. * Gathering points to be completed
  5775. *
  5776. * Собираем точки которые нужно добить
  5777. */
  5778. function checkRivals(rivals) {
  5779. finishListBattle = [];
  5780. for (let n in rivals) {
  5781. if (rivals[n].attackScore < 250) {
  5782. finishListBattle.push(n);
  5783. }
  5784. }
  5785. console.log('checkRivals', finishListBattle);
  5786. countRivalsTier = finishListBattle.length;
  5787. roundRivals();
  5788. }
  5789. /**
  5790. * Selecting the next point to finish off
  5791. *
  5792. * Выбор следующей точки для добития
  5793. */
  5794. function roundRivals() {
  5795. let countRivals = finishListBattle.length;
  5796. if (!countRivals) {
  5797. /**
  5798. * Whole range checked
  5799. *
  5800. * Весь тир проверен
  5801. */
  5802. isCheckCurrentTier = true;
  5803. titanArenaGetStatus();
  5804. return;
  5805. }
  5806. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5807. currentRival = finishListBattle.pop();
  5808. attempts = +currentRival;
  5809. // console.log('roundRivals', currentRival);
  5810. titanArenaStartBattle(currentRival);
  5811. }
  5812. /**
  5813. * The start of a solo battle
  5814. *
  5815. * Начало одиночной битвы
  5816. */
  5817. function titanArenaStartBattle(rivalId) {
  5818. let calls = [{
  5819. name: "titanArenaStartBattle",
  5820. args: {
  5821. rivalId: rivalId,
  5822. titans: titan_arena
  5823. },
  5824. ident: "body"
  5825. }];
  5826. send(JSON.stringify({calls}), calcResult);
  5827. }
  5828. /**
  5829. * Calculation of the results of the battle
  5830. *
  5831. * Расчет результатов боя
  5832. */
  5833. function calcResult(data) {
  5834. let battlesInfo = data.results[0].result.response.battle;
  5835. /**
  5836. * If attempts are equal to the current battle number we make
  5837. * Если попытки равны номеру текущего боя делаем прерасчет
  5838. */
  5839. if (attempts == currentRival) {
  5840. preCalcBattle(battlesInfo);
  5841. return;
  5842. }
  5843. /**
  5844. * If there are still attempts, we calculate a new battle
  5845. * Если попытки еще есть делаем расчет нового боя
  5846. */
  5847. if (attempts > 0) {
  5848. attempts--;
  5849. calcBattleResult(battlesInfo)
  5850. .then(resultCalcBattle);
  5851. return;
  5852. }
  5853. /**
  5854. * Otherwise, go to the next opponent
  5855. * Иначе переходим к следующему сопернику
  5856. */
  5857. roundRivals();
  5858. }
  5859. /**
  5860. * Processing the results of the battle calculation
  5861. *
  5862. * Обработка результатов расчета битвы
  5863. */
  5864. function resultCalcBattle(resultBattle) {
  5865. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5866. /**
  5867. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5868. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5869. */
  5870. if (resultBattle.result.win || !attempts) {
  5871. titanArenaEndBattle({
  5872. progress: resultBattle.progress,
  5873. result: resultBattle.result,
  5874. rivalId: resultBattle.battleData.typeId
  5875. });
  5876. return;
  5877. }
  5878. /**
  5879. * If not victory and there are attempts we start a new battle
  5880. * Если не победа и есть попытки начинаем новый бой
  5881. */
  5882. titanArenaStartBattle(resultBattle.battleData.typeId);
  5883. }
  5884. /**
  5885. * Returns the promise of calculating the results of the battle
  5886. *
  5887. * Возращает промис расчета результатов битвы
  5888. */
  5889. function getBattleInfo(battle, isRandSeed) {
  5890. return new Promise(function (resolve) {
  5891. if (isRandSeed) {
  5892. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5893. }
  5894. // console.log(battle.seed);
  5895. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5896. });
  5897. }
  5898. /**
  5899. * Recalculate battles
  5900. *
  5901. * Прерасчтет битвы
  5902. */
  5903. function preCalcBattle(battle) {
  5904. let actions = [getBattleInfo(battle, false)];
  5905. const countTestBattle = getInput('countTestBattle');
  5906. for (let i = 0; i < countTestBattle; i++) {
  5907. actions.push(getBattleInfo(battle, true));
  5908. }
  5909. Promise.all(actions)
  5910. .then(resultPreCalcBattle);
  5911. }
  5912. /**
  5913. * Processing the results of the battle recalculation
  5914. *
  5915. * Обработка результатов прерасчета битвы
  5916. */
  5917. function resultPreCalcBattle(e) {
  5918. let wins = e.map(n => n.result.win);
  5919. let firstBattle = e.shift();
  5920. let countWin = wins.reduce((w, s) => w + s);
  5921. const countTestBattle = getInput('countTestBattle');
  5922. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  5923. if (countWin > 0) {
  5924. attempts = getInput('countAutoBattle');
  5925. } else {
  5926. attempts = 0;
  5927. }
  5928. resultCalcBattle(firstBattle);
  5929. }
  5930.  
  5931. /**
  5932. * Complete an arena battle
  5933. *
  5934. * Завершить битву на арене
  5935. */
  5936. function titanArenaEndBattle(args) {
  5937. let calls = [{
  5938. name: "titanArenaEndBattle",
  5939. args,
  5940. ident: "body"
  5941. }];
  5942. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5943. }
  5944.  
  5945. function resultTitanArenaEndBattle(e) {
  5946. let attackScore = e.results[0].result.response.attackScore;
  5947. let numReval = countRivalsTier - finishListBattle.length;
  5948. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5949. /**
  5950. * TODO: Might need to improve the results.
  5951. * TODO: Возможно стоит сделать улучшение результатов
  5952. */
  5953. // console.log('resultTitanArenaEndBattle', e)
  5954. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5955. roundRivals();
  5956. }
  5957. /**
  5958. * Arena State
  5959. *
  5960. * Состояние арены
  5961. */
  5962. function titanArenaGetStatus() {
  5963. let calls = [{
  5964. name: "titanArenaGetStatus",
  5965. args: {},
  5966. ident: "body"
  5967. }];
  5968. send(JSON.stringify({calls}), checkResultInfo);
  5969. }
  5970. /**
  5971. * Arena Raid Request
  5972. *
  5973. * Запрос рейда арены
  5974. */
  5975. function titanArenaStartRaid() {
  5976. let calls = [{
  5977. name: "titanArenaStartRaid",
  5978. args: {
  5979. titans: titan_arena
  5980. },
  5981. ident: "body"
  5982. }];
  5983. send(JSON.stringify({calls}), calcResults);
  5984. }
  5985.  
  5986. function calcResults(data) {
  5987. let battlesInfo = data.results[0].result.response;
  5988. let {attackers, rivals} = battlesInfo;
  5989.  
  5990. let promises = [];
  5991. for (let n in rivals) {
  5992. rival = rivals[n];
  5993. promises.push(calcBattleResult({
  5994. attackers: attackers,
  5995. defenders: [rival.team],
  5996. seed: rival.seed,
  5997. typeId: n,
  5998. }));
  5999. }
  6000.  
  6001. Promise.all(promises)
  6002. .then(results => {
  6003. const endResults = {};
  6004. for (let info of results) {
  6005. let id = info.battleData.typeId;
  6006. endResults[id] = {
  6007. progress: info.progress,
  6008. result: info.result,
  6009. }
  6010. }
  6011. titanArenaEndRaid(endResults);
  6012. });
  6013. }
  6014.  
  6015. function calcBattleResult(battleData) {
  6016. return new Promise(function (resolve, reject) {
  6017. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6018. });
  6019. }
  6020.  
  6021. /**
  6022. * Sending Raid Results
  6023. *
  6024. * Отправка результатов рейда
  6025. */
  6026. function titanArenaEndRaid(results) {
  6027. titanArenaEndRaidCall = {
  6028. calls: [{
  6029. name: "titanArenaEndRaid",
  6030. args: {
  6031. results
  6032. },
  6033. ident: "body"
  6034. }]
  6035. }
  6036. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6037. }
  6038.  
  6039. function checkRaidResults(data) {
  6040. results = data.results[0].result.response.results;
  6041. isSucsesRaid = true;
  6042. for (let i in results) {
  6043. isSucsesRaid &&= (results[i].attackScore >= 250);
  6044. }
  6045.  
  6046. if (isSucsesRaid) {
  6047. titanArenaCompleteTier();
  6048. } else {
  6049. titanArenaGetStatus();
  6050. }
  6051. }
  6052.  
  6053. function titanArenaFarmDailyReward() {
  6054. titanArenaFarmDailyRewardCall = {
  6055. calls: [{
  6056. name: "titanArenaFarmDailyReward",
  6057. args: {},
  6058. ident: "body"
  6059. }]
  6060. }
  6061. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6062. }
  6063.  
  6064. function endTitanArena(reason, info) {
  6065. if (!['Peace_time', 'disabled'].includes(reason)) {
  6066. titanArenaFarmDailyReward();
  6067. }
  6068. console.log(reason, info);
  6069. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6070. resolve();
  6071. }
  6072. }
  6073.  
  6074. function hackGame() {
  6075. self = this;
  6076. selfGame = null;
  6077. bindId = 1e9;
  6078. this.libGame = null;
  6079.  
  6080. /**
  6081. * List of correspondence of used classes to their names
  6082. *
  6083. * Список соответствия используемых классов их названиям
  6084. */
  6085. ObjectsList = [
  6086. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  6087. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  6088. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  6089. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  6090. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  6091.  
  6092. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  6093. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  6094. {name:"GameModel", prop:"game.model.GameModel"},
  6095. {name:"CommandManager", prop:"game.command.CommandManager"},
  6096. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  6097. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  6098. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  6099. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  6100. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  6101. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  6102. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  6103. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  6104. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  6105. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  6106. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  6107. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  6108. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  6109. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  6110. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  6111. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  6112. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  6113. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  6114. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  6115. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  6116. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  6117. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  6118. {name:"BattleConfig", prop:"battle.BattleConfig"},
  6119. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  6120. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  6121. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  6122. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  6123. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  6124. { name: "PlayerSubscriptionInfoValueObject", prop: "game.model.user.subscription.PlayerSubscriptionInfoValueObject" },
  6125. ];
  6126.  
  6127. /**
  6128. * Contains the game classes needed to write and override game methods
  6129. *
  6130. * Содержит классы игры необходимые для написания и подмены методов игры
  6131. */
  6132. Game = {
  6133. /**
  6134. * Function 'e'
  6135. * Функция 'e'
  6136. */
  6137. bindFunc: function (a, b) {
  6138. if (null == b)
  6139. return null;
  6140. null == b.__id__ && (b.__id__ = bindId++);
  6141. var c;
  6142. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6143. c = a.hx__closures__[b.__id__];
  6144. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6145. return c
  6146. },
  6147. };
  6148.  
  6149. /**
  6150. * Connects to game objects via the object creation event
  6151. *
  6152. * Подключается к объектам игры через событие создания объекта
  6153. */
  6154. function connectGame() {
  6155. for (let obj of ObjectsList) {
  6156. /**
  6157. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6158. */
  6159. Object.defineProperty(Object.prototype, obj.prop, {
  6160. set: function (value) {
  6161. if (!selfGame) {
  6162. selfGame = this;
  6163. }
  6164. if (!Game[obj.name]) {
  6165. Game[obj.name] = value;
  6166. }
  6167. // console.log('set ' + obj.prop, this, value);
  6168. this[obj.prop + '_'] = value;
  6169. },
  6170. get: function () {
  6171. // console.log('get ' + obj.prop, this);
  6172. return this[obj.prop + '_'];
  6173. }
  6174. });
  6175. }
  6176. }
  6177.  
  6178. /**
  6179. * Game.BattlePresets
  6180. * @param {bool} a isReplay
  6181. * @param {bool} b autoToggleable
  6182. * @param {bool} c auto On Start
  6183. * @param {object} d config
  6184. * @param {bool} f showBothTeams
  6185. */
  6186. /**
  6187. * Returns the results of the battle to the callback function
  6188. * Возвращает в функцию callback результаты боя
  6189. * @param {*} battleData battle data данные боя
  6190. * @param {*} battleConfig combat configuration type options:
  6191. *
  6192. * тип конфигурации боя варианты:
  6193. *
  6194. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6195. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6196. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6197. *
  6198. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6199. *
  6200. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6201. * @param {*} callback функция в которую вернуться результаты боя
  6202. */
  6203. this.BattleCalc = function (battleData, battleConfig, callback) {
  6204. // battleConfig = battleConfig || getBattleType(battleData.type)
  6205. if (!Game.BattlePresets) throw Error('Use connectGame');
  6206. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6207. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6208. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  6209. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6210. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6211. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  6212. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6213. const battleTime = Math.max(...battleLog.map(e => e.time < timeLimit ? e.time : 0));
  6214. callback({
  6215. battleTime,
  6216. battleData,
  6217. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  6218. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  6219. })
  6220. });
  6221. battleInstantPlay.start();
  6222. }
  6223.  
  6224. /**
  6225. * Returns a function with the specified name from the class
  6226. *
  6227. * Возвращает из класса функцию с указанным именем
  6228. * @param {Object} classF Class // класс
  6229. * @param {String} nameF function name // имя функции
  6230. * @param {String} pos name and alias order // порядок имени и псевдонима
  6231. * @returns
  6232. */
  6233. function getF(classF, nameF, pos) {
  6234. pos = pos || false;
  6235. let prop = Object.entries(classF.prototype.__properties__)
  6236. if (!pos) {
  6237. return prop.filter((e) => e[1] == nameF).pop()[0];
  6238. } else {
  6239. return prop.filter((e) => e[0] == nameF).pop()[1];
  6240. }
  6241. }
  6242.  
  6243. /**
  6244. * Returns a function with the specified name from the class
  6245. *
  6246. * Возвращает из класса функцию с указанным именем
  6247. * @param {Object} classF Class // класс
  6248. * @param {String} nameF function name // имя функции
  6249. * @returns
  6250. */
  6251. function getFnP(classF, nameF) {
  6252. let prop = Object.entries(classF.__properties__)
  6253. return prop.filter((e) => e[1] == nameF).pop()[0];
  6254. }
  6255.  
  6256. /**
  6257. * Returns the function name with the specified ordinal from the class
  6258. *
  6259. * Возвращает имя функции с указаным порядковым номером из класса
  6260. * @param {Object} classF Class // класс
  6261. * @param {Number} nF Order number of function // порядковый номер функции
  6262. * @returns
  6263. */
  6264. function getFn(classF, nF) {
  6265. let prop = Object.keys(classF);
  6266. return prop[nF];
  6267. }
  6268.  
  6269. /**
  6270. * Returns the name of the function with the specified serial number from the prototype of the class
  6271. *
  6272. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6273. * @param {Object} classF Class // класс
  6274. * @param {Number} nF Order number of function // порядковый номер функции
  6275. * @returns
  6276. */
  6277. function getProtoFn(classF, nF) {
  6278. let prop = Object.keys(classF.prototype);
  6279. return prop[nF];
  6280. }
  6281. /**
  6282. * Description of replaced functions
  6283. *
  6284. * Описание подменяемых функций
  6285. */
  6286. replaceFunction = {
  6287. company: function() {
  6288. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6289. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6290. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6291. if (!isChecked('passBattle')) {
  6292. oldSkipMisson.call(this, a, b, c);
  6293. return;
  6294. }
  6295.  
  6296. try {
  6297. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6298.  
  6299. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  6300. a = new Game.BattleInstantPlay(c, a);
  6301. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  6302. a.start()
  6303. } catch (error) {
  6304. console.error('company', error)
  6305. oldSkipMisson.call(this, a, b, c);
  6306. }
  6307. }
  6308.  
  6309. Game.PlayerMissionData.prototype.P$h = function (a) {
  6310. let GM_2 = getFn(Game.GameModel, 2);
  6311. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6312. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6313. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6314. let MBR_15 = getF(Game.MultiBattleResult, "get_result");
  6315. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6316. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6317. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  6318. }
  6319. },
  6320. tower: function() {
  6321. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6322. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6323. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6324. if (!isChecked('passBattle')) {
  6325. oldSkipTower.call(this, a);
  6326. return;
  6327. }
  6328. try {
  6329. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  6330. a = new Game.BattleInstantPlay(a, p);
  6331. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  6332. a.start()
  6333. } catch (error) {
  6334. console.error('tower', error)
  6335. oldSkipMisson.call(this, a, b, c);
  6336. }
  6337. }
  6338.  
  6339. Game.PlayerTowerData.prototype.P$h = function (a) {
  6340. const GM_2 = getFnP(Game.GameModel, "get_instance");
  6341. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6342. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6343. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6344. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  6345. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6346. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6347. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6348. }
  6349. },
  6350. // skipSelectHero: function() {
  6351. // if (!HOST) throw Error('Use connectGame');
  6352. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6353. // },
  6354. passBattle: function() {
  6355. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6356. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6357. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6358. if (!isChecked('passBattle')) {
  6359. oldPassBattle.call(this, a);
  6360. return;
  6361. }
  6362. try {
  6363. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6364. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6365. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6366. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  6367.  
  6368. 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, 17)])));
  6369. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6370. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  6371. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  6372. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  6373. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6374. );
  6375.  
  6376. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  6377. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  6378. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  6379. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  6380. /*
  6381. Какая-то ненужная фигня
  6382. if (!HC.lSb()) {
  6383. this.clip.r6b.g().B(!1);
  6384. a = this.clip.r6b.g().X() + 7;
  6385. var b = this.clip.ba.g();
  6386. b.$(b.X() - a);
  6387. b = this.clip.IS.g();
  6388. b.sa(b.Fa() - a)
  6389. }
  6390. */
  6391. } catch(error) {
  6392. console.error('passBattle', error)
  6393. oldPassBattle.call(this, a);
  6394. }
  6395. }
  6396.  
  6397. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  6398. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  6399. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  6400. if (isChecked('passBattle')) {
  6401. return I18N('BTN_PASS');
  6402. } else {
  6403. return oldFunc.call(this);
  6404. }
  6405. }
  6406. },
  6407. endlessCards: function() {
  6408. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  6409. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  6410. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  6411. if (countPredictionCard <= 0) {
  6412. return true;
  6413. } else {
  6414. return oldEndlessCards.call(this);
  6415. }
  6416. }
  6417. },
  6418. speedBattle: function () {
  6419. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  6420. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  6421. Game.BattleController.prototype[get_timeScale] = function () {
  6422. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  6423. if (!speedBattle) {
  6424. return oldSpeedBattle.call(this);
  6425. }
  6426. try {
  6427. const BC_12 = getProtoFn(Game.BattleController, 12);
  6428. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  6429. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  6430. if (this[BC_12][BSM_12][BP_get_value]()) {
  6431. return 0;
  6432. }
  6433. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  6434. const BC_48 = getProtoFn(Game.BattleController, 48);
  6435. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  6436. const BC_14 = getProtoFn(Game.BattleController, 14);
  6437. const BC_3 = getFn(Game.BattleController, 3);
  6438. if (this[BC_12][BSM_2][BP_get_value]()) {
  6439. var a = speedBattle * this[BC_48]();
  6440. } else {
  6441. a = this[BC_12][BSM_1][BP_get_value]();
  6442. const maxSpeed = Math.max(...this[BC_14]);
  6443. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  6444. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_48]();
  6445. }
  6446. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  6447. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  6448. const DS_23 = getFn(Game.DataStorage, 23);
  6449. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  6450. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  6451. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  6452. const R_1 = getFn(selfGame.Reflect, 1);
  6453. const BC_1 = getFn(Game.BattleController, 1);
  6454. const get_config = getF(Game.BattlePresets, "get_config");
  6455. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  6456. 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"));
  6457. return a
  6458. } catch(error) {
  6459. console.error('passBatspeedBattletle', error)
  6460. return oldSpeedBattle.call(this);
  6461. }
  6462. }
  6463. },
  6464.  
  6465. /**
  6466. * Remove the rare shop
  6467. *
  6468. * Удаление торговца редкими товарами
  6469. */
  6470. /*
  6471. removeWelcomeShop: function () {
  6472. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  6473. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  6474. Game.SpecialShopModel.prototype[SSM_3] = function () {
  6475. if (isChecked('noOfferDonat')) {
  6476. return null;
  6477. } else {
  6478. return oldWelcomeShop.call(this);
  6479. }
  6480. }
  6481. },
  6482. */
  6483.  
  6484. /**
  6485. * Acceleration button without Valkyries favor
  6486. *
  6487. * Кнопка ускорения без Покровительства Валькирий
  6488. */
  6489. battleFastKey: function () {
  6490. const PSIVO_9 = getProtoFn(Game.PlayerSubscriptionInfoValueObject, 9);
  6491. const oldBattleFastKey = Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9];
  6492. Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9] = function () {
  6493. //const BGM_42 = getProtoFn(Game.BattleGuiMediator, 42);
  6494. //const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_42];
  6495. //Game.BattleGuiMediator.prototype[BGM_42] = function () {
  6496. let flag = true;
  6497. //console.log(flag)
  6498. if (flag) {
  6499. return true;
  6500. } else {
  6501. return oldBattleFastKey.call(this);
  6502. }
  6503. /*
  6504. if (!flag) {
  6505. return oldBattleFastKey.call(this);
  6506. }
  6507. try {
  6508. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6509. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6510. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6511. this[BGM_9][BPW_0](true);
  6512. this[BGM_10][BPW_0](true);
  6513. } catch (error) {
  6514. console.error(error);
  6515. return oldBattleFastKey.call(this);
  6516. }*/
  6517. }
  6518. },
  6519. fastSeason: function () {
  6520. const GameNavigator = selfGame["game.screen.navigator.GameNavigator"];
  6521. const oldFuncName = getProtoFn(GameNavigator, 16);
  6522. const newFuncName = getProtoFn(GameNavigator, 14);
  6523. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6524. const newFastSeason = GameNavigator.prototype[newFuncName];
  6525. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6526. if (isChecked('fastSeason')) {
  6527. return newFastSeason.apply(this, [a]);
  6528. } else {
  6529. return oldFastSeason.apply(this, [a, b]);
  6530. }
  6531. }
  6532. },
  6533. ShowChestReward: function () {
  6534. const TitanArtifactChest = selfGame["game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator"];
  6535. const getOpenAmountTitan = getF(TitanArtifactChest, "get_openAmount");
  6536. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6537. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6538. if (correctShowOpenArtifact) {
  6539. correctShowOpenArtifact--;
  6540. return 100;
  6541. }
  6542. return oldGetOpenAmountTitan.call(this);
  6543. }
  6544.  
  6545. const ArtifactChest = selfGame["game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator"];
  6546. const getOpenAmount = getF(ArtifactChest, "get_openAmount");
  6547. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6548. ArtifactChest.prototype[getOpenAmount] = function () {
  6549. if (correctShowOpenArtifact) {
  6550. correctShowOpenArtifact--;
  6551. return 100;
  6552. }
  6553. return oldGetOpenAmount.call(this);
  6554. }
  6555.  
  6556. },
  6557. fixCompany: function () {
  6558. const GameBattleView = selfGame["game.mediator.gui.popup.battle.GameBattleView"];
  6559. const BattleThread = selfGame["game.battle.controller.thread.BattleThread"];
  6560. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6561. const getThread = getF(GameBattleView, 'get_thread');
  6562. const oldFunc = GameBattleView.prototype[getThread];
  6563. GameBattleView.prototype[getThread] = function () {
  6564. return oldFunc.call(this) || {
  6565. [getOnViewDisposed]: async () => { }
  6566. }
  6567. }
  6568. }
  6569. }
  6570.  
  6571. /**
  6572. * Starts replacing recorded functions
  6573. *
  6574. * Запускает замену записанных функций
  6575. */
  6576. this.activateHacks = function () {
  6577. if (!selfGame) throw Error('Use connectGame');
  6578. for (let func in replaceFunction) {
  6579. replaceFunction[func]();
  6580. }
  6581. }
  6582.  
  6583. /**
  6584. * Returns the game object
  6585. *
  6586. * Возвращает объект игры
  6587. */
  6588. this.getSelfGame = function () {
  6589. return selfGame;
  6590. }
  6591.  
  6592. /**
  6593. * Updates game data
  6594. *
  6595. * Обновляет данные игры
  6596. */
  6597. this.refreshGame = function () {
  6598. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6599. try {
  6600. cheats.refreshInventory();
  6601. } catch (e) { }
  6602. }
  6603.  
  6604. /**
  6605. * Update inventory
  6606. *
  6607. * Обновляет инвентарь
  6608. */
  6609. this.refreshInventory = async function () {
  6610. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6611. const GM_0 = getProtoFn(Game.GameModel, 0);
  6612. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6613. const Player = Game.GameModel[GM_INST]()[GM_0];
  6614. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6615. Player[P_24].init(await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}').then(e => e.results[0].result.response))
  6616. }
  6617.  
  6618. /**
  6619. * Change the play screen on windowName
  6620. *
  6621. * Сменить экран игры на windowName
  6622. *
  6623. * Possible options:
  6624. *
  6625. * Возможные варианты:
  6626. *
  6627. * 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
  6628. */
  6629. this.goNavigtor = function (windowName) {
  6630. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6631. let window = mechanicStorage[windowName];
  6632. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6633. let Game = selfGame['Game'];
  6634. let navigator = getF(Game, "get_navigator")
  6635. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6636. let instance = getFnP(Game, 'get_instance');
  6637. Game[instance]()[navigator]()[navigate](window, event);
  6638. }
  6639.  
  6640. /**
  6641. * Move to the sanctuary cheats.goSanctuary()
  6642. *
  6643. * Переместиться в святилище cheats.goSanctuary()
  6644. */
  6645. this.goSanctuary = () => {
  6646. this.goNavigtor("SANCTUARY");
  6647. }
  6648.  
  6649. /**
  6650. * Go to Guild War
  6651. *
  6652. * Перейти к Войне Гильдий
  6653. */
  6654. this.goClanWar = function() {
  6655. let instance = getFnP(Game.GameModel, 'get_instance')
  6656. let player = Game.GameModel[instance]().A;
  6657. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6658. new clanWarSelect(player).open();
  6659. }
  6660.  
  6661. /**
  6662. * Go to BrawlShop
  6663. *
  6664. * Переместиться в BrawlShop
  6665. */
  6666. this.goBrawlShop = () => {
  6667. const instance = getFnP(Game.GameModel, 'get_instance')
  6668. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6669. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6670. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6671. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6672.  
  6673. const player = Game.GameModel[instance]().A;
  6674. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6675. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6676. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6677. }
  6678.  
  6679. /**
  6680. * Returns all stores from game data
  6681. *
  6682. * Возвращает все магазины из данных игры
  6683. */
  6684. this.getShops = () => {
  6685. const instance = getFnP(Game.GameModel, 'get_instance')
  6686. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6687. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6688. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6689.  
  6690. const player = Game.GameModel[instance]().A;
  6691. return player[P_36][PSD_0][IM_0];
  6692. }
  6693.  
  6694. /**
  6695. * Returns the store from the game data by ID
  6696. *
  6697. * Возвращает магазин из данных игры по идетификатору
  6698. */
  6699. this.getShop = (id) => {
  6700. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6701. const shops = this.getShops();
  6702. const shop = shops[id]?.[PSDE_4];
  6703. return shop;
  6704. }
  6705.  
  6706. /**
  6707. * Moves to the store with the specified ID
  6708. *
  6709. * Перемещает к магазину с указанным идетификатором
  6710. */
  6711. this.goShopId = function (id) {
  6712. const shop = this.getShop(id);
  6713. if (!shop) {
  6714. return;
  6715. }
  6716. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6717. let Game = selfGame['Game'];
  6718. let navigator = getF(Game, "get_navigator");
  6719. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 21);
  6720. let instance = getFnP(Game, 'get_instance');
  6721. Game[instance]()[navigator]()[navigate](shop, event);
  6722. }
  6723.  
  6724. /**
  6725. * Opens a list of non-standard stores
  6726. *
  6727. * Открывает список не стандартных магазинов
  6728. */
  6729. this.goCustomShops = async (p = 0) => {
  6730. /** Запрос данных нужных магазинов */
  6731. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6732. const shops = lib.getData('shop');
  6733. for (const id in shops) {
  6734. const check = !shops[id].ident.includes('merchantPromo') &&
  6735. ![1, 4, 5, 6, 7, 8, 9, 10, 11, 1023, 1024].includes(+id);
  6736. if (check) {
  6737. calls.push({
  6738. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6739. })
  6740. }
  6741. }
  6742. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6743. const shopAll = result.shift();
  6744. const DS_32 = getFn(Game.DataStorage, 32)
  6745.  
  6746. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6747.  
  6748. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6749. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6750. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6751. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6752.  
  6753. for (let shop of result) {
  6754. shopAll[shop.id] = shop;
  6755. // Снимаем все ограничения с магазинов
  6756. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6757. shopLibData[SD_21] = 1;
  6758. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6759. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6760. teamLevel: 10
  6761. });
  6762. }
  6763. /** Скрываем все остальные магазины */
  6764. for (let id in shops) {
  6765. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6766. if (shopLibData[ident].includes('merchantPromo')) {
  6767. shopLibData[SD_21] = 0;
  6768. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6769. teamLevel: 999
  6770. });
  6771. }
  6772. }
  6773.  
  6774. const instance = getFnP(Game.GameModel, 'get_instance')
  6775. const GM_0 = getProtoFn(Game.GameModel, 0);
  6776. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6777. const player = Game.GameModel[instance]()[GM_0];
  6778. /** Пересоздаем объект с магазинами */
  6779. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6780. player[P_36].init(shopAll);
  6781. /** Даем магазинам новые названия */
  6782. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6783.  
  6784. const shopName = getFn(cheats.getShop(1), 14);
  6785. const currentShops = this.getShops();
  6786. let count = 0;
  6787. const start = 9 * p + 1;
  6788. const end = start + 8;
  6789. for (let id in currentShops) {
  6790. const shop = currentShops[id][PSDE_4];
  6791. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6792. /** Скрываем стандартные магазины */
  6793. shop[SD_21] = 0;
  6794. } else {
  6795. count++;
  6796. if (count < start || count > end) {
  6797. shop[SD_21] = 0;
  6798. continue;
  6799. }
  6800. shop[SD_21] = 1;
  6801. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6802. shop[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6803. shop[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6804. teamLevel: 10
  6805. });
  6806. }
  6807. }
  6808. console.log(count, start, end)
  6809. /** Отправляемся в городскую лавку */
  6810. this.goShopId(1);
  6811. }
  6812.  
  6813. /**
  6814. * Opens a list of standard stores
  6815. *
  6816. * Открывает список стандартных магазинов
  6817. */
  6818. this.goDefaultShops = async () => {
  6819. const result = await Send({ calls: [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }] })
  6820. .then(e => e.results.map(n => n.result.response));
  6821. const shopAll = result.shift();
  6822. const shops = lib.getData('shop');
  6823.  
  6824. const DS_8 = getFn(Game.DataStorage, 8)
  6825. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6826.  
  6827. /** Получаем объект валюты магазина для оторажения */
  6828. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6829. coins.__proto__ = selfGame["game.data.storage.resource.ConsumableDescription"].prototype;
  6830.  
  6831. const DS_32 = getFn(Game.DataStorage, 32)
  6832. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6833.  
  6834. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6835. for (const id in shops) {
  6836. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6837. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6838. shopLibData[SD_21] = 1;
  6839. } else {
  6840. shopLibData[SD_21] = 0;
  6841. }
  6842. }
  6843.  
  6844. const instance = getFnP(Game.GameModel, 'get_instance')
  6845. const GM_0 = getProtoFn(Game.GameModel, 0);
  6846. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6847. const player = Game.GameModel[instance]()[GM_0];
  6848. /** Пересоздаем объект с магазинами */
  6849. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6850. player[P_36].init(shopAll);
  6851.  
  6852. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6853. const currentShops = this.getShops();
  6854. for (let id in currentShops) {
  6855. const shop = currentShops[id][PSDE_4];
  6856. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6857. shop[SD_21] = 1;
  6858. } else {
  6859. shop[SD_21] = 0;
  6860. }
  6861. }
  6862. this.goShopId(1);
  6863. }
  6864.  
  6865. /**
  6866. * Opens a list of Secret Wealth stores
  6867. *
  6868. * Открывает список магазинов Тайное богатство
  6869. */
  6870. this.goSecretWealthShops = async () => {
  6871. /** Запрос данных нужных магазинов */
  6872. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  6873. const shops = lib.getData('shop');
  6874. for (const id in shops) {
  6875. if (shops[id].ident.includes('merchantPromo') && shops[id].teamLevelToUnlock <= 130) {
  6876. calls.push({
  6877. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  6878. })
  6879. }
  6880. }
  6881. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  6882. const shopAll = result.shift();
  6883. const DS_32 = getFn(Game.DataStorage, 32)
  6884.  
  6885. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  6886.  
  6887. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  6888. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  6889. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  6890. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  6891. const specialCurrency = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 15);
  6892.  
  6893. const DS_8 = getFn(Game.DataStorage, 8)
  6894. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  6895.  
  6896. /** Получаем объект валюты магазина для оторажения */
  6897. const coins = Game.DataStorage[DS_8][DSB_4](85);
  6898. coins.__proto__ = selfGame["game.data.storage.resource.CoinDescription"].prototype;
  6899.  
  6900. for (let shop of result) {
  6901. shopAll[shop.id] = shop;
  6902. /** Снимаем все ограничения с магазинов */
  6903. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  6904. if (shopLibData[ident].includes('merchantPromo')) {
  6905. shopLibData[SD_21] = 1;
  6906. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  6907. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  6908. teamLevel: 10
  6909. });
  6910. }
  6911. }
  6912.  
  6913. /** Скрываем все остальные магазины */
  6914. for (let id in shops) {
  6915. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  6916. if (!shopLibData[ident].includes('merchantPromo')) {
  6917. shopLibData[SD_21] = 0;
  6918. }
  6919. }
  6920.  
  6921. const instance = getFnP(Game.GameModel, 'get_instance')
  6922. const GM_0 = getProtoFn(Game.GameModel, 0);
  6923. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6924. const player = Game.GameModel[instance]()[GM_0];
  6925. /** Пересоздаем объект с магазинами */
  6926. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  6927. player[P_36].init(shopAll);
  6928. /** Даем магазинам новые названия */
  6929. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6930.  
  6931. const shopName = getFn(cheats.getShop(1), 14);
  6932. const currentShops = this.getShops();
  6933. for (let id in currentShops) {
  6934. const shop = currentShops[id][PSDE_4];
  6935. if (shop[ident].includes('merchantPromo')) {
  6936. shop[SD_21] = 1;
  6937. shop[specialCurrency] = coins;
  6938. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  6939. } else if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  6940. /** Скрываем стандартные магазины */
  6941. shop[SD_21] = 0;
  6942. }
  6943. }
  6944. /** Отправляемся в городскую лавку */
  6945. this.goShopId(1);
  6946. }
  6947.  
  6948. /**
  6949. * Change island map
  6950. *
  6951. * Сменить карту острова
  6952. */
  6953. this.changeIslandMap = (mapId = 2) => {
  6954. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  6955. const GM_0 = getProtoFn(Game.GameModel, 0);
  6956. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 59);
  6957. const Player = Game.GameModel[GameInst]()[GM_0];
  6958. Player[P_59].$({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  6959.  
  6960. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  6961. const navigator = getF(selfGame['Game'], "get_navigator");
  6962. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  6963. }
  6964.  
  6965. /**
  6966. * Game library availability tracker
  6967. *
  6968. * Отслеживание доступности игровой библиотеки
  6969. */
  6970. function checkLibLoad() {
  6971. timeout = setTimeout(() => {
  6972. if (Game.GameModel) {
  6973. changeLib();
  6974. } else {
  6975. checkLibLoad();
  6976. }
  6977. }, 100)
  6978. }
  6979.  
  6980. /**
  6981. * Game library data spoofing
  6982. *
  6983. * Подмена данных игровой библиотеки
  6984. */
  6985. function changeLib() {
  6986. console.log('lib connect');
  6987. const originalStartFunc = Game.GameModel.prototype.start;
  6988. Game.GameModel.prototype.start = function (a, b, c) {
  6989. self.libGame = b.raw;
  6990. try {
  6991. const levels = b.raw.seasonAdventure.level;
  6992. for (const id in levels) {
  6993. const level = levels[id];
  6994. level.clientData.graphics.fogged = level.clientData.graphics.visible
  6995. }
  6996. // b.raw.shop[26].requirements = null;
  6997. // b.raw.shop[28].requirements = null;
  6998. // b.raw.shop[29].requirements = null;
  6999. } catch (e) {
  7000. console.warn(e);
  7001. }
  7002. originalStartFunc.call(this, a, b, c);
  7003. }
  7004. }
  7005.  
  7006. /**
  7007. * Returns the value of a language constant
  7008. *
  7009. * Возвращает значение языковой константы
  7010. * @param {*} langConst language constant // языковая константа
  7011. * @returns
  7012. */
  7013. this.translate = function (langConst) {
  7014. return Game.Translate.translate(langConst);
  7015. }
  7016.  
  7017. connectGame();
  7018. checkLibLoad();
  7019. }
  7020.  
  7021. /**
  7022. * Auto collection of gifts
  7023. *
  7024. * Автосбор подарков
  7025. */
  7026. function getAutoGifts() {
  7027. let valName = 'giftSendIds_' + userInfo.id;
  7028.  
  7029. if (!localStorage['clearGift' + userInfo.id]) {
  7030. localStorage[valName] = '';
  7031. localStorage['clearGift' + userInfo.id] = '+';
  7032. }
  7033.  
  7034. if (!localStorage[valName]) {
  7035. localStorage[valName] = '';
  7036. }
  7037.  
  7038. const now = Date.now();
  7039. const body = JSON.stringify({ now });
  7040. const signature = window['\x73\x69\x67\x6e'](now);
  7041. /**
  7042. * Submit a request to receive gift codes
  7043. *
  7044. * Отправка запроса для получения кодов подарков
  7045. */
  7046. fetch('https://zingery.ru/heroes/getGifts.php', {
  7047. method: 'POST',
  7048. headers: {
  7049. 'X-Request-Signature': signature,
  7050. 'X-Script-Name': GM_info.script.name,
  7051. 'X-Script-Version': GM_info.script.version,
  7052. 'X-Script-Author': GM_info.script.author,
  7053. },
  7054. body
  7055. }).then(
  7056. response => response.json()
  7057. ).then(
  7058. data => {
  7059. let freebieCheckCalls = {
  7060. calls: []
  7061. }
  7062. data.forEach((giftId, n) => {
  7063. if (localStorage[valName].includes(giftId)) return;
  7064. //localStorage[valName] += ';' + giftId;
  7065. freebieCheckCalls.calls.push({
  7066. name: "registration",
  7067. args: {
  7068. user: { referrer: {} },
  7069. giftId
  7070. },
  7071. context: {
  7072. actionTs: Math.floor(performance.now()),
  7073. cookie: window?.NXAppInfo?.session_id || null
  7074. },
  7075. ident: giftId
  7076. });
  7077. });
  7078.  
  7079. if (!freebieCheckCalls.calls.length) {
  7080. return;
  7081. }
  7082.  
  7083. send(JSON.stringify(freebieCheckCalls), e => {
  7084. let countGetGifts = 0;
  7085. const gifts = [];
  7086. for (check of e.results) {
  7087. gifts.push(check.ident);
  7088. if (check.result.response != null) {
  7089. countGetGifts++;
  7090. }
  7091. }
  7092. const saveGifts = localStorage[valName].split(';');
  7093. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7094. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7095. });
  7096. }
  7097. )
  7098. }
  7099.  
  7100. async function getGiftCode() {
  7101. return null;
  7102. const isWrite = false;
  7103. let data = null;
  7104. try {
  7105. data = await fetch('https://zingery.ru/heroes/getGifts.php', {
  7106. method: 'POST',
  7107. body: JSON.stringify({ isWrite })
  7108. }).then(response => response.json());
  7109. } catch(e) {
  7110. return null;
  7111. }
  7112.  
  7113. const valName = 'newGiftSendIds';
  7114. if (!localStorage[valName]) {
  7115. localStorage[valName] = '';
  7116. }
  7117. const saveGifts = localStorage[valName].split(';');
  7118.  
  7119. while (data.length) {
  7120. let giftId = data.pop()
  7121. if (!localStorage[valName].includes(giftId)) {
  7122. saveGifts.push(giftId);
  7123. localStorage[valName] = saveGifts.slice(-50).join(';');
  7124. return giftId;
  7125. }
  7126. }
  7127. return null;
  7128. }
  7129.  
  7130. /**
  7131. * To fill the kills in the Forge of Souls
  7132. *
  7133. * Набить килов в горниле душ
  7134. */
  7135. async function bossRatingEvent() {
  7136. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7137. if (!topGet || !topGet.results[0].result.response[0]) {
  7138. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7139. return;
  7140. }
  7141. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7142. const result = await Send(JSON.stringify({
  7143. calls: [
  7144. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7145. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7146. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7147. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7148. ]
  7149. }));
  7150. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7151. if (!bossEventInfo) {
  7152. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7153. return;
  7154. }
  7155. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7156. const party = Object.values(result.results[0].result.response.replay.attackers);
  7157. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7158. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7159. const calls = [];
  7160. /**
  7161. * First pack
  7162. *
  7163. * Первая пачка
  7164. */
  7165. const args = {
  7166. heroes: [],
  7167. favor: {}
  7168. }
  7169. for (let hero of party) {
  7170. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7171. args.pet = hero.id;
  7172. continue;
  7173. }
  7174. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7175. continue;
  7176. }
  7177. args.heroes.push(hero.id);
  7178. if (hero.favorPetId) {
  7179. args.favor[hero.id] = hero.favorPetId;
  7180. }
  7181. }
  7182. if (args.heroes.length) {
  7183. calls.push({
  7184. name: "bossRatingEvent_startBattle",
  7185. args,
  7186. ident: "body_0"
  7187. });
  7188. }
  7189. /**
  7190. * Other packs
  7191. *
  7192. * Другие пачки
  7193. */
  7194. let heroes = [];
  7195. let count = 1;
  7196. while (heroId = availableHeroes.pop()) {
  7197. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7198. continue;
  7199. }
  7200. heroes.push(heroId);
  7201. if (heroes.length == 5) {
  7202. calls.push({
  7203. name: "bossRatingEvent_startBattle",
  7204. args: {
  7205. heroes: [...heroes],
  7206. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7207. },
  7208. ident: "body_" + count
  7209. });
  7210. heroes = [];
  7211. count++;
  7212. }
  7213. }
  7214.  
  7215. if (!calls.length) {
  7216. setProgress(`${I18N('NO_HEROES')}`, true);
  7217. return;
  7218. }
  7219.  
  7220. const resultBattles = await Send(JSON.stringify({ calls }));
  7221. console.log(resultBattles);
  7222. rewardBossRatingEvent();
  7223. }
  7224.  
  7225. /**
  7226. * Collecting Rewards from the Forge of Souls
  7227. *
  7228. * Сбор награды из Горнила Душ
  7229. */
  7230. function rewardBossRatingEvent() {
  7231. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7232. send(rewardBossRatingCall, function (data) {
  7233. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7234. if (!bossEventInfo) {
  7235. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7236. return;
  7237. }
  7238.  
  7239. let farmedChests = bossEventInfo.progress.farmedChests;
  7240. let score = bossEventInfo.progress.score;
  7241. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7242. let revard = bossEventInfo.reward;
  7243.  
  7244. let getRewardCall = {
  7245. calls: []
  7246. }
  7247.  
  7248. let count = 0;
  7249. for (let i = 1; i < 10; i++) {
  7250. if (farmedChests.includes(i)) {
  7251. continue;
  7252. }
  7253. if (score < revard[i].score) {
  7254. break;
  7255. }
  7256. getRewardCall.calls.push({
  7257. name: "bossRatingEvent_getReward",
  7258. args: {
  7259. rewardId: i
  7260. },
  7261. ident: "body_" + i
  7262. });
  7263. count++;
  7264. }
  7265. if (!count) {
  7266. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7267. return;
  7268. }
  7269.  
  7270. send(JSON.stringify(getRewardCall), e => {
  7271. console.log(e);
  7272. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7273. });
  7274. });
  7275. }
  7276.  
  7277. /**
  7278. * Collect Easter eggs and event rewards
  7279. *
  7280. * Собрать пасхалки и награды событий
  7281. */
  7282. function offerFarmAllReward() {
  7283. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7284. return Send(offerGetAllCall).then((data) => {
  7285. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7286. if (!offerGetAll.length) {
  7287. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7288. return;
  7289. }
  7290.  
  7291. const calls = [];
  7292. for (let reward of offerGetAll) {
  7293. calls.push({
  7294. name: "offerFarmReward",
  7295. args: {
  7296. offerId: reward.id
  7297. },
  7298. ident: "offerFarmReward_" + reward.id
  7299. });
  7300. }
  7301.  
  7302. return Send(JSON.stringify({ calls })).then(e => {
  7303. console.log(e);
  7304. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7305. });
  7306. });
  7307. }
  7308.  
  7309. /**
  7310. * Assemble Outland
  7311. *
  7312. * Собрать запределье
  7313. */
  7314. function getOutland() {
  7315. return new Promise(function (resolve, reject) {
  7316. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7317. let bosses = e.results[0].result.response;
  7318.  
  7319. let bossRaidOpenChestCall = {
  7320. calls: []
  7321. };
  7322.  
  7323. for (let boss of bosses) {
  7324. if (boss.mayRaid) {
  7325. bossRaidOpenChestCall.calls.push({
  7326. name: "bossRaid",
  7327. args: {
  7328. bossId: boss.id
  7329. },
  7330. ident: "bossRaid_" + boss.id
  7331. });
  7332. bossRaidOpenChestCall.calls.push({
  7333. name: "bossOpenChest",
  7334. args: {
  7335. bossId: boss.id,
  7336. amount: 1,
  7337. starmoney: 0
  7338. },
  7339. ident: "bossOpenChest_" + boss.id
  7340. });
  7341. } else if (boss.chestId == 1) {
  7342. bossRaidOpenChestCall.calls.push({
  7343. name: "bossOpenChest",
  7344. args: {
  7345. bossId: boss.id,
  7346. amount: 1,
  7347. starmoney: 0
  7348. },
  7349. ident: "bossOpenChest_" + boss.id
  7350. });
  7351. }
  7352. }
  7353.  
  7354. if (!bossRaidOpenChestCall.calls.length) {
  7355. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7356. resolve();
  7357. return;
  7358. }
  7359.  
  7360. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7361. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7362. resolve();
  7363. });
  7364. });
  7365. });
  7366. }
  7367.  
  7368. /**
  7369. * Collect all rewards
  7370. *
  7371. * Собрать все награды
  7372. */
  7373. function questAllFarm() {
  7374. return new Promise(function (resolve, reject) {
  7375. let questGetAllCall = {
  7376. calls: [{
  7377. name: "questGetAll",
  7378. args: {},
  7379. ident: "body"
  7380. }]
  7381. }
  7382. send(JSON.stringify(questGetAllCall), function (data) {
  7383. let questGetAll = data.results[0].result.response;
  7384. const questAllFarmCall = {
  7385. calls: []
  7386. }
  7387. let number = 0;
  7388. for (let quest of questGetAll) {
  7389. if (quest.id < 1e6 && quest.state == 2) {
  7390. questAllFarmCall.calls.push({
  7391. name: "questFarm",
  7392. args: {
  7393. questId: quest.id
  7394. },
  7395. ident: `group_${number}_body`
  7396. });
  7397. number++;
  7398. }
  7399. }
  7400.  
  7401. if (!questAllFarmCall.calls.length) {
  7402. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7403. resolve();
  7404. return;
  7405. }
  7406.  
  7407. send(JSON.stringify(questAllFarmCall), function (res) {
  7408. console.log(res);
  7409. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7410. resolve();
  7411. });
  7412. });
  7413. })
  7414. }
  7415.  
  7416. /**
  7417. * Mission auto repeat
  7418. *
  7419. * Автоповтор миссии
  7420. * isStopSendMission = false;
  7421. * isSendsMission = true;
  7422. **/
  7423. this.sendsMission = async function (param) {
  7424. if (isStopSendMission) {
  7425. isSendsMission = false;
  7426. console.log(I18N('STOPPED'));
  7427. setProgress('');
  7428. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7429. msg: 'Ok',
  7430. result: true
  7431. }, ])
  7432. return;
  7433. }
  7434. lastMissionBattleStart = Date.now();
  7435. let missionStartCall = {
  7436. "calls": [{
  7437. "name": "missionStart",
  7438. "args": lastMissionStart,
  7439. "ident": "body"
  7440. }]
  7441. }
  7442. /**
  7443. * Mission Request
  7444. *
  7445. * Запрос на выполнение мисcии
  7446. */
  7447. SendRequest(JSON.stringify(missionStartCall), async e => {
  7448. if (e['error']) {
  7449. isSendsMission = false;
  7450. console.log(e['error']);
  7451. setProgress('');
  7452. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7453. await popup.confirm(msg, [
  7454. {msg: 'Ok', result: true},
  7455. ])
  7456. return;
  7457. }
  7458. /**
  7459. * Mission data calculation
  7460. *
  7461. * Расчет данных мисcии
  7462. */
  7463. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  7464. /** missionTimer */
  7465. let timer = getTimer(r.battleTime) + 5;
  7466. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  7467. if (period < timer) {
  7468. timer = timer - period;
  7469. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  7470. }
  7471.  
  7472. let missionEndCall = {
  7473. "calls": [{
  7474. "name": "missionEnd",
  7475. "args": {
  7476. "id": param.id,
  7477. "result": r.result,
  7478. "progress": r.progress
  7479. },
  7480. "ident": "body"
  7481. }]
  7482. }
  7483. /**
  7484. * Mission Completion Request
  7485. *
  7486. * Запрос на завершение миссии
  7487. */
  7488. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  7489. if (e['error']) {
  7490. isSendsMission = false;
  7491. console.log(e['error']);
  7492. setProgress('');
  7493. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7494. await popup.confirm(msg, [
  7495. {msg: 'Ok', result: true},
  7496. ])
  7497. return;
  7498. }
  7499. r = e.results[0].result.response;
  7500. if (r['error']) {
  7501. isSendsMission = false;
  7502. console.log(r['error']);
  7503. setProgress('');
  7504. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  7505. {msg: 'Ok', result: true},
  7506. ])
  7507. return;
  7508. }
  7509.  
  7510. param.count++;
  7511. let RaidMission = getInput('countRaid');
  7512.  
  7513. if (RaidMission==param.count){
  7514. isStopSendMission = true;
  7515. console.log(RaidMission);
  7516. }
  7517. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  7518. isStopSendMission = true;
  7519. });
  7520. setTimeout(sendsMission, 1, param);
  7521. });
  7522. })
  7523. });
  7524. }
  7525.  
  7526. /**
  7527. * Recursive opening of russian dolls
  7528. *
  7529. * Рекурсивное открытие матрешек
  7530. */
  7531. function openRussianDoll(id, count, sum) {
  7532. sum = sum || 0;
  7533. sum += count;
  7534. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  7535. setProgress(`${I18N('OPEN')} ${count}`, true);
  7536. let result = e.results[0].result.response;
  7537. let newCount = 0;
  7538. for(let n of result) {
  7539. if (n?.consumable && n.consumable[id]) {
  7540. newCount += n.consumable[id]
  7541. }
  7542. }
  7543. if (newCount) {
  7544. openRussianDoll(id, newCount, sum);
  7545. } else {
  7546. popup.confirm(`${I18N('TOTAL_OPEN')} ${sum}`);
  7547. }
  7548. })
  7549. }
  7550.  
  7551. /**
  7552. * Opening of russian dolls
  7553. *
  7554. * Открытие матрешек
  7555. */
  7556. async function openRussianDolls(libId, amount) {
  7557. let sum = 0;
  7558. let sumResult = [];
  7559.  
  7560. while (amount) {
  7561. sum += amount;
  7562. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7563. const calls = [{
  7564. name: "consumableUseLootBox",
  7565. args: { libId, amount },
  7566. ident: "body"
  7567. }];
  7568. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  7569. let newCount = 0;
  7570. for (let n of result) {
  7571. if (n?.consumable && n.consumable[libId]) {
  7572. newCount += n.consumable[libId]
  7573. }
  7574. }
  7575. sumResult = [...sumResult, ...result];
  7576. amount = newCount;
  7577. }
  7578.  
  7579. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7580. return sumResult;
  7581. }
  7582.  
  7583. /**
  7584. * Collect all mail, except letters with energy and charges of the portal
  7585. *
  7586. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7587. */
  7588. function mailGetAll() {
  7589. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7590.  
  7591. return Send(getMailInfo).then(dataMail => {
  7592. const letters = dataMail.results[0].result.response.letters;
  7593. const letterIds = lettersFilter(letters);
  7594. if (!letterIds.length) {
  7595. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7596. return;
  7597. }
  7598.  
  7599. const calls = [
  7600. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7601. ];
  7602.  
  7603. return Send(JSON.stringify({ calls })).then(res => {
  7604. const lettersIds = res.results[0].result.response;
  7605. if (lettersIds) {
  7606. const countLetters = Object.keys(lettersIds).length;
  7607. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7608. }
  7609. });
  7610. });
  7611. }
  7612.  
  7613. /**
  7614. * Filters received emails
  7615. *
  7616. * Фильтрует получаемые письма
  7617. */
  7618. function lettersFilter(letters) {
  7619. const lettersIds = [];
  7620. for (let l in letters) {
  7621. letter = letters[l];
  7622. const reward = letter.reward;
  7623. if (!reward) {
  7624. continue;
  7625. }
  7626. /**
  7627. * Mail Collection Exceptions
  7628. *
  7629. * Исключения на сбор писем
  7630. */
  7631. const isFarmLetter = !(
  7632. /** Portals // сферы портала */
  7633. (reward?.refillable ? reward.refillable[45] : false) ||
  7634. /** Energy // энергия */
  7635. (reward?.stamina ? reward.stamina : false) ||
  7636. /** accelerating energy gain // ускорение набора энергии */
  7637. (reward?.buff ? true : false) ||
  7638. /** VIP Points // вип очки */
  7639. (reward?.vipPoints ? reward.vipPoints : false) ||
  7640. /** souls of heroes // душы героев */
  7641. (reward?.fragmentHero ? true : false) ||
  7642. /** heroes // герои */
  7643. (reward?.bundleHeroReward ? true : false)
  7644. );
  7645. if (isFarmLetter) {
  7646. lettersIds.push(~~letter.id);
  7647. continue;
  7648. }
  7649. /**
  7650. * Если до окончания годности письма менее 24 часов,
  7651. * то оно собирается не смотря на исключения
  7652. */
  7653. const availableUntil = +letter?.availableUntil;
  7654. if (availableUntil) {
  7655. const maxTimeLeft = 24 * 60 * 60 * 1000;
  7656. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  7657. console.log('Time left:', timeLeft)
  7658. if (timeLeft < maxTimeLeft) {
  7659. lettersIds.push(~~letter.id);
  7660. continue;
  7661. }
  7662. }
  7663. }
  7664. return lettersIds;
  7665. }
  7666.  
  7667. /**
  7668. * Displaying information about the areas of the portal and attempts on the VG
  7669. *
  7670. * Отображение информации о сферах портала и попытках на ВГ
  7671. */
  7672. async function justInfo() {
  7673. return new Promise(async (resolve, reject) => {
  7674. const calls = [{
  7675. name: "userGetInfo",
  7676. args: {},
  7677. ident: "userGetInfo"
  7678. },
  7679. {
  7680. name: "clanWarGetInfo",
  7681. args: {},
  7682. ident: "clanWarGetInfo"
  7683. },
  7684. {
  7685. name: "titanArenaGetStatus",
  7686. args: {},
  7687. ident: "titanArenaGetStatus"
  7688. }];
  7689. const result = await Send(JSON.stringify({ calls }));
  7690. const infos = result.results;
  7691. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  7692. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  7693. const arePointsMax = infos[1].result.response?.arePointsMax;
  7694. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  7695. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  7696.  
  7697. const sanctuaryButton = buttons['goToSanctuary'].button;
  7698. const clanWarButton = buttons['goToClanWar'].button;
  7699. const titansArenaButton = buttons['testTitanArena'].button;
  7700.  
  7701. /*if (portalSphere.amount) {
  7702. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  7703. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  7704. } else {*/
  7705. sanctuaryButton.style.color = '';
  7706. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  7707. //}
  7708. /*if (clanWarMyTries && !arePointsMax) {
  7709. clanWarButton.style.color = 'red';
  7710. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  7711. } else {*/
  7712. clanWarButton.style.color = '';
  7713. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  7714. //}
  7715.  
  7716. /*if (titansLevel < 7 && titansStatus == 'battle') {
  7717. const partColor = Math.floor(125 * titansLevel / 7);
  7718. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  7719. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  7720. } else {*/
  7721. titansArenaButton.style.color = '';
  7722. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  7723. //}
  7724. //тест убрал подсветку красным в меню
  7725. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  7726. resolve();
  7727. });
  7728. }
  7729. // тест сделать все
  7730. /** Отправить подарки мое*/
  7731. function testclanSendDailyGifts() {
  7732.  
  7733. send('{"calls":[{"name":"clanSendDailyGifts","args":{},"ident":"clanSendDailyGifts"}]}', e => {
  7734. setProgress('Награды собраны', true);});
  7735. }
  7736. /** Открой сферу артефактов титанов*/
  7737. function testtitanArtifactChestOpen() {
  7738. send('{"calls":[{"name":"titanArtifactChestOpen","args":{"amount":1,"free":true},"ident":"body"}]}',
  7739. isWeCanDo => {
  7740. return info['inventoryGet']?.consumable[55] > 0
  7741. //setProgress('Награды собраны', true);
  7742. });
  7743. }
  7744. /** Воспользуйся призывом питомцев 1 раз*/
  7745. function testpet_chestOpen() {
  7746. send('{"calls":[{"name":"pet_chestOpen","args":{"amount":1,"paid":false},"ident":"pet_chestOpen"}]}',
  7747. isWeCanDo => {
  7748. return info['inventoryGet']?.consumable[90] > 0
  7749. //setProgress('Награды собраны', true);
  7750. });
  7751. }
  7752. async function getDailyBonus() {
  7753. const dailyBonusInfo = await Send(JSON.stringify({
  7754. calls: [{
  7755. name: "dailyBonusGetInfo",
  7756. args: {},
  7757. ident: "body"
  7758. }]
  7759. })).then(e => e.results[0].result.response);
  7760. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  7761.  
  7762. if (!availableToday) {
  7763. console.log('Уже собрано');
  7764. return;
  7765. }
  7766.  
  7767. const currentVipPoints = +userInfo.vipPoints;
  7768. const dailyBonusStat = lib.getData('dailyBonusStatic');
  7769. const vipInfo = lib.getData('level').vip;
  7770. let currentVipLevel = 0;
  7771. for (let i in vipInfo) {
  7772. vipLvl = vipInfo[i];
  7773. if (currentVipPoints >= vipLvl.vipPoints) {
  7774. currentVipLevel = vipLvl.level;
  7775. }
  7776. }
  7777. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  7778.  
  7779. const calls = [{
  7780. name: "dailyBonusFarm",
  7781. args: {
  7782. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  7783. },
  7784. ident: "body"
  7785. }];
  7786.  
  7787. const result = await Send(JSON.stringify({ calls }));
  7788. if (result.error) {
  7789. console.error(result.error);
  7790. return;
  7791. }
  7792.  
  7793. const reward = result.results[0].result.response;
  7794. const type = Object.keys(reward).pop();
  7795. const itemId = Object.keys(reward[type]).pop();
  7796. const count = reward[type][itemId];
  7797. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  7798.  
  7799. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  7800. }
  7801.  
  7802. async function farmStamina(lootBoxId = 148) {
  7803. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  7804. .then(e => e.results[0].result.response.consumable[148]);
  7805.  
  7806. /** Добавить другие ящики */
  7807. /**
  7808. * 144 - медная шкатулка
  7809. * 145 - бронзовая шкатулка
  7810. * 148 - платиновая шкатулка
  7811. */
  7812. if (!lootBox) {
  7813. setProgress(I18N('NO_BOXES'), true);
  7814. return;
  7815. }
  7816.  
  7817. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  7818. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  7819. { result: false, isClose: true },
  7820. { msg: I18N('BTN_YES'), result: true },
  7821. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7822. ]);
  7823.  
  7824. if (!+result) {
  7825. return;
  7826. }
  7827.  
  7828. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7829. maxFarmEnergy = +result;
  7830. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7831. } else {
  7832. maxFarmEnergy = 0;
  7833. }
  7834.  
  7835. let collectEnergy = 0;
  7836. for (let count = lootBox; count > 0; count--) {
  7837. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  7838. .then(e => e.results[0].result.response[0]);
  7839. if ('stamina' in result) {
  7840. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7841. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7842. if (!maxFarmEnergy) {
  7843. return;
  7844. }
  7845. collectEnergy += +result.stamina;
  7846. if (collectEnergy >= maxFarmEnergy) {
  7847. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7848. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7849. return;
  7850. }
  7851. } else {
  7852. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7853. console.log(result);
  7854. }
  7855. }
  7856.  
  7857. setProgress(I18N('BOXES_OVER'), true);
  7858. }
  7859.  
  7860. async function fillActive() {
  7861. const data = await Send(JSON.stringify({
  7862. calls: [{
  7863. name: "questGetAll",
  7864. args: {},
  7865. ident: "questGetAll"
  7866. }, {
  7867. name: "inventoryGet",
  7868. args: {},
  7869. ident: "inventoryGet"
  7870. }, {
  7871. name: "clanGetInfo",
  7872. args: {},
  7873. ident: "clanGetInfo"
  7874. }
  7875. ]
  7876. })).then(e => e.results.map(n => n.result.response));
  7877.  
  7878. const quests = data[0];
  7879. const inv = data[1];
  7880. const stat = data[2].stat;
  7881. const maxActive = 2000 - stat.todayItemsActivity;
  7882. if (maxActive <= 0) {
  7883. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7884. return;
  7885. }
  7886.  
  7887. let countGetActive = 0;
  7888. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7889. if (quest) {
  7890. countGetActive = 1750 - quest.progress;
  7891. }
  7892.  
  7893. if (countGetActive <= 0) {
  7894. countGetActive = maxActive;
  7895. }
  7896. console.log(countGetActive);
  7897.  
  7898. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7899. { result: false, isClose: true },
  7900. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7901. ]));
  7902.  
  7903. if (!countGetActive) {
  7904. return;
  7905. }
  7906.  
  7907. if (countGetActive > maxActive) {
  7908. countGetActive = maxActive;
  7909. }
  7910.  
  7911. const items = lib.getData('inventoryItem');
  7912.  
  7913. let itemsInfo = [];
  7914. for (let type of ['gear', 'scroll']) {
  7915. for (let i in inv[type]) {
  7916. const v = items[type][i]?.enchantValue || 0;
  7917. itemsInfo.push({
  7918. id: i,
  7919. count: inv[type][i],
  7920. v,
  7921. type
  7922. })
  7923. }
  7924. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7925. for (let i in inv[invType]) {
  7926. const v = items[type][i]?.fragmentEnchantValue || 0;
  7927. itemsInfo.push({
  7928. id: i,
  7929. count: inv[invType][i],
  7930. v,
  7931. type: invType
  7932. })
  7933. }
  7934. }
  7935. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7936. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7937. console.log(itemsInfo);
  7938. const activeItem = itemsInfo.shift();
  7939. console.log(activeItem);
  7940. const countItem = Math.ceil(countGetActive / activeItem.v);
  7941. if (countItem > activeItem.count) {
  7942. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7943. console.log(activeItem);
  7944. return;
  7945. }
  7946.  
  7947. await Send(JSON.stringify({
  7948. calls: [{
  7949. name: "clanItemsForActivity",
  7950. args: {
  7951. items: {
  7952. [activeItem.type]: {
  7953. [activeItem.id]: countItem
  7954. }
  7955. }
  7956. },
  7957. ident: "body"
  7958. }]
  7959. })).then(e => {
  7960. /** TODO: Вывести потраченые предметы */
  7961. console.log(e);
  7962. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7963. });
  7964. }
  7965.  
  7966. async function buyHeroFragments() {
  7967. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7968. .then(e => e.results.map(n => n.result.response));
  7969. const inv = result[0];
  7970. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7971. const calls = [];
  7972.  
  7973. for (let shop of shops) {
  7974. const slots = Object.values(shop.slots);
  7975. for (const slot of slots) {
  7976. /* Уже куплено */
  7977. if (slot.bought) {
  7978. continue;
  7979. }
  7980. /* Не душа героя */
  7981. if (!('fragmentHero' in slot.reward)) {
  7982. continue;
  7983. }
  7984. const coin = Object.keys(slot.cost).pop();
  7985. const coinId = Object.keys(slot.cost[coin]).pop();
  7986. const stock = inv[coin][coinId] || 0;
  7987. /* Не хватает на покупку */
  7988. if (slot.cost[coin][coinId] > stock) {
  7989. continue;
  7990. }
  7991. inv[coin][coinId] -= slot.cost[coin][coinId];
  7992. calls.push({
  7993. name: "shopBuy",
  7994. args: {
  7995. shopId: shop.id,
  7996. slot: slot.id,
  7997. cost: slot.cost,
  7998. reward: slot.reward,
  7999. },
  8000. ident: `shopBuy_${shop.id}_${slot.id}`,
  8001. })
  8002. }
  8003. }
  8004.  
  8005. if (!calls.length) {
  8006. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8007. return;
  8008. }
  8009.  
  8010. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8011. if (!bought) {
  8012. console.log('что-то пошло не так')
  8013. return;
  8014. }
  8015.  
  8016. let countHeroSouls = 0;
  8017. for (const buy of bought) {
  8018. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8019. }
  8020. console.log(countHeroSouls, bought, calls);
  8021. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8022. }
  8023.  
  8024. /** Открыть платные сундуки в Запределье за 90 */
  8025. async function bossOpenChestPay() {
  8026. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  8027. .then(e => e.results.map(n => n.result.response));
  8028.  
  8029. const user = info[0];
  8030. const boses = info[1];
  8031.  
  8032. const currentStarMoney = user.starMoney;
  8033. if (currentStarMoney < 540) {
  8034. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  8035. return;
  8036. }
  8037.  
  8038. const calls = [];
  8039.  
  8040. let n = 0;
  8041. const amount = 1;
  8042. for (let boss of boses) {
  8043. const bossId = boss.id;
  8044. if (boss.chestNum != 2) {
  8045. continue;
  8046. }
  8047. for (const starmoney of [90, 90, 0]) {
  8048. calls.push({
  8049. name: "bossOpenChest",
  8050. args: {
  8051. bossId,
  8052. amount,
  8053. starmoney
  8054. },
  8055. ident: "bossOpenChest_" + (++n)
  8056. });
  8057. }
  8058. }
  8059.  
  8060. if (!calls.length) {
  8061. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8062. return;
  8063. }
  8064.  
  8065. const result = await Send(JSON.stringify({ calls }));
  8066. console.log(result);
  8067. if (result?.results) {
  8068. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  8069. } else {
  8070. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8071. }
  8072. }
  8073.  
  8074. async function autoRaidAdventure() {
  8075. const calls = [
  8076. {
  8077. name: "userGetInfo",
  8078. args: {},
  8079. ident: "userGetInfo"
  8080. },
  8081. {
  8082. name: "adventure_raidGetInfo",
  8083. args: {},
  8084. ident: "adventure_raidGetInfo"
  8085. }
  8086. ];
  8087. const result = await Send(JSON.stringify({ calls }))
  8088. .then(e => e.results.map(n => n.result.response));
  8089.  
  8090. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8091. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8092. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8093.  
  8094. if (!portalSphere.amount || !adventureId) {
  8095. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8096. return;
  8097. }
  8098.  
  8099. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8100. { result: false, isClose: true },
  8101. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8102. ]));
  8103.  
  8104. if (!countRaid) {
  8105. return;
  8106. }
  8107.  
  8108. if (countRaid > portalSphere.amount) {
  8109. countRaid = portalSphere.amount;
  8110. }
  8111.  
  8112. const resultRaid = await Send(JSON.stringify({
  8113. calls: [...Array(countRaid)].map((e, i) => ({
  8114. name: "adventure_raid",
  8115. args: {
  8116. adventureId
  8117. },
  8118. ident: `body_${i}`
  8119. }))
  8120. })).then(e => e.results.map(n => n.result.response));
  8121.  
  8122. if (!resultRaid.length) {
  8123. console.log(resultRaid);
  8124. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8125. return;
  8126. }
  8127.  
  8128. console.log(resultRaid, adventureId, portalSphere.amount);
  8129. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8130. }
  8131.  
  8132. /** Вывести всю клановую статистику в консоль браузера */
  8133. async function clanStatistic() {
  8134. const copy = function (text) {
  8135. const copyTextarea = document.createElement("textarea");
  8136. copyTextarea.style.opacity = "0";
  8137. copyTextarea.textContent = text;
  8138. document.body.appendChild(copyTextarea);
  8139. copyTextarea.select();
  8140. document.execCommand("copy");
  8141. document.body.removeChild(copyTextarea);
  8142. delete copyTextarea;
  8143. }
  8144. const calls = [
  8145. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8146. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8147. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8148. ];
  8149.  
  8150. const result = await Send(JSON.stringify({ calls }));
  8151.  
  8152. const dataClanInfo = result.results[0].result.response;
  8153. const dataClanStat = result.results[1].result.response;
  8154. const dataClanLog = result.results[2].result.response;
  8155.  
  8156. const membersStat = {};
  8157. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8158. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8159. }
  8160.  
  8161. const joinStat = {};
  8162. historyLog = dataClanLog.history;
  8163. for (let j in historyLog) {
  8164. his = historyLog[j];
  8165. if (his.event == 'join') {
  8166. joinStat[his.userId] = his.ctime;
  8167. }
  8168. }
  8169.  
  8170. const infoArr = [];
  8171. const members = dataClanInfo.clan.members;
  8172. for (let n in members) {
  8173. var member = [
  8174. n,
  8175. members[n].name,
  8176. members[n].level,
  8177. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8178. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8179. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8180. membersStat[n].activity.reverse().join('\t'),
  8181. membersStat[n].adventureStat.reverse().join('\t'),
  8182. membersStat[n].clanGifts.reverse().join('\t'),
  8183. membersStat[n].clanWarStat.reverse().join('\t'),
  8184. membersStat[n].dungeonActivity.reverse().join('\t'),
  8185. ];
  8186. infoArr.push(member);
  8187. }
  8188. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8189. console.log(info);
  8190. copy(info);
  8191. setProgress(I18N('CLAN_STAT_COPY'), true);
  8192. }
  8193.  
  8194. async function buyInStoreForGold() {
  8195. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8196. const shops = result[0];
  8197. const user = result[1];
  8198. let gold = user.gold;
  8199. const calls = [];
  8200. if (shops[17]) {
  8201. const slots = shops[17].slots;
  8202. for (let i = 1; i <= 2; i++) {
  8203. if (!slots[i].bought) {
  8204. const costGold = slots[i].cost.gold;
  8205. if ((gold - costGold) < 0) {
  8206. continue;
  8207. }
  8208. gold -= costGold;
  8209. calls.push({
  8210. name: "shopBuy",
  8211. args: {
  8212. shopId: 17,
  8213. slot: i,
  8214. cost: slots[i].cost,
  8215. reward: slots[i].reward,
  8216. },
  8217. ident: 'body_' + i,
  8218. })
  8219. }
  8220. }
  8221. }
  8222. const slots = shops[1].slots;
  8223. for (let i = 4; i <= 6; i++) {
  8224. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8225. const costGold = slots[i].cost.gold;
  8226. if ((gold - costGold) < 0) {
  8227. continue;
  8228. }
  8229. gold -= costGold;
  8230. calls.push({
  8231. name: "shopBuy",
  8232. args: {
  8233. shopId: 1,
  8234. slot: i,
  8235. cost: slots[i].cost,
  8236. reward: slots[i].reward,
  8237. },
  8238. ident: 'body_' + i,
  8239. })
  8240. }
  8241. }
  8242.  
  8243. if (!calls.length) {
  8244. setProgress(I18N('NOTHING_BUY'), true);
  8245. return;
  8246. }
  8247.  
  8248. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8249. console.log(resultBuy);
  8250. const countBuy = resultBuy.length;
  8251. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8252. }
  8253.  
  8254. function rewardsAndMailFarm() {
  8255. return new Promise(function (resolve, reject) {
  8256. let questGetAllCall = {
  8257. calls: [{
  8258. name: "questGetAll",
  8259. args: {},
  8260. ident: "questGetAll"
  8261. }, {
  8262. name: "mailGetAll",
  8263. args: {},
  8264. ident: "mailGetAll"
  8265. }]
  8266. }
  8267. send(JSON.stringify(questGetAllCall), function (data) {
  8268. if (!data) return;
  8269. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  8270. const questBattlePass = lib.getData('quest').battlePass;
  8271. const questChainBPass = lib.getData('battlePass').questChain;
  8272.  
  8273. const questAllFarmCall = {
  8274. calls: []
  8275. }
  8276. let number = 0;
  8277. for (let quest of questGetAll) {
  8278. if (quest.id > 1e6) {
  8279. const questInfo = questBattlePass[quest.id];
  8280. const chain = questChainBPass[questInfo.chain];
  8281. if (chain.requirement?.battlePassTicket) {
  8282. continue;
  8283. }
  8284. }
  8285. questAllFarmCall.calls.push({
  8286. name: "questFarm",
  8287. args: {
  8288. questId: quest.id
  8289. },
  8290. ident: `questFarm_${number}`
  8291. });
  8292. number++;
  8293. }
  8294.  
  8295. let letters = data?.results[1]?.result?.response?.letters;
  8296. letterIds = lettersFilter(letters);
  8297.  
  8298. if (letterIds.length) {
  8299. questAllFarmCall.calls.push({
  8300. name: "mailFarm",
  8301. args: { letterIds },
  8302. ident: "mailFarm"
  8303. })
  8304. }
  8305.  
  8306. if (!questAllFarmCall.calls.length) {
  8307. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8308. resolve();
  8309. return;
  8310. }
  8311.  
  8312. send(JSON.stringify(questAllFarmCall), function (res) {
  8313. let reSend = false;
  8314. let countQuests = 0;
  8315. let countMail = 0;
  8316. for (let call of res.results) {
  8317. if (call.ident.includes('questFarm')) {
  8318. countQuests++;
  8319. } else {
  8320. countMail = Object.keys(call.result.response).length;
  8321. }
  8322.  
  8323. /** TODO: Переписать чтоб не вызывать функцию дважды */
  8324. const newQuests = call.result.newQuests;
  8325. if (newQuests) {
  8326. for (let quest of newQuests) {
  8327. if (quest.id < 1e6 && quest.state == 2) {
  8328. reSend = true;
  8329. }
  8330. }
  8331. }
  8332. }
  8333. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8334. if (reSend) {
  8335. rewardsAndMailFarm()
  8336. }
  8337. resolve();
  8338. });
  8339. });
  8340. })
  8341. }
  8342.  
  8343. class epicBrawl {
  8344. timeout = null;
  8345. time = null;
  8346.  
  8347. constructor() {
  8348. if (epicBrawl.inst) {
  8349. return epicBrawl.inst;
  8350. }
  8351. epicBrawl.inst = this;
  8352. return this;
  8353. }
  8354.  
  8355. runTimeout(func, timeDiff) {
  8356. const worker = new Worker(URL.createObjectURL(new Blob([`
  8357. self.onmessage = function(e) {
  8358. const timeDiff = e.data;
  8359.  
  8360. if (timeDiff > 0) {
  8361. setTimeout(() => {
  8362. self.postMessage(1);
  8363. self.close();
  8364. }, timeDiff);
  8365. }
  8366. };
  8367. `])));
  8368. worker.postMessage(timeDiff);
  8369. worker.onmessage = () => {
  8370. func();
  8371. };
  8372. return true;
  8373. }
  8374.  
  8375. timeDiff(date1, date2) {
  8376. const date1Obj = new Date(date1);
  8377. const date2Obj = new Date(date2);
  8378.  
  8379. const timeDiff = Math.abs(date2Obj - date1Obj);
  8380.  
  8381. const totalSeconds = timeDiff / 1000;
  8382. const minutes = Math.floor(totalSeconds / 60);
  8383. const seconds = Math.floor(totalSeconds % 60);
  8384.  
  8385. const formattedMinutes = String(minutes).padStart(2, '0');
  8386. const formattedSeconds = String(seconds).padStart(2, '0');
  8387.  
  8388. return `${formattedMinutes}:${formattedSeconds}`;
  8389. }
  8390.  
  8391. check() {
  8392. console.log(new Date(this.time))
  8393. if (Date.now() > this.time) {
  8394. this.timeout = null;
  8395. this.start()
  8396. return;
  8397. }
  8398. this.timeout = this.runTimeout(() => this.check(), 6e4);
  8399. return this.timeDiff(this.time, Date.now())
  8400. }
  8401.  
  8402. async start() {
  8403. if (this.timeout) {
  8404. const time = this.timeDiff(this.time, Date.now());
  8405. console.log(new Date(this.time))
  8406. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  8407. return;
  8408. }
  8409. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  8410. const teamInfo = await Send('{"calls":[{"name":"teamGetAll","args":{},"ident":"teamGetAll"},{"name":"teamGetFavor","args":{},"ident":"teamGetFavor"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8411. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  8412. this.time = (refill.lastRefill + 3600) * 1000
  8413. const attempts = refill.amount;
  8414. if (!attempts) {
  8415. console.log(new Date(this.time));
  8416. const time = this.check();
  8417. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  8418. return;
  8419. }
  8420.  
  8421. if (!teamInfo[0].epic_brawl) {
  8422. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  8423. return;
  8424. }
  8425.  
  8426. const args = {
  8427. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  8428. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  8429. favor: teamInfo[1].epic_brawl,
  8430. }
  8431.  
  8432. let wins = 0;
  8433. let coins = 0;
  8434. let streak = { progress: 0, nextStage: 0 };
  8435. for (let i = attempts; i > 0; i--) {
  8436. const info = await Send(JSON.stringify({
  8437. calls: [
  8438. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  8439. ]
  8440. })).then(e => e.results.map(n => n.result.response));
  8441.  
  8442. const { progress, result } = await Calc(info[1].battle);
  8443. const endResult = await Send(JSON.stringify({ calls: [{ name: "epicBrawl_endBattle", args: { progress, result }, ident: "epicBrawl_endBattle" }, { name: "epicBrawl_getWinStreak", args: {}, ident: "epicBrawl_getWinStreak" }] })).then(e => e.results.map(n => n.result.response));
  8444.  
  8445. const resultInfo = endResult[0].result;
  8446. streak = endResult[1];
  8447.  
  8448. wins += resultInfo.win;
  8449. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  8450.  
  8451. console.log(endResult[0].result)
  8452. if (endResult[1].progress == endResult[1].nextStage) {
  8453. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  8454. coins += farm.coin[39];
  8455. }
  8456.  
  8457. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8458. i, wins, attempts, coins,
  8459. progress: streak.progress,
  8460. nextStage: streak.nextStage,
  8461. end: '',
  8462. }), false, hideProgress);
  8463. }
  8464.  
  8465. console.log(new Date(this.time));
  8466. const time = this.check();
  8467. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8468. wins, attempts, coins,
  8469. i: '',
  8470. progress: streak.progress,
  8471. nextStage: streak.nextStage,
  8472. end: I18N('ATTEMPT_ENDED', { time }),
  8473. }), false, hideProgress);
  8474. }
  8475. }
  8476. /* тест остановка подземки*/
  8477. function stopDungeon(e) {
  8478. stopDung = true;
  8479. }
  8480. function Sleep(ms) {
  8481. return new Promise(resolve => setTimeout(resolve, ms));
  8482. }
  8483. function countdownTimer(seconds, message) {
  8484. message = message || I18N('TIMER');
  8485. const stopTimer = Date.now() + seconds * 1e3
  8486. return new Promise(resolve => {
  8487. const interval = setInterval(async () => {
  8488. const now = Date.now();
  8489. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8490. if (now > stopTimer) {
  8491. clearInterval(interval);
  8492. setProgress('', 1);
  8493. resolve();
  8494. }
  8495. }, 100);
  8496. });
  8497. }
  8498.  
  8499. /** Набить килов в горниле душк */
  8500. async function bossRatingEventSouls() {
  8501. const data = await Send({
  8502. calls: [
  8503. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8504. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8505. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8506. ]
  8507. });
  8508. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8509. if (!bossEventInfo) {
  8510. setProgress('Эвент завершен', true);
  8511. return;
  8512. }
  8513.  
  8514. if (bossEventInfo.progress.score > 250) {
  8515. setProgress('Уже убито больше 250 врагов');
  8516. rewardBossRatingEventSouls();
  8517. return;
  8518. }
  8519. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8520. const heroGetAllList = data.results[0].result.response;
  8521. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8522. const heroList = [];
  8523.  
  8524. for (let heroId in heroGetAllList) {
  8525. let hero = heroGetAllList[heroId];
  8526. if (usedHeroes.includes(hero.id)) {
  8527. continue;
  8528. }
  8529. heroList.push(hero.id);
  8530. }
  8531.  
  8532. if (!heroList.length) {
  8533. setProgress('Нет героев', true);
  8534. return;
  8535. }
  8536.  
  8537. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  8538. const petLib = lib.getData('pet');
  8539. let count = 1;
  8540.  
  8541. for (const heroId of heroList) {
  8542. const args = {
  8543. heroes: [heroId],
  8544. pet
  8545. }
  8546. /** Поиск питомца для героя */
  8547. for (const petId of availablePets) {
  8548. if (petLib[petId].favorHeroes.includes(heroId)) {
  8549. args.favor = {
  8550. [heroId]: petId
  8551. }
  8552. break;
  8553. }
  8554. }
  8555.  
  8556. const calls = [{
  8557. name: "bossRatingEvent_startBattle",
  8558. args,
  8559. ident: "body"
  8560. }, {
  8561. name: "offerGetAll",
  8562. args: {},
  8563. ident: "offerGetAll"
  8564. }];
  8565.  
  8566. const res = await Send({ calls });
  8567. count++;
  8568.  
  8569. if ('error' in res) {
  8570. console.error(res.error);
  8571. setProgress('Перезагрузите игру и попробуйте позже', true);
  8572. return;
  8573. }
  8574.  
  8575. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  8576. if (eventInfo.progress.score > 250) {
  8577. break;
  8578. }
  8579. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  8580. }
  8581.  
  8582. rewardBossRatingEventSouls();
  8583. }
  8584. /** Сбор награды из Горнила Душ */
  8585. async function rewardBossRatingEventSouls() {
  8586. const data = await Send({
  8587. calls: [
  8588. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8589. ]
  8590. });
  8591.  
  8592. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8593. if (!bossEventInfo) {
  8594. setProgress('Эвент завершен', true);
  8595. return;
  8596. }
  8597.  
  8598. const farmedChests = bossEventInfo.progress.farmedChests;
  8599. const score = bossEventInfo.progress.score;
  8600. // setProgress('Количество убитых врагов: ' + score);
  8601. const revard = bossEventInfo.reward;
  8602. const calls = [];
  8603.  
  8604. let count = 0;
  8605. for (let i = 1; i < 10; i++) {
  8606. if (farmedChests.includes(i)) {
  8607. continue;
  8608. }
  8609. if (score < revard[i].score) {
  8610. break;
  8611. }
  8612. calls.push({
  8613. name: "bossRatingEvent_getReward",
  8614. args: {
  8615. rewardId: i
  8616. },
  8617. ident: "body_" + i
  8618. });
  8619. count++;
  8620. }
  8621. if (!count) {
  8622. setProgress('Нечего собирать', true);
  8623. return;
  8624. }
  8625.  
  8626. Send({ calls }).then(e => {
  8627. console.log(e);
  8628. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  8629. })
  8630. }
  8631. /**
  8632. * Spin the Seer
  8633. *
  8634. * Покрутить провидца
  8635. */
  8636. async function rollAscension() {
  8637. const refillable = await Send({calls:[
  8638. {
  8639. name:"userGetInfo",
  8640. args:{},
  8641. ident:"userGetInfo"
  8642. }
  8643. ]}).then(e => e.results[0].result.response.refillable);
  8644. const i47 = refillable.find(i => i.id == 47);
  8645. if (i47?.amount) {
  8646. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  8647. setProgress(I18N('DONE'), true);
  8648. } else {
  8649. setProgress(I18N('NOT_ENOUGH_AP'), true);
  8650. }
  8651. }
  8652.  
  8653. /**
  8654. * Collect gifts for the New Year
  8655. *
  8656. * Собрать подарки на новый год
  8657. */
  8658. function getGiftNewYear() {
  8659. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  8660. const gifts = e.results[0].result.response.gifts;
  8661. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  8662. name: "newYearGiftOpen",
  8663. args: {
  8664. giftId: e.id
  8665. },
  8666. ident: `body_${e.id}`
  8667. }));
  8668. if (!calls.length) {
  8669. setProgress(I18N('NY_NO_GIFTS'), 5000);
  8670. return;
  8671. }
  8672. Send({ calls }).then(e => {
  8673. console.log(e.results)
  8674. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  8675. console.log(msg);
  8676. setProgress(msg, 5000);
  8677. });
  8678. })
  8679. }
  8680.  
  8681. async function updateArtifacts() {
  8682. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8683. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8684. { result: false, isClose: true }
  8685. ]);
  8686. if (!count) {
  8687. return;
  8688. }
  8689. const quest = new questRun;
  8690. await quest.autoInit();
  8691. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8692. const inventory = quest.questInfo['inventoryGet'];
  8693. const calls = [];
  8694. for (let i = count; i > 0; i--) {
  8695. const upArtifact = quest.getUpgradeArtifact();
  8696. if (!upArtifact.heroId) {
  8697. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8698. { msg: I18N('YES'), result: true },
  8699. { result: false, isClose: true }
  8700. ])) {
  8701. break;
  8702. } else {
  8703. return;
  8704. }
  8705. }
  8706. const hero = heroes.find(e => e.id == upArtifact.heroId);
  8707. hero.artifacts[upArtifact.slotId].level++;
  8708. inventory[upArtifact.costСurrency][upArtifact.costId] -= upArtifact.costValue;
  8709. calls.push({
  8710. name: "heroArtifactLevelUp",
  8711. args: {
  8712. heroId: upArtifact.heroId,
  8713. slotId: upArtifact.slotId
  8714. },
  8715. ident: `heroArtifactLevelUp_${i}`
  8716. });
  8717. }
  8718.  
  8719. if (!calls.length) {
  8720. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8721. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8722. return;
  8723. }
  8724.  
  8725. await Send(JSON.stringify({ calls })).then(e => {
  8726. if ('error' in e) {
  8727. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8728. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8729. } else {
  8730. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8731. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8732. }
  8733. });
  8734. }
  8735.  
  8736. window.sign = a => {
  8737. const i = this['\x78\x79\x7a'];
  8738. return md5([i['\x6e\x61\x6d\x65'], i['\x76\x65\x72\x73\x69\x6f\x6e'], i['\x61\x75\x74\x68\x6f\x72'], ~(a % 1e3)]['\x6a\x6f\x69\x6e']('\x5f'))
  8739. }
  8740.  
  8741. async function updateSkins() {
  8742. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  8743. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  8744. { result: false, isClose: true }
  8745. ]);
  8746. if (!count) {
  8747. return;
  8748. }
  8749.  
  8750. const quest = new questRun;
  8751. await quest.autoInit();
  8752. const heroes = Object.values(quest.questInfo['heroGetAll']);
  8753. const inventory = quest.questInfo['inventoryGet'];
  8754. const calls = [];
  8755. for (let i = count; i > 0; i--) {
  8756. const upSkin = quest.getUpgradeSkin();
  8757. if (!upSkin.heroId) {
  8758. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  8759. { msg: I18N('YES'), result: true },
  8760. { result: false, isClose: true }
  8761. ])) {
  8762. break;
  8763. } else {
  8764. return;
  8765. }
  8766. }
  8767. const hero = heroes.find(e => e.id == upSkin.heroId);
  8768. hero.skins[upSkin.skinId]++;
  8769. inventory[upSkin.costСurrency][upSkin.costСurrencyId] -= upSkin.cost;
  8770. calls.push({
  8771. name: "heroSkinUpgrade",
  8772. args: {
  8773. heroId: upSkin.heroId,
  8774. skinId: upSkin.skinId
  8775. },
  8776. ident: `heroSkinUpgrade_${i}`
  8777. })
  8778. }
  8779.  
  8780. if (!calls.length) {
  8781. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8782. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8783. return;
  8784. }
  8785.  
  8786. await Send(JSON.stringify({ calls })).then(e => {
  8787. if ('error' in e) {
  8788. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  8789. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  8790. } else {
  8791. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  8792. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  8793. }
  8794. });
  8795. }
  8796.  
  8797. function getQuestionInfo(img, nameOnly = false) {
  8798. const libHeroes = Object.values(lib.data.hero);
  8799. const parts = img.split(':');
  8800. const id = parts[1];
  8801. switch (parts[0]) {
  8802. case 'titanArtifact_id':
  8803. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  8804. case 'titan':
  8805. return cheats.translate("LIB_HERO_NAME_" + id);
  8806. case 'skill':
  8807. return cheats.translate("LIB_SKILL_" + id);
  8808. case 'inventoryItem_gear':
  8809. return cheats.translate("LIB_GEAR_NAME_" + id);
  8810. case 'inventoryItem_coin':
  8811. return cheats.translate("LIB_COIN_NAME_" + id);
  8812. case 'artifact':
  8813. if (nameOnly) {
  8814. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  8815. }
  8816. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  8817. return {
  8818. /** Как называется этот артефакт? */
  8819. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  8820. /** Какому герою принадлежит этот артефакт? */
  8821. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  8822. };
  8823. case 'hero':
  8824. if (nameOnly) {
  8825. return cheats.translate("LIB_HERO_NAME_" + id);
  8826. }
  8827. artifacts = lib.data.hero[id].artifacts;
  8828. return {
  8829. /** Как зовут этого героя? */
  8830. name: cheats.translate("LIB_HERO_NAME_" + id),
  8831. /** Какой артефакт принадлежит этому герою? */
  8832. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  8833. };
  8834. }
  8835. }
  8836.  
  8837. function hintQuest(quest) {
  8838. const result = {};
  8839. if (quest?.questionIcon) {
  8840. const info = getQuestionInfo(quest.questionIcon);
  8841. if (info?.heroes) {
  8842. /** Какому герою принадлежит этот артефакт? */
  8843. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  8844. }
  8845. if (info?.artifact) {
  8846. /** Какой артефакт принадлежит этому герою? */
  8847. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  8848. }
  8849. if (typeof info == 'string') {
  8850. result.info = { name: info };
  8851. } else {
  8852. result.info = info;
  8853. }
  8854. }
  8855.  
  8856. if (quest.answers[0]?.answerIcon) {
  8857. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  8858. }
  8859.  
  8860. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  8861. return false;
  8862. }
  8863.  
  8864. let resultText = '';
  8865. if (result?.info) {
  8866. resultText += I18N('PICTURE') + result.info.name;
  8867. }
  8868. console.log(result);
  8869. if (result?.answer && result.answer.length) {
  8870. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  8871. }
  8872.  
  8873. return resultText;
  8874. }
  8875.  
  8876. /**
  8877. * Attack of the minions of Asgard
  8878. *
  8879. * Атака прислужников Асгарда
  8880. */
  8881. function testRaidNodes() {
  8882. return new Promise((resolve, reject) => {
  8883. const tower = new executeRaidNodes(resolve, reject);
  8884. tower.start();
  8885. });
  8886. }
  8887.  
  8888. /**
  8889. * Attack of the minions of Asgard
  8890. *
  8891. * Атака прислужников Асгарда
  8892. */
  8893. function executeRaidNodes(resolve, reject) {
  8894. let raidData = {
  8895. teams: [],
  8896. favor: {},
  8897. nodes: [],
  8898. attempts: 0,
  8899. countExecuteBattles: 0,
  8900. cancelBattle: 0,
  8901. }
  8902.  
  8903. callsExecuteRaidNodes = {
  8904. calls: [{
  8905. name: "clanRaid_getInfo",
  8906. args: {},
  8907. ident: "clanRaid_getInfo"
  8908. }, {
  8909. name: "teamGetAll",
  8910. args: {},
  8911. ident: "teamGetAll"
  8912. }, {
  8913. name: "teamGetFavor",
  8914. args: {},
  8915. ident: "teamGetFavor"
  8916. }]
  8917. }
  8918.  
  8919. this.start = function () {
  8920. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  8921. }
  8922.  
  8923. async function startRaidNodes(data) {
  8924. res = data.results;
  8925. clanRaidInfo = res[0].result.response;
  8926. teamGetAll = res[1].result.response;
  8927. teamGetFavor = res[2].result.response;
  8928.  
  8929. let index = 0;
  8930. let isNotFullPack = false;
  8931. for (let team of teamGetAll.clanRaid_nodes) {
  8932. if (team.length < 6) {
  8933. isNotFullPack = true;
  8934. }
  8935. raidData.teams.push({
  8936. data: {},
  8937. heroes: team.filter(id => id < 6000),
  8938. pet: team.filter(id => id >= 6000).pop(),
  8939. battleIndex: index++
  8940. });
  8941. }
  8942. raidData.favor = teamGetFavor.clanRaid_nodes;
  8943.  
  8944. if (isNotFullPack) {
  8945. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  8946. { msg: I18N('BTN_NO'), result: true },
  8947. { msg: I18N('BTN_YES'), result: false },
  8948. ])) {
  8949. endRaidNodes('isNotFullPack');
  8950. return;
  8951. }
  8952. }
  8953.  
  8954. raidData.nodes = clanRaidInfo.nodes;
  8955. raidData.attempts = clanRaidInfo.attempts;
  8956. isCancalBattle = false;
  8957.  
  8958. checkNodes();
  8959. }
  8960.  
  8961. function getAttackNode() {
  8962. for (let nodeId in raidData.nodes) {
  8963. let node = raidData.nodes[nodeId];
  8964. let points = 0
  8965. for (team of node.teams) {
  8966. points += team.points;
  8967. }
  8968. let now = Date.now() / 1000;
  8969. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  8970. let countTeam = node.teams.length;
  8971. delete raidData.nodes[nodeId];
  8972. return {
  8973. nodeId,
  8974. countTeam
  8975. };
  8976. }
  8977. }
  8978. return null;
  8979. }
  8980.  
  8981. function checkNodes() {
  8982. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  8983. let nodeInfo = getAttackNode();
  8984. if (nodeInfo && raidData.attempts) {
  8985. startNodeBattles(nodeInfo);
  8986. return;
  8987. }
  8988.  
  8989. endRaidNodes('EndRaidNodes');
  8990. }
  8991.  
  8992. function startNodeBattles(nodeInfo) {
  8993. let {nodeId, countTeam} = nodeInfo;
  8994. let teams = raidData.teams.slice(0, countTeam);
  8995. let heroes = raidData.teams.map(e => e.heroes).flat();
  8996. let favor = {...raidData.favor};
  8997. for (let heroId in favor) {
  8998. if (!heroes.includes(+heroId)) {
  8999. delete favor[heroId];
  9000. }
  9001. }
  9002.  
  9003. let calls = [{
  9004. name: "clanRaid_startNodeBattles",
  9005. args: {
  9006. nodeId,
  9007. teams,
  9008. favor
  9009. },
  9010. ident: "body"
  9011. }];
  9012.  
  9013. send(JSON.stringify({calls}), resultNodeBattles);
  9014. }
  9015.  
  9016. function resultNodeBattles(e) {
  9017. if (e['error']) {
  9018. endRaidNodes('nodeBattlesError', e['error']);
  9019. return;
  9020. }
  9021.  
  9022. console.log(e);
  9023. let battles = e.results[0].result.response.battles;
  9024. let promises = [];
  9025. let battleIndex = 0;
  9026. for (let battle of battles) {
  9027. battle.battleIndex = battleIndex++;
  9028. promises.push(calcBattleResult(battle));
  9029. }
  9030.  
  9031. Promise.all(promises)
  9032. .then(results => {
  9033. const endResults = {};
  9034. let isAllWin = true;
  9035. for (let r of results) {
  9036. isAllWin &&= r.result.win;
  9037. }
  9038. if (!isAllWin) {
  9039. cancelEndNodeBattle(results[0]);
  9040. return;
  9041. }
  9042. raidData.countExecuteBattles = results.length;
  9043. let timeout = 500;
  9044. for (let r of results) {
  9045. setTimeout(endNodeBattle, timeout, r);
  9046. timeout += 500;
  9047. }
  9048. });
  9049. }
  9050. /**
  9051. * Returns the battle calculation promise
  9052. *
  9053. * Возвращает промис расчета боя
  9054. */
  9055. function calcBattleResult(battleData) {
  9056. return new Promise(function (resolve, reject) {
  9057. BattleCalc(battleData, "get_clanPvp", resolve);
  9058. });
  9059. }
  9060. /**
  9061. * Cancels the fight
  9062. *
  9063. * Отменяет бой
  9064. */
  9065. function cancelEndNodeBattle(r) {
  9066. const fixBattle = function (heroes) {
  9067. for (const ids in heroes) {
  9068. hero = heroes[ids];
  9069. hero.energy = random(1, 999);
  9070. if (hero.hp > 0) {
  9071. hero.hp = random(1, hero.hp);
  9072. }
  9073. }
  9074. }
  9075. fixBattle(r.progress[0].attackers.heroes);
  9076. fixBattle(r.progress[0].defenders.heroes);
  9077. endNodeBattle(r);
  9078. }
  9079. /**
  9080. * Ends the fight
  9081. *
  9082. * Завершает бой
  9083. */
  9084. function endNodeBattle(r) {
  9085. let nodeId = r.battleData.result.nodeId;
  9086. let battleIndex = r.battleData.battleIndex;
  9087. let calls = [{
  9088. name: "clanRaid_endNodeBattle",
  9089. args: {
  9090. nodeId,
  9091. battleIndex,
  9092. result: r.result,
  9093. progress: r.progress
  9094. },
  9095. ident: "body"
  9096. }]
  9097.  
  9098. SendRequest(JSON.stringify({calls}), battleResult);
  9099. }
  9100. /**
  9101. * Processing the results of the battle
  9102. *
  9103. * Обработка результатов боя
  9104. */
  9105. function battleResult(e) {
  9106. if (e['error']) {
  9107. endRaidNodes('missionEndError', e['error']);
  9108. return;
  9109. }
  9110. r = e.results[0].result.response;
  9111. if (r['error']) {
  9112. if (r.reason == "invalidBattle") {
  9113. raidData.cancelBattle++;
  9114. checkNodes();
  9115. } else {
  9116. endRaidNodes('missionEndError', e['error']);
  9117. }
  9118. return;
  9119. }
  9120.  
  9121. if (!(--raidData.countExecuteBattles)) {
  9122. raidData.attempts--;
  9123. checkNodes();
  9124. }
  9125. }
  9126. /**
  9127. * Completing a task
  9128. *
  9129. * Завершение задачи
  9130. */
  9131. function endRaidNodes(reason, info) {
  9132. isCancalBattle = true;
  9133. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9134. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9135. console.log(reason, info);
  9136. resolve();
  9137. }
  9138. }
  9139.  
  9140. /**
  9141. * Asgard Boss Attack Replay
  9142. *
  9143. * Повтор атаки босса Асгарда
  9144. */
  9145. function testBossBattle() {
  9146. return new Promise((resolve, reject) => {
  9147. const bossBattle = new executeBossBattle(resolve, reject);
  9148. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  9149. });
  9150. }
  9151.  
  9152. /**
  9153. * Asgard Boss Attack Replay
  9154. *
  9155. * Повтор атаки босса Асгарда
  9156. */
  9157. function executeBossBattle(resolve, reject) {
  9158. let lastBossBattleArgs = {};
  9159. let reachDamage = 0;
  9160. let countBattle = 0;
  9161. let countMaxBattle = 10;
  9162. let lastDamage = 0;
  9163.  
  9164. this.start = function (battleArg, battleInfo) {
  9165. lastBossBattleArgs = battleArg;
  9166. preCalcBattle(battleInfo);
  9167. }
  9168.  
  9169. function getBattleInfo(battle) {
  9170. return new Promise(function (resolve) {
  9171. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9172. BattleCalc(battle, getBattleType(battle.type), e => {
  9173. let extra = e.progress[0].defenders.heroes[1].extra;
  9174. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9175. });
  9176. });
  9177. }
  9178.  
  9179. function preCalcBattle(battle) {
  9180. let actions = [];
  9181. const countTestBattle = getInput('countTestBattle');
  9182. for (let i = 0; i < countTestBattle; i++) {
  9183. actions.push(getBattleInfo(battle, true));
  9184. }
  9185. Promise.all(actions)
  9186. .then(resultPreCalcBattle);
  9187. }
  9188.  
  9189. function fixDamage(damage) {
  9190. for (let i = 1e6; i > 1; i /= 10) {
  9191. if (damage > i) {
  9192. let n = i / 10;
  9193. damage = Math.ceil(damage / n) * n;
  9194. break;
  9195. }
  9196. }
  9197. return damage;
  9198. }
  9199.  
  9200. async function resultPreCalcBattle(damages) {
  9201. let maxDamage = 0;
  9202. let minDamage = 1e10;
  9203. let avgDamage = 0;
  9204. for (let damage of damages) {
  9205. avgDamage += damage
  9206. if (damage > maxDamage) {
  9207. maxDamage = damage;
  9208. }
  9209. if (damage < minDamage) {
  9210. minDamage = damage;
  9211. }
  9212. }
  9213. avgDamage /= damages.length;
  9214. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9215.  
  9216. reachDamage = fixDamage(avgDamage);
  9217. const result = await popup.confirm(
  9218. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9219. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9220. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9221. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9222. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  9223. , [
  9224. { msg: I18N('BTN_OK'), result: 0},
  9225. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  9226. ])
  9227. if (result) {
  9228. reachDamage = result;
  9229. isCancalBossBattle = false;
  9230. startBossBattle();
  9231. return;
  9232. }
  9233. endBossBattle(I18N('BTN_CANCEL'));
  9234. }
  9235.  
  9236. function startBossBattle() {
  9237. countBattle++;
  9238. countMaxBattle = getInput('countAutoBattle');
  9239. if (countBattle > countMaxBattle) {
  9240. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  9241. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  9242. return;
  9243. }
  9244. let calls = [{
  9245. name: "clanRaid_startBossBattle",
  9246. args: lastBossBattleArgs,
  9247. ident: "body"
  9248. }];
  9249. send(JSON.stringify({calls}), calcResultBattle);
  9250. }
  9251.  
  9252. function calcResultBattle(e) {
  9253. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  9254. }
  9255.  
  9256. async function resultBattle(e) {
  9257. let extra = e.progress[0].defenders.heroes[1].extra
  9258. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  9259. console.log(resultDamage);
  9260. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  9261. lastDamage = resultDamage;
  9262. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  9263. {msg: 'Ок', result: true},
  9264. {msg: 'Не пойдет', result: false},
  9265. ])) {
  9266. endBattle(e, false);
  9267. return;
  9268. }
  9269. cancelEndBattle(e);
  9270. }
  9271.  
  9272. function cancelEndBattle (r) {
  9273. const fixBattle = function (heroes) {
  9274. for (const ids in heroes) {
  9275. hero = heroes[ids];
  9276. hero.energy = random(1, 999);
  9277. if (hero.hp > 0) {
  9278. hero.hp = random(1, hero.hp);
  9279. }
  9280. }
  9281. }
  9282. fixBattle(r.progress[0].attackers.heroes);
  9283. fixBattle(r.progress[0].defenders.heroes);
  9284. endBattle(r, true);
  9285. }
  9286.  
  9287. function endBattle(battleResult, isCancal) {
  9288. let calls = [{
  9289. name: "clanRaid_endBossBattle",
  9290. args: {
  9291. result: battleResult.result,
  9292. progress: battleResult.progress
  9293. },
  9294. ident: "body"
  9295. }];
  9296.  
  9297. send(JSON.stringify({calls}), e => {
  9298. console.log(e);
  9299. if (isCancal) {
  9300. startBossBattle();
  9301. return;
  9302. }
  9303. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  9304. setTimeout(() => {
  9305. scriptMenu.setStatus('');
  9306. }, 5000);
  9307. endBossBattle('Узпех!');
  9308. });
  9309. }
  9310.  
  9311. /**
  9312. * Completing a task
  9313. *
  9314. * Завершение задачи
  9315. */
  9316. function endBossBattle(reason, info) {
  9317. isCancalBossBattle = true;
  9318. console.log(reason, info);
  9319. resolve();
  9320. }
  9321. }
  9322.  
  9323. /**
  9324. * Auto-repeat attack
  9325. *
  9326. * Автоповтор атаки
  9327. */
  9328. function testAutoBattle() {
  9329. return new Promise((resolve, reject) => {
  9330. const bossBattle = new executeAutoBattle(resolve, reject);
  9331. bossBattle.start(lastBattleArg, lastBattleInfo);
  9332. });
  9333. }
  9334.  
  9335. /**
  9336. * Auto-repeat attack
  9337. *
  9338. * Автоповтор атаки
  9339. */
  9340. function executeAutoBattle(resolve, reject) {
  9341. let battleArg = {};
  9342. let countBattle = 0;
  9343. let findCoeff = 0;
  9344. let lastCalcBattle = null;
  9345.  
  9346. this.start = function (battleArgs, battleInfo) {
  9347. battleArg = battleArgs;
  9348. preCalcBattle(battleInfo);
  9349. }
  9350. /**
  9351. * Returns a promise for combat recalculation
  9352. *
  9353. * Возвращает промис для прерасчета боя
  9354. */
  9355. function getBattleInfo(battle) {
  9356. return new Promise(function (resolve) {
  9357. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9358. Calc(battle).then(e => {
  9359. e.coeff = calcCoeff(e, 'defenders');
  9360. resolve(e);
  9361. });
  9362. });
  9363. }
  9364. /**
  9365. * Battle recalculation
  9366. *
  9367. * Прерасчет боя
  9368. */
  9369. function preCalcBattle(battle) {
  9370. let actions = [];
  9371. const countTestBattle = getInput('countTestBattle');
  9372. for (let i = 0; i < countTestBattle; i++) {
  9373. actions.push(getBattleInfo(battle));
  9374. }
  9375. Promise.all(actions)
  9376. .then(resultPreCalcBattle);
  9377. }
  9378. /**
  9379. * Processing the results of the battle recalculation
  9380. *
  9381. * Обработка результатов прерасчета боя
  9382. */
  9383. async function resultPreCalcBattle(results) {
  9384. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  9385. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  9386. if (countWin > 0) {
  9387. isCancalBattle = false;
  9388. startBattle();
  9389. return;
  9390. }
  9391.  
  9392. let minCoeff = 100;
  9393. let maxCoeff = -100;
  9394. let avgCoeff = 0;
  9395. results.forEach(e => {
  9396. if (e.coeff < minCoeff) minCoeff = e.coeff;
  9397. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  9398. avgCoeff += e.coeff;
  9399. });
  9400. avgCoeff /= results.length;
  9401.  
  9402. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9403. nameFuncStartBattle == 'bossAttack') {
  9404. const result = await popup.confirm(
  9405. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  9406. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9407. { msg: I18N('BTN_DO_IT'), result: true },
  9408. ])
  9409. if (result) {
  9410. isCancalBattle = false;
  9411. startBattle();
  9412. return;
  9413. }
  9414. setProgress(I18N('NOT_THIS_TIME'), true);
  9415. endAutoBattle('invasion_bossStart');
  9416. return;
  9417. }
  9418.  
  9419. const result = await popup.confirm(
  9420. I18N('VICTORY_IMPOSSIBLE') +
  9421. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  9422. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  9423. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  9424. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  9425. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  9426. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  9427. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  9428. ])
  9429. if (result) {
  9430. findCoeff = result;
  9431. isCancalBattle = false;
  9432. startBattle();
  9433. return;
  9434. }
  9435. setProgress(I18N('NOT_THIS_TIME'), true);
  9436. endAutoBattle(I18N('NOT_THIS_TIME'));
  9437. }
  9438.  
  9439. /**
  9440. * Calculation of the combat result coefficient
  9441. *
  9442. * Расчет коэфициента результата боя
  9443. */
  9444. function calcCoeff(result, packType) {
  9445. let beforeSumFactor = 0;
  9446. const beforePack = result.battleData[packType][0];
  9447. for (let heroId in beforePack) {
  9448. const hero = beforePack[heroId];
  9449. const state = hero.state;
  9450. let factor = 1;
  9451. if (state) {
  9452. const hp = state.hp / state.maxHp;
  9453. const energy = state.energy / 1e3;
  9454. factor = hp + energy / 20;
  9455. }
  9456. beforeSumFactor += factor;
  9457. }
  9458.  
  9459. let afterSumFactor = 0;
  9460. const afterPack = result.progress[0][packType].heroes;
  9461. for (let heroId in afterPack) {
  9462. const hero = afterPack[heroId];
  9463. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  9464. const hp = hero.hp / stateHp;
  9465. const energy = hero.energy / 1e3;
  9466. const factor = hp + energy / 20;
  9467. afterSumFactor += factor;
  9468. }
  9469. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  9470. return Math.round(resultCoeff * 1000) / 1000;
  9471. }
  9472. /**
  9473. * Start battle
  9474. *
  9475. * Начало боя
  9476. */
  9477. function startBattle() {
  9478. countBattle++;
  9479. const countMaxBattle = getInput('countAutoBattle');
  9480. // setProgress(countBattle + '/' + countMaxBattle);
  9481. if (countBattle > countMaxBattle) {
  9482. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  9483. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  9484. return;
  9485. }
  9486. let calls = [{
  9487. name: nameFuncStartBattle,
  9488. args: battleArg,
  9489. ident: "body"
  9490. }];
  9491. send(JSON.stringify({
  9492. calls
  9493. }), calcResultBattle);
  9494. }
  9495. /**
  9496. * Battle calculation
  9497. *
  9498. * Расчет боя
  9499. */
  9500. async function calcResultBattle(e) {
  9501. if ('error' in e) {
  9502. const result = await popup.confirm(
  9503. I18N('ERROR_DURING_THE_BATTLE'), [
  9504. { msg: I18N('BTN_OK'), result: false },
  9505. { msg: I18N('RELOAD_GAME'), result: true },
  9506. ]);
  9507. endAutoBattle('Error', e.error);
  9508. if (result) {
  9509. location.reload();
  9510. }
  9511. return;
  9512. }
  9513. let battle = e.results[0].result.response.battle
  9514. if (nameFuncStartBattle == 'towerStartBattle' ||
  9515. nameFuncStartBattle == 'bossAttack' ||
  9516. nameFuncStartBattle == 'invasion_bossStart') {
  9517. battle = e.results[0].result.response;
  9518. }
  9519. lastCalcBattle = battle;
  9520. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  9521. }
  9522. /**
  9523. * Processing the results of the battle
  9524. *
  9525. * Обработка результатов боя
  9526. */
  9527. function resultBattle(e) {
  9528. const isWin = e.result.win;
  9529. if (isWin) {
  9530. endBattle(e, false);
  9531. return;
  9532. }
  9533. const countMaxBattle = getInput('countAutoBattle');
  9534. if (findCoeff) {
  9535. const coeff = calcCoeff(e, 'defenders');
  9536. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  9537. if (coeff > findCoeff) {
  9538. endBattle(e, false);
  9539. return;
  9540. }
  9541. } else {
  9542. setProgress(`${countBattle}/${countMaxBattle}`);
  9543. }
  9544. if (nameFuncStartBattle == 'towerStartBattle' ||
  9545. nameFuncStartBattle == 'bossAttack' ||
  9546. nameFuncStartBattle == 'invasion_bossStart') {
  9547. startBattle();
  9548. return;
  9549. }
  9550. cancelEndBattle(e);
  9551. }
  9552. /**
  9553. * Cancel fight
  9554. *
  9555. * Отмена боя
  9556. */
  9557. function cancelEndBattle(r) {
  9558. const fixBattle = function (heroes) {
  9559. for (const ids in heroes) {
  9560. hero = heroes[ids];
  9561. hero.energy = random(1, 999);
  9562. if (hero.hp > 0) {
  9563. hero.hp = random(1, hero.hp);
  9564. }
  9565. }
  9566. }
  9567. fixBattle(r.progress[0].attackers.heroes);
  9568. fixBattle(r.progress[0].defenders.heroes);
  9569. endBattle(r, true);
  9570. }
  9571. /**
  9572. * End of the fight
  9573. *
  9574. * Завершение боя */
  9575. function endBattle(battleResult, isCancal) {
  9576. let calls = [{
  9577. name: nameFuncEndBattle,
  9578. args: {
  9579. result: battleResult.result,
  9580. progress: battleResult.progress
  9581. },
  9582. ident: "body"
  9583. }];
  9584.  
  9585. if (nameFuncStartBattle == 'invasion_bossStart') {
  9586. calls[0].args.id = lastBattleArg.id;
  9587. }
  9588.  
  9589. send(JSON.stringify({
  9590. calls
  9591. }), async e => {
  9592. console.log(e);
  9593. if (isCancal) {
  9594. startBattle();
  9595. return;
  9596. }
  9597.  
  9598. setProgress(`${I18N('SUCCESS')}!`, 5000)
  9599. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9600. nameFuncStartBattle == 'bossAttack') {
  9601. const countMaxBattle = getInput('countAutoBattle');
  9602. const bossLvl = lastCalcBattle.typeId >= 130 ? lastCalcBattle.typeId : '';
  9603. const result = await popup.confirm(
  9604. I18N('BOSS_HAS_BEEN_DEF_TEXT', { bossLvl, countBattle, countMaxBattle }), [
  9605. { msg: I18N('BTN_OK'), result: 0 },
  9606. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  9607. { msg: I18N('RELOAD_GAME'), result: 2 },
  9608. ]);
  9609. if (result) {
  9610. if (result == 1) {
  9611. cheats.refreshGame();
  9612. }
  9613. if (result == 2) {
  9614. location.reload();
  9615. }
  9616. }
  9617.  
  9618. }
  9619. endAutoBattle(`${I18N('SUCCESS')}!`)
  9620. });
  9621. }
  9622. /**
  9623. * Completing a task
  9624. *
  9625. * Завершение задачи
  9626. */
  9627. function endAutoBattle(reason, info) {
  9628. isCancalBattle = true;
  9629. console.log(reason, info);
  9630. resolve();
  9631. }
  9632. }
  9633.  
  9634. function testDailyQuests() {
  9635. return new Promise((resolve, reject) => {
  9636. const quests = new dailyQuests(resolve, reject);
  9637. quests.init(questsInfo);
  9638. quests.start();
  9639. });
  9640. }
  9641.  
  9642. /**
  9643. * Automatic completion of daily quests
  9644. *
  9645. * Автоматическое выполнение ежедневных квестов
  9646. */
  9647. class dailyQuests {
  9648. /**
  9649. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  9650. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9651. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9652. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  9653. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9654. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  9655. */
  9656. callsList = [
  9657. "userGetInfo",
  9658. "heroGetAll",
  9659. "titanGetAll",
  9660. "inventoryGet",
  9661. "questGetAll",
  9662. "bossGetAll",
  9663. ]
  9664.  
  9665. dataQuests = {
  9666. 10001: {
  9667. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  9668. doItCall: () => {
  9669. const upgradeSkills = this.getUpgradeSkills();
  9670. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  9671. },
  9672. isWeCanDo: () => {
  9673. const upgradeSkills = this.getUpgradeSkills();
  9674. let sumGold = 0;
  9675. for (const skill of upgradeSkills) {
  9676. sumGold += this.skillCost(skill.value);
  9677. if (!skill.heroId) {
  9678. return false;
  9679. }
  9680. }
  9681. return this.questInfo['userGetInfo'].gold > sumGold;
  9682. },
  9683. },
  9684. 10002: {
  9685. description: 'Пройди 10 миссий', // --------------
  9686. isWeCanDo: () => false,
  9687. },
  9688. 10003: {
  9689. description: 'Пройди 3 героические миссии', // --------------
  9690. isWeCanDo: () => false,
  9691. },
  9692. 10004: {
  9693. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  9694. isWeCanDo: () => false,
  9695. },
  9696. 10006: {
  9697. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  9698. doItCall: () => [{
  9699. name: "refillableAlchemyUse",
  9700. args: { multi: false },
  9701. ident: "refillableAlchemyUse"
  9702. }],
  9703. isWeCanDo: () => {
  9704. const starMoney = this.questInfo['userGetInfo'].starMoney;
  9705. return starMoney >= 20;
  9706. },
  9707. },
  9708. 10007: {
  9709. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  9710. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  9711. isWeCanDo: () => {
  9712. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  9713. return soulCrystal > 0;
  9714. },
  9715. },
  9716. 10016: {
  9717. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  9718. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  9719. isWeCanDo: () => true,
  9720. },
  9721. 10018: {
  9722. description: 'Используй зелье опыта', // ++++++++++++++++
  9723. doItCall: () => {
  9724. const expHero = this.getExpHero();
  9725. return [{
  9726. name: "consumableUseHeroXp",
  9727. args: {
  9728. heroId: expHero.heroId,
  9729. libId: expHero.libId,
  9730. amount: 1
  9731. },
  9732. ident: "consumableUseHeroXp"
  9733. }];
  9734. },
  9735. isWeCanDo: () => {
  9736. const expHero = this.getExpHero();
  9737. return expHero.heroId && expHero.libId;
  9738. },
  9739. },
  9740. 10019: {
  9741. description: 'Открой 1 сундук в Башне',
  9742. doItFunc: testTower,
  9743. isWeCanDo: () => false,
  9744. },
  9745. 10020: {
  9746. description: 'Открой 3 сундука в Запределье', // Готово
  9747. doItCall: () => {
  9748. return this.getOutlandChest();
  9749. },
  9750. isWeCanDo: () => {
  9751. const outlandChest = this.getOutlandChest();
  9752. return outlandChest.length > 0;
  9753. },
  9754. },
  9755. 10021: {
  9756. description: 'Собери 75 Титанита в Подземелье Гильдии',
  9757. isWeCanDo: () => false,
  9758. },
  9759. 10022: {
  9760. description: 'Собери 150 Титанита в Подземелье Гильдии',
  9761. doItFunc: testDungeon,
  9762. isWeCanDo: () => false,
  9763. },
  9764. 10023: {
  9765. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  9766. doItCall: () => {
  9767. const heroId = this.getHeroIdTitanGift();
  9768. return [
  9769. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  9770. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  9771. ]
  9772. },
  9773. isWeCanDo: () => {
  9774. const heroId = this.getHeroIdTitanGift();
  9775. return heroId;
  9776. },
  9777. },
  9778. 10024: {
  9779. description: 'Повысь уровень любого артефакта один раз', // Готово
  9780. doItCall: () => {
  9781. const upArtifact = this.getUpgradeArtifact();
  9782. return [
  9783. {
  9784. name: "heroArtifactLevelUp",
  9785. args: {
  9786. heroId: upArtifact.heroId,
  9787. slotId: upArtifact.slotId
  9788. },
  9789. ident: `heroArtifactLevelUp`
  9790. }
  9791. ];
  9792. },
  9793. isWeCanDo: () => {
  9794. const upgradeArtifact = this.getUpgradeArtifact();
  9795. return upgradeArtifact.heroId;
  9796. },
  9797. },
  9798. 10025: {
  9799. description: 'Начни 1 Экспедицию',
  9800. doItFunc: checkExpedition,
  9801. isWeCanDo: () => false,
  9802. },
  9803. 10026: {
  9804. description: 'Начни 4 Экспедиции', // --------------
  9805. doItFunc: checkExpedition,
  9806. isWeCanDo: () => false,
  9807. },
  9808. 10027: {
  9809. description: 'Победи в 1 бою Турнира Стихий',
  9810. doItFunc: testTitanArena,
  9811. isWeCanDo: () => false,
  9812. },
  9813. 10028: {
  9814. description: 'Повысь уровень любого артефакта титанов', // Готово
  9815. doItCall: () => {
  9816. const upTitanArtifact = this.getUpgradeTitanArtifact();
  9817. return [
  9818. {
  9819. name: "titanArtifactLevelUp",
  9820. args: {
  9821. titanId: upTitanArtifact.titanId,
  9822. slotId: upTitanArtifact.slotId
  9823. },
  9824. ident: `titanArtifactLevelUp`
  9825. }
  9826. ];
  9827. },
  9828. isWeCanDo: () => {
  9829. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  9830. return upgradeTitanArtifact.titanId;
  9831. },
  9832. },
  9833. 10029: {
  9834. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  9835. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  9836. isWeCanDo: () => {
  9837. return this.questInfo['inventoryGet']?.consumable[55] > 0
  9838. },
  9839. },
  9840. 10030: {
  9841. description: 'Улучши облик любого героя 1 раз', // Готово
  9842. doItCall: () => {
  9843. const upSkin = this.getUpgradeSkin();
  9844. return [
  9845. {
  9846. name: "heroSkinUpgrade",
  9847. args: {
  9848. heroId: upSkin.heroId,
  9849. skinId: upSkin.skinId
  9850. },
  9851. ident: `heroSkinUpgrade`
  9852. }
  9853. ];
  9854. },
  9855. isWeCanDo: () => {
  9856. const upgradeSkin = this.getUpgradeSkin();
  9857. return upgradeSkin.heroId;
  9858. },
  9859. },
  9860. 10031: {
  9861. description: 'Победи в 6 боях Турнира Стихий', // --------------
  9862. doItFunc: testTitanArena,
  9863. isWeCanDo: () => false,
  9864. },
  9865. 10043: {
  9866. description: 'Начни или присоеденись к Приключению', // --------------
  9867. isWeCanDo: () => false,
  9868. },
  9869. 10044: {
  9870. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  9871. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  9872. isWeCanDo: () => {
  9873. return this.questInfo['inventoryGet']?.consumable[90] > 0
  9874. },
  9875. },
  9876. 10046: {
  9877. /**
  9878. * TODO: Watch Adventure
  9879. * TODO: Смотреть приключение
  9880. */
  9881. description: 'Открой 3 сундука в Приключениях',
  9882. isWeCanDo: () => false,
  9883. },
  9884. 10047: {
  9885. description: 'Набери 150 очков активности в Гильдии', // Готово
  9886. doItCall: () => {
  9887. const enchantRune = this.getEnchantRune();
  9888. return [
  9889. {
  9890. name: "heroEnchantRune",
  9891. args: {
  9892. heroId: enchantRune.heroId,
  9893. tier: enchantRune.tier,
  9894. items: {
  9895. consumable: { [enchantRune.itemId]: 1 }
  9896. }
  9897. },
  9898. ident: `heroEnchantRune`
  9899. }
  9900. ];
  9901. },
  9902. isWeCanDo: () => {
  9903. const userInfo = this.questInfo['userGetInfo'];
  9904. const enchantRune = this.getEnchantRune();
  9905. return enchantRune.heroId && userInfo.gold > 1e3;
  9906. },
  9907. },
  9908. };
  9909.  
  9910. constructor(resolve, reject, questInfo) {
  9911. this.resolve = resolve;
  9912. this.reject = reject;
  9913. }
  9914.  
  9915. init(questInfo) {
  9916. this.questInfo = questInfo;
  9917. this.isAuto = false;
  9918. }
  9919.  
  9920. async autoInit(isAuto) {
  9921. this.isAuto = isAuto || false;
  9922. const quests = {};
  9923. const calls = this.callsList.map(name => ({
  9924. name, args: {}, ident: name
  9925. }))
  9926. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  9927. for (const call of result) {
  9928. quests[call.ident] = call.result.response;
  9929. }
  9930. this.questInfo = quests;
  9931. }
  9932.  
  9933. async start() {
  9934. /**
  9935. * TODO may not be needed
  9936. *
  9937. * TODO возожно не нужна
  9938. */
  9939. let countQuest = 0;
  9940. const weCanDo = [];
  9941. const selectedActions = getSaveVal('selectedActions', {});
  9942. for (let quest of this.questInfo['questGetAll']) {
  9943. if (quest.id in this.dataQuests && quest.state == 1) {
  9944. if (!selectedActions[quest.id]) {
  9945. selectedActions[quest.id] = {
  9946. checked: false
  9947. }
  9948. }
  9949.  
  9950. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  9951. if (!isWeCanDo.call(this)) {
  9952. continue;
  9953. }
  9954.  
  9955. weCanDo.push({
  9956. name: quest.id,
  9957. label: I18N(`QUEST_${quest.id}`),
  9958. checked: selectedActions[quest.id].checked
  9959. });
  9960. countQuest++;
  9961. }
  9962. }
  9963.  
  9964. if (!weCanDo.length) {
  9965. this.end(I18N('NOTHING_TO_DO'));
  9966. return;
  9967. }
  9968.  
  9969. console.log(weCanDo);
  9970. let taskList = [];
  9971. if (this.isAuto) {
  9972. taskList = weCanDo;
  9973. } else {
  9974. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  9975. { msg: I18N('BTN_DO_IT'), result: true },
  9976. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9977. ], weCanDo);
  9978. if (!answer) {
  9979. this.end('');
  9980. return;
  9981. }
  9982. taskList = popup.getCheckBoxes();
  9983. taskList.forEach(e => {
  9984. selectedActions[e.name].checked = e.checked;
  9985. });
  9986. setSaveVal('selectedActions', selectedActions);
  9987. }
  9988.  
  9989. const calls = [];
  9990. let countChecked = 0;
  9991. for (const task of taskList) {
  9992. if (task.checked) {
  9993. countChecked++;
  9994. const quest = this.dataQuests[task.name]
  9995. console.log(quest.description);
  9996.  
  9997. if (quest.doItCall) {
  9998. const doItCall = quest.doItCall.call(this);
  9999. calls.push(...doItCall);
  10000. }
  10001. }
  10002. }
  10003.  
  10004. if (!countChecked) {
  10005. this.end(I18N('NOT_QUEST_COMPLETED'));
  10006. return;
  10007. }
  10008.  
  10009. const result = await Send(JSON.stringify({ calls }));
  10010. if (result.error) {
  10011. console.error(result.error, result.error.call)
  10012. }
  10013. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  10014. }
  10015.  
  10016. errorHandling(error) {
  10017. //console.error(error);
  10018. let errorInfo = error.toString() + '\n';
  10019. try {
  10020. const errorStack = error.stack.split('\n');
  10021. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  10022. errorInfo += errorStack.slice(0, endStack).join('\n');
  10023. } catch (e) {
  10024. errorInfo += error.stack;
  10025. }
  10026. copyText(errorInfo);
  10027. }
  10028.  
  10029. skillCost(lvl) {
  10030. return 573 * lvl ** 0.9 + lvl ** 2.379;
  10031. }
  10032.  
  10033. getUpgradeSkills() {
  10034. const heroes = Object.values(this.questInfo['heroGetAll']);
  10035. const upgradeSkills = [
  10036. { heroId: 0, slotId: 0, value: 130 },
  10037. { heroId: 0, slotId: 0, value: 130 },
  10038. { heroId: 0, slotId: 0, value: 130 },
  10039. ];
  10040. const skillLib = lib.getData('skill');
  10041. /**
  10042. * color - 1 (белый) открывает 1 навык
  10043. * color - 2 (зеленый) открывает 2 навык
  10044. * color - 4 (синий) открывает 3 навык
  10045. * color - 7 (фиолетовый) открывает 4 навык
  10046. */
  10047. const colors = [1, 2, 4, 7];
  10048. for (const hero of heroes) {
  10049. const level = hero.level;
  10050. const color = hero.color;
  10051. for (let skillId in hero.skills) {
  10052. const tier = skillLib[skillId].tier;
  10053. const sVal = hero.skills[skillId];
  10054. if (color < colors[tier] || tier < 1 || tier > 4) {
  10055. continue;
  10056. }
  10057. for (let upSkill of upgradeSkills) {
  10058. if (sVal < upSkill.value && sVal < level) {
  10059. upSkill.value = sVal;
  10060. upSkill.heroId = hero.id;
  10061. upSkill.skill = tier;
  10062. break;
  10063. }
  10064. }
  10065. }
  10066. }
  10067. return upgradeSkills;
  10068. }
  10069.  
  10070. getUpgradeArtifact() {
  10071. const heroes = Object.values(this.questInfo['heroGetAll']);
  10072. const inventory = this.questInfo['inventoryGet'];
  10073. const upArt = { heroId: 0, slotId: 0, level: 100 };
  10074.  
  10075. const heroLib = lib.getData('hero');
  10076. const artifactLib = lib.getData('artifact');
  10077.  
  10078. for (const hero of heroes) {
  10079. const heroInfo = heroLib[hero.id];
  10080. const level = hero.level
  10081. if (level < 20) {
  10082. continue;
  10083. }
  10084.  
  10085. for (let slotId in hero.artifacts) {
  10086. const art = hero.artifacts[slotId];
  10087. /* Текущая звезданость арта */
  10088. const star = art.star;
  10089. if (!star) {
  10090. continue;
  10091. }
  10092. /* Текущий уровень арта */
  10093. const level = art.level;
  10094. if (level >= 100) {
  10095. continue;
  10096. }
  10097. /* Идентификатор арта в библиотеке */
  10098. const artifactId = heroInfo.artifacts[slotId];
  10099. const artInfo = artifactLib.id[artifactId];
  10100. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  10101.  
  10102. const costСurrency = Object.keys(costNextLevel).pop();
  10103. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  10104. const costId = costValues[0];
  10105. const costValue = +costValues[1];
  10106.  
  10107. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10108. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  10109. upArt.level = level;
  10110. upArt.heroId = hero.id;
  10111. upArt.slotId = slotId;
  10112. upArt.costСurrency = costСurrency;
  10113. upArt.costId = costId;
  10114. upArt.costValue = costValue;
  10115. }
  10116. }
  10117. }
  10118. return upArt;
  10119. }
  10120.  
  10121. getUpgradeSkin() {
  10122. const heroes = Object.values(this.questInfo['heroGetAll']);
  10123. const inventory = this.questInfo['inventoryGet'];
  10124. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  10125.  
  10126. const skinLib = lib.getData('skin');
  10127.  
  10128. for (const hero of heroes) {
  10129. const level = hero.level
  10130. if (level < 20) {
  10131. continue;
  10132. }
  10133.  
  10134. for (let skinId in hero.skins) {
  10135. /* Текущий уровень скина */
  10136. const level = hero.skins[skinId];
  10137. if (level >= 60) {
  10138. continue;
  10139. }
  10140. /* Идентификатор скина в библиотеке */
  10141. const skinInfo = skinLib[skinId];
  10142. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  10143.  
  10144. const costСurrency = Object.keys(costNextLevel).pop();
  10145. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  10146. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  10147.  
  10148. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10149. if (level < upSkin.level &&
  10150. costValue < upSkin.cost &&
  10151. inventory[costСurrency][costСurrencyId] >= costValue) {
  10152. upSkin.cost = costValue;
  10153. upSkin.level = level;
  10154. upSkin.heroId = hero.id;
  10155. upSkin.skinId = skinId;
  10156. upSkin.costСurrency = costСurrency;
  10157. upSkin.costСurrencyId = costСurrencyId;
  10158. }
  10159. }
  10160. }
  10161. return upSkin;
  10162. }
  10163.  
  10164. getUpgradeTitanArtifact() {
  10165. const titans = Object.values(this.questInfo['titanGetAll']);
  10166. const inventory = this.questInfo['inventoryGet'];
  10167. const userInfo = this.questInfo['userGetInfo'];
  10168. const upArt = { titanId: 0, slotId: 0, level: 120 };
  10169.  
  10170. const titanLib = lib.getData('titan');
  10171. const artTitanLib = lib.getData('titanArtifact');
  10172.  
  10173. for (const titan of titans) {
  10174. const titanInfo = titanLib[titan.id];
  10175. // const level = titan.level
  10176. // if (level < 20) {
  10177. // continue;
  10178. // }
  10179.  
  10180. for (let slotId in titan.artifacts) {
  10181. const art = titan.artifacts[slotId];
  10182. /* Текущая звезданость арта */
  10183. const star = art.star;
  10184. if (!star) {
  10185. continue;
  10186. }
  10187. /* Текущий уровень арта */
  10188. const level = art.level;
  10189. if (level >= 120) {
  10190. continue;
  10191. }
  10192. /* Идентификатор арта в библиотеке */
  10193. const artifactId = titanInfo.artifacts[slotId];
  10194. const artInfo = artTitanLib.id[artifactId];
  10195. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  10196.  
  10197. const costСurrency = Object.keys(costNextLevel).pop();
  10198. let costValue = 0;
  10199. let currentValue = 0;
  10200. if (costСurrency == 'gold') {
  10201. costValue = costNextLevel[costСurrency];
  10202. currentValue = userInfo.gold;
  10203. } else {
  10204. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  10205. const costId = costValues[0];
  10206. costValue = +costValues[1];
  10207. currentValue = inventory[costСurrency][costId];
  10208. }
  10209.  
  10210. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10211. if (level < upArt.level && currentValue >= costValue) {
  10212. upArt.level = level;
  10213. upArt.titanId = titan.id;
  10214. upArt.slotId = slotId;
  10215. break;
  10216. }
  10217. }
  10218. }
  10219. return upArt;
  10220. }
  10221.  
  10222. getEnchantRune() {
  10223. const heroes = Object.values(this.questInfo['heroGetAll']);
  10224. const inventory = this.questInfo['inventoryGet'];
  10225. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  10226. for (let i = 1; i <= 4; i++) {
  10227. if (inventory.consumable[i] > 0) {
  10228. enchRune.itemId = i;
  10229. break;
  10230. }
  10231. return enchRune;
  10232. }
  10233.  
  10234. const runeLib = lib.getData('rune');
  10235. const runeLvls = Object.values(runeLib.level);
  10236. /**
  10237. * color - 4 (синий) открывает 1 и 2 символ
  10238. * color - 7 (фиолетовый) открывает 3 символ
  10239. * color - 8 (фиолетовый +1) открывает 4 символ
  10240. * color - 9 (фиолетовый +2) открывает 5 символ
  10241. */
  10242. // TODO: кажется надо учесть уровень команды
  10243. const colors = [4, 4, 7, 8, 9];
  10244. for (const hero of heroes) {
  10245. const color = hero.color;
  10246.  
  10247.  
  10248. for (let runeTier in hero.runes) {
  10249. /* Проверка на доступность руны */
  10250. if (color < colors[runeTier]) {
  10251. continue;
  10252. }
  10253. /* Текущий опыт руны */
  10254. const exp = hero.runes[runeTier];
  10255. if (exp >= 43750) {
  10256. continue;
  10257. }
  10258.  
  10259. let level = 0;
  10260. if (exp) {
  10261. for (let lvl of runeLvls) {
  10262. if (exp >= lvl.enchantValue) {
  10263. level = lvl.level;
  10264. } else {
  10265. break;
  10266. }
  10267. }
  10268. }
  10269. /** Уровень героя необходимый для уровня руны */
  10270. const heroLevel = runeLib.level[level].heroLevel;
  10271. if (hero.level < heroLevel) {
  10272. continue;
  10273. }
  10274.  
  10275. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10276. if (exp < enchRune.exp) {
  10277. enchRune.exp = exp;
  10278. enchRune.heroId = hero.id;
  10279. enchRune.tier = runeTier;
  10280. break;
  10281. }
  10282. }
  10283. }
  10284. return enchRune;
  10285. }
  10286.  
  10287. getOutlandChest() {
  10288. const bosses = this.questInfo['bossGetAll'];
  10289.  
  10290. const calls = [];
  10291.  
  10292. for (let boss of bosses) {
  10293. if (boss.mayRaid) {
  10294. calls.push({
  10295. name: "bossRaid",
  10296. args: {
  10297. bossId: boss.id
  10298. },
  10299. ident: "bossRaid_" + boss.id
  10300. });
  10301. calls.push({
  10302. name: "bossOpenChest",
  10303. args: {
  10304. bossId: boss.id,
  10305. amount: 1,
  10306. starmoney: 0
  10307. },
  10308. ident: "bossOpenChest_" + boss.id
  10309. });
  10310. } else if (boss.chestId == 1) {
  10311. calls.push({
  10312. name: "bossOpenChest",
  10313. args: {
  10314. bossId: boss.id,
  10315. amount: 1,
  10316. starmoney: 0
  10317. },
  10318. ident: "bossOpenChest_" + boss.id
  10319. });
  10320. }
  10321. }
  10322.  
  10323. return calls;
  10324. }
  10325.  
  10326. getExpHero() {
  10327. const heroes = Object.values(this.questInfo['heroGetAll']);
  10328. const inventory = this.questInfo['inventoryGet'];
  10329. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  10330. /** зелья опыта (consumable 9, 10, 11, 12) */
  10331. for (let i = 9; i <= 12; i++) {
  10332. if (inventory.consumable[i]) {
  10333. expHero.libId = i;
  10334. break;
  10335. }
  10336. }
  10337.  
  10338. for (const hero of heroes) {
  10339. const exp = hero.xp;
  10340. if (exp < expHero.exp) {
  10341. expHero.heroId = hero.id;
  10342. }
  10343. }
  10344. return expHero;
  10345. }
  10346.  
  10347. getHeroIdTitanGift() {
  10348. const heroes = Object.values(this.questInfo['heroGetAll']);
  10349. const inventory = this.questInfo['inventoryGet'];
  10350. const user = this.questInfo['userGetInfo'];
  10351. const titanGiftLib = lib.getData('titanGift');
  10352. /** Искры */
  10353. const titanGift = inventory.consumable[24];
  10354. let heroId = 0;
  10355. let minLevel = 30;
  10356.  
  10357. if (titanGift < 250 || user.gold < 7000) {
  10358. return 0;
  10359. }
  10360.  
  10361. for (const hero of heroes) {
  10362. if (hero.titanGiftLevel >= 30) {
  10363. continue;
  10364. }
  10365.  
  10366. if (!hero.titanGiftLevel) {
  10367. return hero.id;
  10368. }
  10369.  
  10370. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  10371. if (minLevel > hero.titanGiftLevel &&
  10372. titanGift >= cost.consumable[24] &&
  10373. user.gold >= cost.gold
  10374. ) {
  10375. minLevel = hero.titanGiftLevel;
  10376. heroId = hero.id;
  10377. }
  10378. }
  10379.  
  10380. return heroId;
  10381. }
  10382.  
  10383. end(status) {
  10384. setProgress(status, true);
  10385. this.resolve();
  10386. }
  10387. }
  10388.  
  10389. this.questRun = dailyQuests;
  10390.  
  10391. function testDoYourBest() {
  10392. return new Promise((resolve, reject) => {
  10393. const doIt = new doYourBest(resolve, reject);
  10394. doIt.start();
  10395. });
  10396. }
  10397.  
  10398. /**
  10399. * Do everything button
  10400. *
  10401. * Кнопка сделать все
  10402. */
  10403. class doYourBest {
  10404.  
  10405. funcList = [
  10406. //собрать запределье
  10407. {
  10408. name: 'getOutland',
  10409. label: I18N('ASSEMBLE_OUTLAND'),
  10410. checked: false
  10411. },
  10412. //пройти башню
  10413. {
  10414. name: 'testTower',
  10415. label: I18N('PASS_THE_TOWER'),
  10416. checked: false
  10417. },
  10418. //экспедиции
  10419. {
  10420. name: 'checkExpedition',
  10421. label: I18N('CHECK_EXPEDITIONS'),
  10422. checked: false
  10423. },
  10424. //турнир стихий
  10425. {
  10426. name: 'testTitanArena',
  10427. label: I18N('COMPLETE_TOE'),
  10428. checked: false
  10429. },
  10430. //собрать почту
  10431. {
  10432. name: 'mailGetAll',
  10433. label: I18N('COLLECT_MAIL'),
  10434. checked: false
  10435. },
  10436. //Собрать всякую херню
  10437. {
  10438. name: 'collectAllStuff',
  10439. label: I18N('COLLECT_MISC'),
  10440. title: I18N('COLLECT_MISC_TITLE'),
  10441. checked: false
  10442. },
  10443. //ежедневная награда
  10444. {
  10445. name: 'getDailyBonus',
  10446. label: I18N('DAILY_BONUS'),
  10447. checked: false
  10448. },
  10449. //ежедневные квесты удалить наверно есть в настройках
  10450. /*{
  10451. name: 'dailyQuests',
  10452. label: I18N('DO_DAILY_QUESTS'),
  10453. checked: false
  10454. },*/
  10455. //Провидец
  10456. {
  10457. name: 'rollAscension',
  10458. label: I18N('SEER_TITLE'),
  10459. checked: false
  10460. },
  10461. //собрать награды за квесты
  10462. {
  10463. name: 'questAllFarm',
  10464. label: I18N('COLLECT_QUEST_REWARDS'),
  10465. checked: false
  10466. },
  10467. // тест отправь подарки согильдийцам
  10468. {
  10469. name: 'testclanSendDailyGifts',
  10470. label: I18N('QUEST_10016'),
  10471. checked: false
  10472. },
  10473. //собрать новогодние подарки
  10474. /*{
  10475. name: 'getGiftNewYear',
  10476. label: I18N('NY_GIFTS'),
  10477. checked: false
  10478. },*/
  10479. // тест сферу титанов
  10480. {
  10481. name: 'testtitanArtifactChestOpen',
  10482. label: I18N('QUEST_10029'),
  10483. checked: false
  10484. },
  10485. // тест призыв петов
  10486. {
  10487. name: 'testpet_chestOpen',
  10488. label: I18N('QUEST_10044'),
  10489. checked: false
  10490. },
  10491. //пройти подземелье обычное
  10492. {
  10493. name: 'testDungeon',
  10494. label: I18N('COMPLETE_DUNGEON'),
  10495. checked: false
  10496. },
  10497. //пройти подземелье для фуловых титанов
  10498. {
  10499. name: 'DungeonFull',
  10500. label: I18N('COMPLETE_DUNGEON_FULL'),
  10501. checked: false
  10502. },
  10503. //синхронизация
  10504. {
  10505. name: 'synchronization',
  10506. label: I18N('MAKE_A_SYNC'),
  10507. checked: false
  10508. },
  10509. //перезагрузка
  10510. {
  10511. name: 'reloadGame',
  10512. label: I18N('RELOAD_GAME'),
  10513. checked: false
  10514. },
  10515. ];
  10516.  
  10517. functions = {
  10518. getOutland,//собрать запределье
  10519. testTower,//прохождение башни
  10520. checkExpedition,//автоэкспедиции
  10521. testTitanArena,//Автопрохождение Турнира Стихий
  10522. mailGetAll,//Собрать всю почту, кроме писем с энергией и зарядами портала
  10523. //Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души
  10524. collectAllStuff: async () => {
  10525. await offerFarmAllReward();
  10526. await Send('{"calls":[{"name":"subscriptionFarm","args":{},"ident":"body"},{"name":"zeppelinGiftFarm","args":{},"ident":"zeppelinGiftFarm"},{"name":"grandFarmCoins","args":{},"ident":"grandFarmCoins"},{"name":"gacha_refill","args":{"ident":"heroGacha"},"ident":"gacha_refill"}]}');
  10527. },
  10528. //Выполнять ежедневные квесты
  10529. dailyQuests: async function () {
  10530. const quests = new dailyQuests(() => { }, () => { });
  10531. await quests.autoInit(true);
  10532. await quests.start();
  10533. },
  10534. rollAscension,//провидец
  10535. getDailyBonus,//ежедневная награда
  10536. questAllFarm,//Собрать все награды за задания
  10537. testclanSendDailyGifts, //отправить подарки
  10538. getGiftNewYear,//собрать новогодние подарки
  10539. testtitanArtifactChestOpen, //открой сферу титанов
  10540. testpet_chestOpen, //Воспользуйся призывом питомцев 1 раз
  10541. testDungeon,//подземка обычная
  10542. DungeonFull,//подземка для фуловых титанов
  10543. synchronization: async () => {
  10544. cheats.refreshGame();
  10545. },
  10546. reloadGame: async () => {
  10547. location.reload();
  10548. },
  10549. }
  10550.  
  10551. constructor(resolve, reject, questInfo) {
  10552. this.resolve = resolve;
  10553. this.reject = reject;
  10554. this.questInfo = questInfo
  10555. }
  10556.  
  10557. async start() {
  10558. const selectedDoIt = getSaveVal('selectedDoIt', {});
  10559.  
  10560. this.funcList.forEach(task => {
  10561. if (!selectedDoIt[task.name]) {
  10562. selectedDoIt[task.name] = {
  10563. checked: task.checked
  10564. }
  10565. } else {
  10566. task.checked = selectedDoIt[task.name].checked
  10567. }
  10568. });
  10569.  
  10570. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  10571. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10572. { msg: I18N('BTN_GO'), result: true },
  10573. ], this.funcList);
  10574.  
  10575. if (!answer) {
  10576. this.end('');
  10577. return;
  10578. }
  10579.  
  10580. const taskList = popup.getCheckBoxes();
  10581. taskList.forEach(task => {
  10582. selectedDoIt[task.name].checked = task.checked;
  10583. });
  10584. setSaveVal('selectedDoIt', selectedDoIt);
  10585. for (const task of popup.getCheckBoxes()) {
  10586. if (task.checked) {
  10587. try {
  10588. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  10589. await this.functions[task.name]();
  10590. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  10591. } catch (error) {
  10592. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  10593. { msg: I18N('BTN_NO'), result: false },
  10594. { msg: I18N('BTN_YES'), result: true },
  10595. ])) {
  10596. this.errorHandling(error);
  10597. }
  10598. }
  10599. }
  10600. }
  10601. setTimeout((msg) => {
  10602. this.end(msg);
  10603. }, 2000, I18N('ALL_TASK_COMPLETED'));
  10604. return;
  10605. }
  10606.  
  10607. errorHandling(error) {
  10608. //console.error(error);
  10609. let errorInfo = error.toString() + '\n';
  10610. try {
  10611. const errorStack = error.stack.split('\n');
  10612. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  10613. errorInfo += errorStack.slice(0, endStack).join('\n');
  10614. } catch (e) {
  10615. errorInfo += error.stack;
  10616. }
  10617. copyText(errorInfo);
  10618. }
  10619.  
  10620. end(status) {
  10621. setProgress(status, true);
  10622. this.resolve();
  10623. }
  10624. }
  10625.  
  10626. /**
  10627. * Passing the adventure along the specified route
  10628. *
  10629. * Прохождение приключения по указанному маршруту
  10630. */
  10631. function testAdventure(type) {
  10632. return new Promise((resolve, reject) => {
  10633. const bossBattle = new executeAdventure(resolve, reject);
  10634. bossBattle.start(type);
  10635. });
  10636. }
  10637.  
  10638. /**
  10639. * Passing the adventure along the specified route
  10640. *
  10641. * Прохождение приключения по указанному маршруту
  10642. */
  10643. class executeAdventure {
  10644.  
  10645. type = 'default';
  10646.  
  10647. actions = {
  10648. default: {
  10649. getInfo: "adventure_getInfo",
  10650. startBattle: 'adventure_turnStartBattle',
  10651. endBattle: 'adventure_endBattle',
  10652. collectBuff: 'adventure_turnCollectBuff'
  10653. },
  10654. solo: {
  10655. getInfo: "adventureSolo_getInfo",
  10656. startBattle: 'adventureSolo_turnStartBattle',
  10657. endBattle: 'adventureSolo_endBattle',
  10658. collectBuff: 'adventureSolo_turnCollectBuff'
  10659. }
  10660. }
  10661.  
  10662. terminatеReason = I18N('UNKNOWN');
  10663. callAdventureInfo = {
  10664. name: "adventure_getInfo",
  10665. args: {},
  10666. ident: "adventure_getInfo"
  10667. }
  10668. callTeamGetAll = {
  10669. name: "teamGetAll",
  10670. args: {},
  10671. ident: "teamGetAll"
  10672. }
  10673. callTeamGetFavor = {
  10674. name: "teamGetFavor",
  10675. args: {},
  10676. ident: "teamGetFavor"
  10677. }
  10678. //тест прикла
  10679. defaultWays = {
  10680. //Галахад, 1-я
  10681. "adv_strongford_2pl_easy": {
  10682. first: '1,2,3,5,6',
  10683. second: '1,2,4,7,6',
  10684. third: '1,2,3,5,6'
  10685. },
  10686. //Джинджер, 2-я
  10687. "adv_valley_3pl_easy": {
  10688. first: '1,2,5,8,9,11',
  10689. second: '1,3,6,9,11',
  10690. third: '1,4,7,10,9,11'
  10691. },
  10692. //Орион, 3-я
  10693. "adv_ghirwil_3pl_easy": {
  10694. first: '1,5,6,9,11',
  10695. second: '1,4,12,13,11',
  10696. third: '1,2,3,7,10,11'
  10697. },
  10698. //Тесак, 4-я
  10699. "adv_angels_3pl_easy_fire": {
  10700. first: '1,2,4,7,18,8,12,19,22,23',
  10701. second: '1,3,6,11,17,10,16,21,22,23',
  10702. third: '1,5,24,25,9,14,15,20,22,23'
  10703. },
  10704. //Галахад, 5-я
  10705. "adv_strongford_3pl_normal_2": {
  10706. first: '1,2,7,8,12,16,23,26,25,21,24',
  10707. second: '1,4,6,10,11,15,22,15,19,18,24',
  10708. third: '1,5,9,10,14,17,20,27,25,21,24'
  10709. },
  10710. //Джинджер, 6-я
  10711. "adv_valley_3pl_normal": {
  10712. first: '1,2,4,7,10,13,16,19,24,22,25',
  10713. second: '1,3,6,9,12,15,18,21,26,23,25',
  10714. third: '1,5,7,8,11,14,17,20,22,25'
  10715. },
  10716. //Орион, 7-я
  10717. "adv_ghirwil_3pl_normal_2": {
  10718. first: '1,11,10,11,12,15,12,11,21,25,27',
  10719. second: '1,7,3,4,3,6,13,19,20,24,27',
  10720. third: '1,8,5,9,16,23,22,26,27'
  10721. },
  10722. //Тесак, 8-я
  10723. "adv_angels_3pl_normal": {
  10724. first: '1,3,4,8,7,9,10,13,17,16,20,22,23,31,32',
  10725. second: '1,3,5,7,8,11,14,18,20,22,24,27,30,26,32',
  10726. third: '1,3,2,6,7,9,11,15,19,20,22,21,28,29,25'
  10727. },
  10728. //Галахад, 9-я
  10729. "adv_strongford_3pl_hard_2": {
  10730. first: '1,2,6,10,15,7,16,17,23,22,27,32,35,37,40,45',
  10731. second: '1,3,8,12,11,18,19,28,34,33,38,41,43,46,45',
  10732. third: '1,2,5,9,14,20,26,21,30,36,39,42,44,45'
  10733. },
  10734. //Джинджер, 10-я
  10735. "adv_valley_3pl_hard": {
  10736. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  10737. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  10738. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  10739. },
  10740. //Орион, 11-я
  10741. "adv_ghirwil_3pl_hard": {
  10742. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  10743. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  10744. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  10745. },
  10746. //Тесак, 12-я
  10747. "adv_angels_3pl_hard": {
  10748. first: '1,2,8,11,7,4,7,16,23,32,33,25,34,29,35,36',
  10749. second: '1,3,9,13,10,6,10,22,31,30,21,30,15,28,20,27',
  10750. third: '1,5,12,14,24,17,24,25,26,18,19,20,27'
  10751. },
  10752. //Тесак, 13-я
  10753. "adv_angels_3pl_hell": {
  10754. first: '1,2,4,6,16,23,33,34,25,32,29,28,20,27',
  10755. second: '1,7,11,17,24,14,26,18,19,20,27,20,12,8',
  10756. third: '1,9,3,5,10,22,31,36,31,30,15,28,29,30,21,13'
  10757. },
  10758. //Галахад, 13-я
  10759. "adv_strongford_3pl_hell": {
  10760. first: '1,2,5,11,14,20,26,21,30,35,38,41,43,44',
  10761. second: '1,2,6,12,15,7,16,17,23,22,27,42,34,36,39,44',
  10762. third: '1,3,8,9,13,18,19,28,0,33,37,40,32,45,44'
  10763. },
  10764. //Орион, 13-я
  10765. "adv_ghirwil_3pl_hell": {
  10766. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  10767. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  10768. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  10769. },
  10770. //Джинджер, 13-я
  10771. "adv_valley_3pl_hell": {
  10772. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  10773. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  10774. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  10775. },
  10776. //Буря, 061123
  10777. "tempest_3_3": {
  10778. first: '1,5,1,5,11,17,25,30,35,34,29,24,21,17,12,7',
  10779. //second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  10780. //third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  10781. }
  10782. }
  10783. callStartBattle = {
  10784. name: "adventure_turnStartBattle",
  10785. args: {},
  10786. ident: "body"
  10787. }
  10788. callEndBattle = {
  10789. name: "adventure_endBattle",
  10790. args: {
  10791. result: {},
  10792. progress: {},
  10793. },
  10794. ident: "body"
  10795. }
  10796. callCollectBuff = {
  10797. name: "adventure_turnCollectBuff",
  10798. args: {},
  10799. ident: "body"
  10800. }
  10801.  
  10802. constructor(resolve, reject) {
  10803. this.resolve = resolve;
  10804. this.reject = reject;
  10805. }
  10806.  
  10807. async start(type) {
  10808. //this.type = type || this.type;
  10809. //this.callAdventureInfo.name = this.actions[this.type].getInfo;
  10810. const data = await Send(JSON.stringify({
  10811. calls: [
  10812. this.callAdventureInfo,
  10813. this.callTeamGetAll,
  10814. this.callTeamGetFavor
  10815. ]
  10816. }));
  10817. //тест прикла1
  10818. this.path = await this.getPath(data.results[0].result.response.mapIdent);
  10819. if (!this.path) {
  10820. this.end();
  10821. return;
  10822. }
  10823. return this.checkAdventureInfo(data.results);
  10824. }
  10825.  
  10826. async getPath(mapId) {
  10827. //const oldVal = getSaveVal('adventurePath', '');
  10828. //const keyPath = `adventurePath:${this.mapIdent}`;
  10829. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  10830. {
  10831. msg: I18N('START_ADVENTURE'),
  10832. placeholder: '1,2,3,4,5,6',
  10833. isInput: true,
  10834. //default: getSaveVal(keyPath, oldVal)
  10835. default: getSaveVal('adventurePath', '')
  10836. },
  10837. {
  10838. msg: ' Начать по пути №1! ',
  10839. placeholder: '1,2,3',
  10840. isInput: true,
  10841. default: this.defaultWays[mapId]?.first
  10842. },
  10843. {
  10844. msg: ' Начать по пути №2! ',
  10845. placeholder: '1,2,3',
  10846. isInput: true,
  10847. default: this.defaultWays[mapId]?.second
  10848. },
  10849. {
  10850. msg: ' Начать по пути №3! ',
  10851. placeholder: '1,2,3',
  10852. isInput: true,
  10853. default: this.defaultWays[mapId]?.third
  10854. },
  10855. {
  10856. msg: I18N('BTN_CANCEL'),
  10857. result: false,
  10858. isCancel: true
  10859. },
  10860. ]);
  10861. if (!answer) {
  10862. this.terminatеReason = I18N('BTN_CANCELED');
  10863. return false;
  10864. }
  10865.  
  10866. let path = answer.split(',');
  10867. if (path.length < 2) {
  10868. path = answer.split('-');
  10869. }
  10870. if (path.length < 2) {
  10871. this.terminatеReason = I18N('MUST_TWO_POINTS');
  10872. return false;
  10873. }
  10874.  
  10875. for (let p in path) {
  10876. path[p] = +path[p].trim()
  10877. if (Number.isNaN(path[p])) {
  10878. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  10879. return false;
  10880. }
  10881. }
  10882.  
  10883. /*if (!this.checkPath(path)) {
  10884. return false;
  10885. }*/
  10886. //setSaveVal(keyPath, answer);
  10887. setSaveVal('adventurePath', answer);
  10888. return path;
  10889. }
  10890. /*
  10891. checkPath(path) {
  10892. for (let i = 0; i < path.length - 1; i++) {
  10893. const currentPoint = path[i];
  10894. const nextPoint = path[i + 1];
  10895.  
  10896. const isValidPath = this.paths.some(p =>
  10897. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  10898. (p.from_id === nextPoint && p.to_id === currentPoint)
  10899. );
  10900.  
  10901. if (!isValidPath) {
  10902. this.terminatеReason = I18N('INCORRECT_WAY', {
  10903. from: currentPoint,
  10904. to: nextPoint,
  10905. });
  10906. return false;
  10907. }
  10908. }
  10909.  
  10910. return true;
  10911. }
  10912. */
  10913. async checkAdventureInfo(data) {
  10914. this.advInfo = data[0].result.response;
  10915. if (!this.advInfo) {
  10916. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  10917. return this.end();
  10918. }
  10919. const heroesTeam = data[1].result.response.adventure_hero;
  10920. const favor = data[2]?.result.response.adventure_hero;
  10921. const heroes = heroesTeam.slice(0, 5);
  10922. const pet = heroesTeam[5];
  10923. this.args = {
  10924. pet,
  10925. heroes,
  10926. favor,
  10927. path: [],
  10928. broadcast: false
  10929. }
  10930. const advUserInfo = this.advInfo.users[userInfo.id];
  10931. this.turnsLeft = advUserInfo.turnsLeft;
  10932. this.currentNode = advUserInfo.currentNode;
  10933. this.nodes = this.advInfo.nodes;
  10934. //this.paths = this.advInfo.paths;
  10935. //this.mapIdent = this.advInfo.mapIdent;
  10936.  
  10937. /*this.path = await this.getPath();
  10938. if (!this.path) {
  10939. return this.end();
  10940. }*/
  10941.  
  10942. if (this.currentNode == 1 && this.path[0] != 1) {
  10943. this.path.unshift(1);
  10944. }
  10945.  
  10946. return this.loop();
  10947. }
  10948.  
  10949. async loop() {
  10950. const position = this.path.indexOf(+this.currentNode);
  10951. if (!(~position)) {
  10952. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  10953. return this.end();
  10954. }
  10955. this.path = this.path.slice(position);
  10956. if ((this.path.length - 1) > this.turnsLeft &&
  10957. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  10958. { msg: I18N('YES_CONTINUE'), result: false },
  10959. { msg: I18N('BTN_NO'), result: true },
  10960. ])) {
  10961. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  10962. return this.end();
  10963. }
  10964. const toPath = [];
  10965. for (const nodeId of this.path) {
  10966. if (!this.turnsLeft) {
  10967. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  10968. return this.end();
  10969. }
  10970. toPath.push(nodeId);
  10971. console.log(toPath);
  10972. if (toPath.length > 1) {
  10973. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  10974. }
  10975. if (nodeId == this.currentNode) {
  10976. continue;
  10977. }
  10978.  
  10979. const nodeInfo = this.getNodeInfo(nodeId);
  10980. if (nodeInfo.type == 'TYPE_COMBAT') {
  10981. if (nodeInfo.state == 'empty') {
  10982. this.turnsLeft--;
  10983. continue;
  10984. }
  10985.  
  10986. /**
  10987. * Disable regular battle cancellation
  10988. *
  10989. * Отключаем штатную отменую боя
  10990. */
  10991. isCancalBattle = false;
  10992. if (await this.battle(toPath)) {
  10993. this.turnsLeft--;
  10994. toPath.splice(0, toPath.indexOf(nodeId));
  10995. nodeInfo.state = 'empty';
  10996. isCancalBattle = true;
  10997. continue;
  10998. }
  10999. isCancalBattle = true;
  11000. return this.end()
  11001. }
  11002.  
  11003. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11004. const buff = this.checkBuff(nodeInfo);
  11005. if (buff == null) {
  11006. continue;
  11007. }
  11008.  
  11009. if (await this.collectBuff(buff, toPath)) {
  11010. this.turnsLeft--;
  11011. toPath.splice(0, toPath.indexOf(nodeId));
  11012. continue;
  11013. }
  11014. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11015. return this.end();
  11016. }
  11017. }
  11018. this.terminatеReason = I18N('SUCCESS');
  11019. return this.end();
  11020. }
  11021.  
  11022. /**
  11023. * Carrying out a fight
  11024. *
  11025. * Проведение боя
  11026. */
  11027. async battle(path, preCalc = true) {
  11028. const data = await this.startBattle(path);
  11029. try {
  11030. const battle = data.results[0].result.response.battle;
  11031. const result = await Calc(battle);
  11032. if (result.result.win) {
  11033. const info = await this.endBattle(result);
  11034. if (info.results[0].result.response?.error) {
  11035. this.terminatеReason = I18N('BATTLE_END_ERROR');
  11036. return false;
  11037. }
  11038. } else {
  11039. await this.cancelBattle(result);
  11040.  
  11041. if (preCalc && await this.preCalcBattle(battle)) {
  11042. path = path.slice(-2);
  11043. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  11044. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  11045. const result = await this.battle(path, false);
  11046. if (result) {
  11047. setProgress(I18N('VICTORY'));
  11048. return true;
  11049. }
  11050. }
  11051. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  11052. return false;
  11053. }
  11054. return false;
  11055. }
  11056. } catch (error) {
  11057. console.error(error);
  11058. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  11059. { msg: I18N('BTN_NO'), result: false },
  11060. { msg: I18N('BTN_YES'), result: true },
  11061. ])) {
  11062. this.errorHandling(error, data);
  11063. }
  11064. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  11065. return false;
  11066. }
  11067. return true;
  11068. }
  11069.  
  11070. /**
  11071. * Recalculate battles
  11072. *
  11073. * Прерасчтет битвы
  11074. */
  11075. async preCalcBattle(battle) {
  11076. const countTestBattle = getInput('countTestBattle');
  11077. for (let i = 0; i < countTestBattle; i++) {
  11078. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  11079. const result = await Calc(battle);
  11080. if (result.result.win) {
  11081. console.log(i, countTestBattle);
  11082. return true;
  11083. }
  11084. }
  11085. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  11086. return false;
  11087. }
  11088.  
  11089. /**
  11090. * Starts a fight
  11091. *
  11092. * Начинает бой
  11093. */
  11094. startBattle(path) {
  11095. this.args.path = path;
  11096. this.callStartBattle.name = this.actions[this.type].startBattle;
  11097. this.callStartBattle.args = this.args
  11098. const calls = [this.callStartBattle];
  11099. return Send(JSON.stringify({ calls }));
  11100. }
  11101.  
  11102. cancelBattle(battle) {
  11103. const fixBattle = function (heroes) {
  11104. for (const ids in heroes) {
  11105. const hero = heroes[ids];
  11106. hero.energy = random(1, 999);
  11107. if (hero.hp > 0) {
  11108. hero.hp = random(1, hero.hp);
  11109. }
  11110. }
  11111. }
  11112. fixBattle(battle.progress[0].attackers.heroes);
  11113. fixBattle(battle.progress[0].defenders.heroes);
  11114. return this.endBattle(battle);
  11115. }
  11116.  
  11117. /**
  11118. * Ends the fight
  11119. *
  11120. * Заканчивает бой
  11121. */
  11122. endBattle(battle) {
  11123. this.callEndBattle.name = this.actions[this.type].endBattle;
  11124. this.callEndBattle.args.result = battle.result
  11125. this.callEndBattle.args.progress = battle.progress
  11126. const calls = [this.callEndBattle];
  11127. return Send(JSON.stringify({ calls }));
  11128. }
  11129.  
  11130. /**
  11131. * Checks if you can get a buff
  11132. *
  11133. * Проверяет можно ли получить баф
  11134. */
  11135. checkBuff(nodeInfo) {
  11136. let id = null;
  11137. let value = 0;
  11138. for (const buffId in nodeInfo.buffs) {
  11139. const buff = nodeInfo.buffs[buffId];
  11140. if (buff.owner == null && buff.value > value) {
  11141. id = buffId;
  11142. value = buff.value;
  11143. }
  11144. }
  11145. nodeInfo.buffs[id].owner = 'Я';
  11146. return id;
  11147. }
  11148.  
  11149. /**
  11150. * Collects a buff
  11151. *
  11152. * Собирает баф
  11153. */
  11154. async collectBuff(buff, path) {
  11155. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  11156. this.callCollectBuff.args = { buff, path };
  11157. const calls = [this.callCollectBuff];
  11158. return Send(JSON.stringify({ calls }));
  11159. }
  11160.  
  11161. getNodeInfo(nodeId) {
  11162. return this.nodes.find(node => node.id == nodeId);
  11163. }
  11164.  
  11165. errorHandling(error, data) {
  11166. //console.error(error);
  11167. let errorInfo = error.toString() + '\n';
  11168. try {
  11169. const errorStack = error.stack.split('\n');
  11170. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  11171. errorInfo += errorStack.slice(0, endStack).join('\n');
  11172. } catch (e) {
  11173. errorInfo += error.stack;
  11174. }
  11175. if (data) {
  11176. errorInfo += '\nData: ' + JSON.stringify(data);
  11177. }
  11178. copyText(errorInfo);
  11179. }
  11180.  
  11181. end() {
  11182. isCancalBattle = true;
  11183. setProgress(this.terminatеReason, true);
  11184. console.log(this.terminatеReason);
  11185. this.resolve();
  11186. }
  11187. }
  11188.  
  11189. /**
  11190. * Passage of brawls
  11191. *
  11192. * Прохождение потасовок
  11193. */
  11194. function testBrawls() {
  11195. return new Promise((resolve, reject) => {
  11196. const brawls = new executeBrawls(resolve, reject);
  11197. brawls.start(brawlsPack);
  11198. });
  11199. }
  11200. /**
  11201. * Passage of brawls
  11202. *
  11203. * Прохождение потасовок
  11204. */
  11205. class executeBrawls {
  11206. callBrawlQuestGetInfo = {
  11207. name: "brawl_questGetInfo",
  11208. args: {},
  11209. ident: "brawl_questGetInfo"
  11210. }
  11211. callBrawlFindEnemies = {
  11212. name: "brawl_findEnemies",
  11213. args: {},
  11214. ident: "brawl_findEnemies"
  11215. }
  11216. callBrawlQuestFarm = {
  11217. name: "brawl_questFarm",
  11218. args: {},
  11219. ident: "brawl_questFarm"
  11220. }
  11221. callUserGetInfo = {
  11222. name: "userGetInfo",
  11223. args: {},
  11224. ident: "userGetInfo"
  11225. }
  11226. callTeamGetMaxUpgrade = {
  11227. name: "teamGetMaxUpgrade",
  11228. args: {},
  11229. ident: "teamGetMaxUpgrade"
  11230. }
  11231. callBrawlGetInfo = {
  11232. name: "brawl_getInfo",
  11233. args: {},
  11234. ident: "brawl_getInfo"
  11235. }
  11236.  
  11237. stats = {
  11238. win: 0,
  11239. loss: 0,
  11240. count: 0,
  11241. }
  11242.  
  11243. stage = {
  11244. '3': 1,
  11245. '7': 2,
  11246. '12': 3,
  11247. }
  11248.  
  11249. attempts = 0;
  11250.  
  11251. constructor(resolve, reject) {
  11252. this.resolve = resolve;
  11253. this.reject = reject;
  11254. }
  11255.  
  11256. async start(args) {
  11257. this.args = args;
  11258. isCancalBattle = false;
  11259. this.brawlInfo = await this.getBrawlInfo();
  11260. this.attempts = this.brawlInfo.attempts;
  11261.  
  11262. if (!this.attempts) {
  11263. this.end(I18N('DONT_HAVE_LIVES'))
  11264. return;
  11265. }
  11266.  
  11267. while (1) {
  11268. if (!isBrawlsAutoStart) {
  11269. this.end(I18N('BTN_CANCELED'))
  11270. return;
  11271. }
  11272.  
  11273. const maxStage = this.brawlInfo.questInfo.stage;
  11274. const stage = this.stage[maxStage];
  11275. const progress = this.brawlInfo.questInfo.progress;
  11276.  
  11277. setProgress(`${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${this.stats.win}<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`, false, function () {
  11278. isBrawlsAutoStart = false;
  11279. });
  11280.  
  11281. if (this.brawlInfo.questInfo.canFarm) {
  11282. const result = await this.questFarm();
  11283. console.log(result);
  11284. }
  11285.  
  11286. if (this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  11287. this.end(I18N('SUCCESS'))
  11288. return;
  11289. }
  11290.  
  11291. if (!this.attempts) {
  11292. this.end(I18N('DONT_HAVE_LIVES'))
  11293. return;
  11294. }
  11295.  
  11296. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  11297.  
  11298. // Для потасовок брустара
  11299. this.args.heroes = await this.updatePack(enemie.heroes);
  11300.  
  11301. const result = await this.battle(enemie.userId);
  11302. this.brawlInfo = {
  11303. questInfo: result[1].result.response,
  11304. findEnemies: result[2].result.response,
  11305. }
  11306. }
  11307. }
  11308.  
  11309. async updatePack(enemieHeroes) {
  11310. const packs = [
  11311. // 4023 Эдем
  11312. [4020, 4022, 4023, 4042, 4043],
  11313. [4023, 4030, 4033, 4042, 4043],
  11314. [4023, 4040, 4041, 4042, 4043],
  11315. // Разное
  11316. [4003, 4010, 4011, 4012, 4013],
  11317. [4030, 4032, 4033, 4040, 4043],
  11318. [4033, 4040, 4041, 4042, 4043],
  11319. [4030, 4031, 4033, 4040, 4043],
  11320. [4030, 4033, 4040, 4042, 4043],
  11321. [4001, 4032, 4033, 4040, 4043],
  11322. [4010, 4012, 4013, 4040, 4043],
  11323. [4001, 4002, 4003, 4040, 4043],
  11324. // 4003 Гиперион
  11325. [4000, 4001, 4003, 4033, 4043],
  11326. [4000, 4001, 4003, 4023, 4030],
  11327. [4000, 4001, 4003, 4023, 4033],
  11328. [4000, 4001, 4003, 4013, 4033],
  11329. [4003, 4010, 4012, 4013, 4043],
  11330. [4003, 4010, 4012, 4013, 4033],
  11331. [4003, 4030, 4032, 4042, 4043],
  11332. [4003, 4030, 4031, 4032, 4033],
  11333. [4003, 4040, 4041, 4042, 4043],
  11334. [4003, 4030, 4033, 4040, 4043],
  11335. // 4013 Араджи
  11336. [4010, 4011, 4012, 4013, 4033],
  11337. [4010, 4011, 4012, 4013, 4043],
  11338. [4010, 4011, 4013, 4042, 4043],
  11339. [4010, 4011, 4013, 4033, 4043],
  11340. [4001, 4010, 4011, 4013, 4033],
  11341. [4010, 4011, 4013, 4030, 4033],
  11342. [4010, 4011, 4013, 4040, 4043],
  11343. [4013, 4030, 4033, 4040, 4043],
  11344. [4013, 4030, 4033, 4042, 4043],
  11345. [4013, 4020, 4022, 4023, 4033],
  11346. ].filter(p => p.includes(this.mandatoryId))
  11347.  
  11348. const bestPack = {
  11349. pack: packs[0],
  11350. countWin: 0,
  11351. }
  11352.  
  11353. for (const pack of packs) {
  11354. const attackers = this.maxUpgrade
  11355. .filter(e => pack.includes(e.id))
  11356. .reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  11357. const battle = {
  11358. attackers,
  11359. defenders: [enemieHeroes],
  11360. type: "brawl_titan",
  11361. }
  11362.  
  11363. let countWinBattles = 0;
  11364. let countTestBattle = 10;
  11365. for (let i = 0; i < countTestBattle; i++) {
  11366. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  11367. const result = await Calc(battle);
  11368. if (result.result.win) {
  11369. countWinBattles++;
  11370. }
  11371. if (countWinBattles > 7) {
  11372. console.log(pack)
  11373. return pack;
  11374. }
  11375. }
  11376. if (countWinBattles > bestPack.countWin) {
  11377. bestPack.countWin = countWinBattles;
  11378. bestPack.pack = pack;
  11379. }
  11380. }
  11381.  
  11382. console.log(bestPack);
  11383. return bestPack.pack;
  11384. }
  11385.  
  11386. async questFarm() {
  11387. const calls = [this.callBrawlQuestFarm];
  11388. const result = await Send(JSON.stringify({ calls }));
  11389. return result.results[0].result.response;
  11390. }
  11391.  
  11392. async getBrawlInfo() {
  11393. const data = await Send(JSON.stringify({
  11394. calls: [
  11395. this.callUserGetInfo,
  11396. this.callBrawlQuestGetInfo,
  11397. this.callBrawlFindEnemies,
  11398. this.callTeamGetMaxUpgrade,
  11399. this.callBrawlGetInfo,
  11400. ]
  11401. }));
  11402.  
  11403. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  11404. this.maxUpgrade = Object.values(data.results[3].result.response.titan);
  11405. this.info = data.results[4].result.response;
  11406. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  11407. return {
  11408. attempts: attempts.amount,
  11409. questInfo: data.results[1].result.response,
  11410. findEnemies: data.results[2].result.response,
  11411. }
  11412. }
  11413.  
  11414. /**
  11415. * Carrying out a fight
  11416. *
  11417. * Проведение боя
  11418. */
  11419. async battle(userId) {
  11420. this.stats.count++;
  11421. const battle = await this.startBattle(userId, this.args);
  11422. const result = await Calc(battle);
  11423. console.log(result.result);
  11424. if (result.result.win) {
  11425. this.stats.win++;
  11426. } else {
  11427. this.stats.loss++;
  11428. this.attempts--;
  11429. }
  11430. return await this.endBattle(result);
  11431. // return await this.cancelBattle(result);
  11432. }
  11433.  
  11434. /**
  11435. * Starts a fight
  11436. *
  11437. * Начинает бой
  11438. */
  11439. async startBattle(userId, args) {
  11440. const call = {
  11441. name: "brawl_startBattle",
  11442. args,
  11443. ident: "brawl_startBattle"
  11444. }
  11445. call.args.userId = userId;
  11446. const calls = [call];
  11447. const result = await Send(JSON.stringify({ calls }));
  11448. return result.results[0].result.response;
  11449. }
  11450.  
  11451. cancelBattle(battle) {
  11452. const fixBattle = function (heroes) {
  11453. for (const ids in heroes) {
  11454. const hero = heroes[ids];
  11455. hero.energy = random(1, 999);
  11456. if (hero.hp > 0) {
  11457. hero.hp = random(1, hero.hp);
  11458. }
  11459. }
  11460. }
  11461. fixBattle(battle.progress[0].attackers.heroes);
  11462. fixBattle(battle.progress[0].defenders.heroes);
  11463. return this.endBattle(battle);
  11464. }
  11465.  
  11466. /**
  11467. * Ends the fight
  11468. *
  11469. * Заканчивает бой
  11470. */
  11471. async endBattle(battle) {
  11472. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  11473. const calls = [{
  11474. name: "brawl_endBattle",
  11475. args: {
  11476. result: battle.result,
  11477. progress: battle.progress
  11478. },
  11479. ident: "brawl_endBattle"
  11480. },
  11481. this.callBrawlQuestGetInfo,
  11482. this.callBrawlFindEnemies,
  11483. ];
  11484. const result = await Send(JSON.stringify({ calls }));
  11485. return result.results;
  11486. }
  11487.  
  11488. end(endReason) {
  11489. isCancalBattle = true;
  11490. isBrawlsAutoStart = false;
  11491. setProgress(endReason, true);
  11492. console.log(endReason);
  11493. this.resolve();
  11494. }
  11495. }
  11496.  
  11497. class executeEventAutoBoss {
  11498.  
  11499. async start() {
  11500. await this.loadInfo();
  11501. this.generateCombo();
  11502.  
  11503. const countTestBattle = +getInput('countTestBattle');
  11504. const maxCalcBattle = this.combo.length * countTestBattle;
  11505.  
  11506. const resultDialog = await popup.confirm(I18N('EVENT_AUTO_BOSS', {
  11507. length: this.combo.length,
  11508. countTestBattle,
  11509. maxCalcBattle
  11510. }), [
  11511. { msg: I18N('BEST_SLOW'), result: true },
  11512. { msg: I18N('FIRST_FAST'), result: false },
  11513. { isClose: true, result: 'exit' },
  11514. ]);
  11515.  
  11516. if (resultDialog == 'exit') {
  11517. this.end('Отменено');
  11518. return;
  11519. }
  11520.  
  11521. popup.confirm(I18N('FREEZE_INTERFACE'));
  11522.  
  11523. setTimeout(() => {
  11524. this.startFindPack(resultDialog)
  11525. }, 1000)
  11526. }
  11527.  
  11528. async loadInfo() {
  11529. const resultReq = await Send({ calls: [{ name: "teamGetMaxUpgrade", args: {}, ident: "group_1_body" }, { name: "invasion_bossStart", args: { id: 119, heroes: [3, 61], favor: { "61": 6001 } }, ident: "body" }] }).then(e => e.results);
  11530. this.heroes = resultReq[0].result.response;
  11531. this.battle = resultReq[1].result.response;
  11532.  
  11533. this.heroes.hero[61] = this.battle.attackers[1];
  11534. this.battle.attackers = [];
  11535. }
  11536.  
  11537. combinations(arr, n) {
  11538. if (n == 1) {
  11539. return arr.map(function (x) { return [x]; });
  11540. }
  11541. else if (n <= 0) {
  11542. return [];
  11543. }
  11544. var result = [];
  11545. for (var i = 0; i < arr.length; i++) {
  11546. var rest = arr.slice(i + 1);
  11547. var c = this.combinations(rest, n - 1);
  11548. for (var j = 0; j < c.length; j++) {
  11549. c[j].unshift(arr[i]);
  11550. result.push(c[j]);
  11551. }
  11552. }
  11553. return result;
  11554. }
  11555.  
  11556. generateCombo() {
  11557. // const heroesIds = [3, 7, 8, 9, 12, 16, 18, 22, 35, 40, 48, 57, 58, 59];
  11558. const heroesIds = [3, 7, 9, 12, 18, 22, 35, 40, 48, 57, 58, 59];
  11559. this.combo = this.combinations(heroesIds, 4);
  11560. }
  11561.  
  11562. async startFindPack(findBestOfAll) {
  11563. const promises = [];
  11564. let bestBattle = null;
  11565. for (const comb of this.combo) {
  11566. const copyBattle = structuredClone(this.battle);
  11567. const attackers = [];
  11568. for (const id of comb) {
  11569. if (this.heroes.hero[id]) {
  11570. attackers.push(this.heroes.hero[id]);
  11571. }
  11572. }
  11573. attackers.push(this.heroes.hero[61]);
  11574. attackers.push(this.heroes.pet[6001]);
  11575. copyBattle.attackers = attackers;
  11576. const countTestBattle = +getInput('countTestBattle');
  11577. if (findBestOfAll) {
  11578. promises.push(this.CalcBattle(copyBattle, countTestBattle));
  11579. } else {
  11580. try {
  11581. const checkBattle = await this.CalcBattle(copyBattle, countTestBattle);
  11582. if (checkBattle.result.win) {
  11583. bestBattle = checkBattle;
  11584. break;
  11585. }
  11586. } catch(e) {
  11587. console.log(e, copyBattle)
  11588. popup.confirm(I18N('ERROR_F12'));
  11589. this.end(I18N('ERROR_F12'), e, copyBattle)
  11590. return;
  11591. }
  11592. }
  11593. }
  11594.  
  11595. if (findBestOfAll) {
  11596. bestBattle = await Promise.all(promises)
  11597. .then(results => {
  11598. results = results.sort((a, b) => b.coeff - a.coeff).slice(0, 10);
  11599. let maxStars = 0;
  11600. let maxCoeff = -100;
  11601. let maxBattle = null;
  11602. results.forEach(e => {
  11603. if (e.stars > maxStars || e.coeff > maxCoeff) {
  11604. maxCoeff = e.coeff;
  11605. maxStars = e.stars;
  11606. maxBattle = e;
  11607. }
  11608. });
  11609. console.log(results);
  11610. console.log('better', maxCoeff, maxStars, maxBattle, maxBattle.battleData.attackers.map(e => e.id));
  11611. return maxBattle;
  11612. });
  11613. }
  11614.  
  11615. if (!bestBattle || !bestBattle.result.win) {
  11616. let msg = I18N('FAILED_FIND_WIN_PACK');
  11617. let msgc = msg;
  11618. if (bestBattle?.battleData) {
  11619. const heroes = bestBattle.battleData.attackers.map(e => e.id).filter(e => e < 61);
  11620. msg += `</br>${I18N('BEST_PACK')}</br>` + heroes.map(
  11621. id => `<img src="https://heroesweb-a.akamaihd.net/vk/v0952/assets/hero_icons/${('000' + id).slice(-4)}.png"/>`
  11622. ).join('');
  11623. msgc += I18N('BEST_PACK') + heroes.join(',')
  11624. }
  11625.  
  11626. await popup.confirm(msg);
  11627. this.end(msgc);
  11628. return;
  11629. }
  11630.  
  11631. this.heroesPack = bestBattle.battleData.attackers.map(e => e.id).filter(e => e < 6000);
  11632. this.battleLoop();
  11633. }
  11634.  
  11635. async battleLoop() {
  11636. let repeat = false;
  11637. do {
  11638. repeat = false;
  11639. const countAutoBattle = +getInput('countAutoBattle');
  11640. for (let i = 1; i <= countAutoBattle; i++) {
  11641. const startBattle = await Send({
  11642. calls: [{
  11643. name: "invasion_bossStart",
  11644. args: {
  11645. id: 119,
  11646. heroes: this.heroesPack,
  11647. favor: { "61": 6001 },
  11648. pet: 6001
  11649. }, ident: "body"
  11650. }]
  11651. }).then(e => e.results[0].result.response);
  11652. const calcBattle = await Calc(startBattle);
  11653.  
  11654. setProgress(`${i}) ${calcBattle.result.win ? I18N('VICTORY') : I18N('DEFEAT') } `)
  11655. console.log(i, calcBattle.result.win)
  11656. if (!calcBattle.result.win) {
  11657. continue;
  11658. }
  11659.  
  11660. const endBattle = await Send({
  11661. calls: [{
  11662. name: "invasion_bossEnd",
  11663. args: {
  11664. id: 119,
  11665. result: calcBattle.result,
  11666. progress: calcBattle.progress
  11667. }, ident: "body"
  11668. }]
  11669. }).then(e => e.results[0].result.response);
  11670. console.log(endBattle);
  11671. const msg = I18N('BOSS_HAS_BEEN_DEF', { bossLvl: this.battle.typeId });
  11672. await popup.confirm(msg);
  11673. this.end(msg);
  11674. return;
  11675. }
  11676.  
  11677. const msg = I18N('NOT_ENOUGH_ATTEMPTS_BOSS', { bossLvl: this.battle.typeId });
  11678. repeat = await popup.confirm(msg, [
  11679. { msg: 'Да', result: true },
  11680. { msg: 'Нет', result: false },
  11681. ]);
  11682. this.end(I18N('NOT_ENOUGH_ATTEMPTS_BOSS', { bossLvl: this.battle.typeId }));
  11683.  
  11684. } while (repeat)
  11685. }
  11686.  
  11687. calcCoeff(result, packType) {
  11688. let beforeSumFactor = 0;
  11689. const beforePack = result.battleData[packType][0];
  11690. for (let heroId in beforePack) {
  11691. const hero = beforePack[heroId];
  11692. const state = hero.state;
  11693. let factor = 1;
  11694. if (state) {
  11695. const hp = state.hp / state.maxHp;
  11696. factor = hp;
  11697. }
  11698. beforeSumFactor += factor;
  11699. }
  11700.  
  11701. let afterSumFactor = 0;
  11702. const afterPack = result.progress[0][packType].heroes;
  11703. for (let heroId in afterPack) {
  11704. const hero = afterPack[heroId];
  11705. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  11706. const hp = hero.hp / stateHp;
  11707. afterSumFactor += hp;
  11708. }
  11709. const resultCoeff = beforeSumFactor / afterSumFactor;
  11710. return resultCoeff;
  11711. }
  11712.  
  11713. async CalcBattle(battle, count) {
  11714. const actions = [];
  11715. for (let i = 0; i < count; i++) {
  11716. battle.seed = Math.floor(Date.now() / 1000) + this.random(0, 1e3);
  11717. actions.push(Calc(battle).then(e => {
  11718. e.coeff = this.calcCoeff(e, 'defenders');
  11719. return e;
  11720. }));
  11721. }
  11722.  
  11723. return Promise.all(actions).then(results => {
  11724. let maxCoeff = -100;
  11725. let maxBattle = null;
  11726. results.forEach(e => {
  11727. if (e.coeff > maxCoeff) {
  11728. maxCoeff = e.coeff;
  11729. maxBattle = e;
  11730. }
  11731. });
  11732. maxBattle.stars = results.reduce((w, s) => w + s.result.stars, 0);
  11733. maxBattle.attempts = results;
  11734. return maxBattle;
  11735. });
  11736. }
  11737.  
  11738. random(min, max) {
  11739. return Math.floor(Math.random() * (max - min + 1) + min);
  11740. }
  11741.  
  11742. end(reason) {
  11743. setProgress('');
  11744. console.log('endEventAutoBoss', reason)
  11745. }
  11746. }
  11747.  
  11748. // подземку вконце впихнул
  11749. function DungeonFull() {
  11750. return new Promise((resolve, reject) => {
  11751. const dung = new executeDungeon2(resolve, reject);
  11752. const titanit = getInput('countTitanit');
  11753. dung.start(titanit);
  11754. });
  11755. }
  11756. /** Прохождение подземелья */
  11757. function executeDungeon2(resolve, reject) {
  11758. let dungeonActivity = 0;
  11759. let startDungeonActivity = 0;
  11760. let maxDungeonActivity = 150;
  11761. let limitDungeonActivity = 30180;
  11762. let countShowStats = 1;
  11763. //let fastMode = isChecked('fastMode');
  11764. let end = false;
  11765.  
  11766. let countTeam = [];
  11767. let timeDungeon = {
  11768. all: new Date().getTime(),
  11769. findAttack: 0,
  11770. attackNeutral: 0,
  11771. attackEarthOrFire: 0
  11772. }
  11773.  
  11774. let titansStates = {};
  11775. let bestBattle = {};
  11776.  
  11777. let teams = {
  11778. neutral: [],
  11779. water: [],
  11780. earth: [],
  11781. fire: [],
  11782. hero: []
  11783. }
  11784.  
  11785. let callsExecuteDungeon = {
  11786. calls: [{
  11787. name: "dungeonGetInfo",
  11788. args: {},
  11789. ident: "dungeonGetInfo"
  11790. }, {
  11791. name: "teamGetAll",
  11792. args: {},
  11793. ident: "teamGetAll"
  11794. }, {
  11795. name: "teamGetFavor",
  11796. args: {},
  11797. ident: "teamGetFavor"
  11798. }, {
  11799. name: "clanGetInfo",
  11800. args: {},
  11801. ident: "clanGetInfo"
  11802. }]
  11803. }
  11804.  
  11805. this.start = async function(titanit) {
  11806. //maxDungeonActivity = titanit > limitDungeonActivity ? limitDungeonActivity : titanit;
  11807. maxDungeonActivity = titanit || getInput('countTitanit');
  11808. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  11809. }
  11810.  
  11811. /** Получаем данные по подземелью */
  11812. function startDungeon(e) {
  11813. stopDung = false; // стоп подземка
  11814. let res = e.results;
  11815. let dungeonGetInfo = res[0].result.response;
  11816. if (!dungeonGetInfo) {
  11817. endDungeon('noDungeon', res);
  11818. return;
  11819. }
  11820. console.log("Начинаем копать на фулл: ", new Date());
  11821. let teamGetAll = res[1].result.response;
  11822. let teamGetFavor = res[2].result.response;
  11823. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  11824. startDungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  11825. titansStates = dungeonGetInfo.states.titans;
  11826.  
  11827. teams.hero = {
  11828. favor: teamGetFavor.dungeon_hero,
  11829. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  11830. teamNum: 0,
  11831. }
  11832. let heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  11833. if (heroPet) {
  11834. teams.hero.pet = heroPet;
  11835. }
  11836. teams.neutral = getTitanTeam('neutral');
  11837. teams.water = {
  11838. favor: {},
  11839. heroes: getTitanTeam('water'),
  11840. teamNum: 0,
  11841. };
  11842. teams.earth = {
  11843. favor: {},
  11844. heroes: getTitanTeam('earth'),
  11845. teamNum: 0,
  11846. };
  11847. teams.fire = {
  11848. favor: {},
  11849. heroes: getTitanTeam('fire'),
  11850. teamNum: 0,
  11851. };
  11852.  
  11853. checkFloor(dungeonGetInfo);
  11854. }
  11855.  
  11856. function getTitanTeam(type) {
  11857. switch (type) {
  11858. case 'neutral':
  11859. return [4023, 4022, 4012, 4021, 4011, 4010, 4020];
  11860. case 'water':
  11861. return [4000, 4001, 4002, 4003]
  11862. .filter(e => !titansStates[e]?.isDead);
  11863. case 'earth':
  11864. return [4020, 4022, 4021, 4023]
  11865. .filter(e => !titansStates[e]?.isDead);
  11866. case 'fire':
  11867. return [4010, 4011, 4012, 4013]
  11868. .filter(e => !titansStates[e]?.isDead);
  11869. }
  11870. }
  11871.  
  11872. /** Создать копию объекта */
  11873. function clone(a) {
  11874. return JSON.parse(JSON.stringify(a));
  11875. }
  11876.  
  11877. /** Находит стихию на этаже */
  11878. function findElement(floor, element) {
  11879. for (let i in floor) {
  11880. if (floor[i].attackerType === element) {
  11881. return i;
  11882. }
  11883. }
  11884. return undefined;
  11885. }
  11886.  
  11887. /** Проверяем этаж */
  11888. async function checkFloor(dungeonInfo) {
  11889. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  11890. saveProgress();
  11891. return;
  11892. }
  11893. // console.log(dungeonInfo, dungeonActivity);
  11894. setProgress(`${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  11895. //setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  11896. if (dungeonActivity >= maxDungeonActivity) {
  11897. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  11898. return;
  11899. }
  11900. let activity = dungeonActivity - startDungeonActivity;
  11901. titansStates = dungeonInfo.states.titans;
  11902. if (stopDung){
  11903. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  11904. return;
  11905. }
  11906. /*if (activity / 1000 > countShowStats) {
  11907. countShowStats++;
  11908. showStats();
  11909. }*/
  11910. bestBattle = {};
  11911. let floorChoices = dungeonInfo.floor.userData;
  11912. if (floorChoices.length > 1) {
  11913. for (let element in teams) {
  11914. let teamNum = findElement(floorChoices, element);
  11915. if (!!teamNum) {
  11916. if (element == 'earth') {
  11917. teamNum = await chooseEarthOrFire(floorChoices);
  11918. if (teamNum < 0) {
  11919. endDungeon('Невозможно победить без потери Титана!', dungeonInfo);
  11920. return;
  11921. }
  11922. }
  11923. chooseElement(floorChoices[teamNum].attackerType, teamNum);
  11924. return;
  11925. }
  11926. }
  11927. } else {
  11928. chooseElement(floorChoices[0].attackerType, 0);
  11929. }
  11930. }
  11931.  
  11932. /** Выбираем огнем или землей атаковать */
  11933. async function chooseEarthOrFire(floorChoices) {
  11934. bestBattle.recovery = -11;
  11935. let selectedTeamNum = -1;
  11936. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  11937. for (let teamNum in floorChoices) {
  11938. let attackerType = floorChoices[teamNum].attackerType;
  11939. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  11940. }
  11941. }
  11942. console.log("Выбор команды огня или земли: ", selectedTeamNum < 0 ? "не сделан" : floorChoices[selectedTeamNum].attackerType);
  11943. return selectedTeamNum;
  11944. }
  11945.  
  11946. /** Попытка атаки землей и огнем */
  11947. async function attemptAttackEarthOrFire(teamNum, attackerType, attempt) {
  11948. let start = new Date();
  11949. let team = clone(teams[attackerType]);
  11950. let startIndex = team.heroes.length + attempt - 4;
  11951. if (startIndex >= 0) {
  11952. team.heroes = team.heroes.slice(startIndex);
  11953. let recovery = await getBestRecovery(teamNum, attackerType, team, 25);
  11954. if (recovery > bestBattle.recovery) {
  11955. bestBattle.recovery = recovery;
  11956. bestBattle.selectedTeamNum = teamNum;
  11957. bestBattle.team = team;
  11958. }
  11959. }
  11960. let workTime = new Date().getTime() - start.getTime();
  11961. timeDungeon.attackEarthOrFire += workTime;
  11962. if (bestBattle.recovery < -10) {
  11963. return -1;
  11964. }
  11965. return bestBattle.selectedTeamNum;
  11966. }
  11967.  
  11968. /** Выбираем стихию для атаки */
  11969. async function chooseElement(attackerType, teamNum) {
  11970. let result;
  11971. switch (attackerType) {
  11972. case 'hero':
  11973. case 'water':
  11974. result = await startBattle(teamNum, attackerType, teams[attackerType]);
  11975. break;
  11976. case 'earth':
  11977. case 'fire':
  11978. result = await attackEarthOrFire(teamNum, attackerType);
  11979. break;
  11980. case 'neutral':
  11981. result = await attackNeutral(teamNum, attackerType);
  11982. }
  11983. if (!!result && attackerType != 'hero') {
  11984. let recovery = (!!!bestBattle.recovery ? 10 * getRecovery(result) : bestBattle.recovery) * 100;
  11985. let titans = result.progress[0].attackers.heroes;
  11986. console.log("Проведен бой: " + attackerType +
  11987. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", titans);
  11988. }
  11989. endBattle(result);
  11990. }
  11991.  
  11992. /** Атакуем Землей или Огнем */
  11993. async function attackEarthOrFire(teamNum, attackerType) {
  11994. if (!!!bestBattle.recovery) {
  11995. bestBattle.recovery = -11;
  11996. let selectedTeamNum = -1;
  11997. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  11998. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  11999. }
  12000. if (selectedTeamNum < 0) {
  12001. endDungeon('Невозможно победить без потери Титана!', attackerType);
  12002. return;
  12003. }
  12004. }
  12005. return findAttack(teamNum, attackerType, bestBattle.team);
  12006. }
  12007.  
  12008. /** Находим подходящий результат для атаки */
  12009. async function findAttack(teamNum, attackerType, team) {
  12010. let start = new Date();
  12011. let recovery = -1000;
  12012. let iterations = 0;
  12013. let result;
  12014. let correction = 0.01;
  12015. for (let needRecovery = bestBattle.recovery; recovery < needRecovery; needRecovery -= correction, iterations++) {
  12016. result = await startBattle(teamNum, attackerType, team);
  12017. recovery = getRecovery(result);
  12018. }
  12019. bestBattle.recovery = recovery;
  12020. let workTime = new Date().getTime() - start.getTime();
  12021. timeDungeon.findAttack += workTime;
  12022. return result;
  12023. }
  12024.  
  12025. /** Атакуем Нейтральной командой */
  12026. async function attackNeutral(teamNum, attackerType) {
  12027. let start = new Date();
  12028. let factors = calcFactor();
  12029. bestBattle.recovery = -0.2;
  12030. await findBestBattleNeutral(teamNum, attackerType, factors, true)
  12031. if (bestBattle.recovery < 0 || (bestBattle.recovery < 0.2 && factors[0].value < 0.5)) {
  12032. let recovery = 100 * bestBattle.recovery;
  12033. console.log("Не удалось найти удачный бой в быстром режиме: " + attackerType +
  12034. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", bestBattle.attackers);
  12035. await findBestBattleNeutral(teamNum, attackerType, factors, false)
  12036. }
  12037. let workTime = new Date().getTime() - start.getTime();
  12038. timeDungeon.attackNeutral += workTime;
  12039. if (!!bestBattle.attackers) {
  12040. let team = getTeam(bestBattle.attackers);
  12041. return findAttack(teamNum, attackerType, team);
  12042. }
  12043. endDungeon('Не удалось найти удачный бой!', attackerType);
  12044. return undefined;
  12045. }
  12046.  
  12047. /** Находит лучшую нейтральную команду */
  12048. async function findBestBattleNeutral(teamNum, attackerType, factors, mode) {
  12049. let countFactors = factors.length < 4 ? factors.length : 4;
  12050. let aradgi = !titansStates['4013']?.isDead;
  12051. let edem = !titansStates['4023']?.isDead;
  12052. let dark = [4032, 4033].filter(e => !titansStates[e]?.isDead);
  12053. let light = [4042].filter(e => !titansStates[e]?.isDead);
  12054. let actions = [];
  12055. if (mode) {
  12056. for (let i = 0; i < countFactors; i++) {
  12057. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  12058. }
  12059. if (countFactors > 1) {
  12060. let firstId = factors[0].id;
  12061. let secondId = factors[1].id;
  12062. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12063. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12064. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, secondId)));
  12065. }
  12066. if (aradgi) {
  12067. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  12068. if (countFactors > 0) {
  12069. let firstId = factors[0].id;
  12070. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4000, 4013)));
  12071. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, 4013)));
  12072. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, 4013)));
  12073. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, 4013)));
  12074. }
  12075. if (edem) {
  12076. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4023, 4000, 4013)));
  12077. }
  12078. }
  12079. } else {
  12080. if (mode) {
  12081. for (let i = 0; i < factors.length; i++) {
  12082. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  12083. }
  12084. } else {
  12085. countFactors = factors.length < 2 ? factors.length : 2;
  12086. }
  12087. for (let i = 0; i < countFactors; i++) {
  12088. let mainId = factors[i].id;
  12089. if (aradgi && (mode || i > 0)) {
  12090. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, 4013)));
  12091. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, 4013)));
  12092. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, 4013)));
  12093. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, 4013)));
  12094. }
  12095. for (let i = 0; i < dark.length; i++) {
  12096. let darkId = dark[i];
  12097. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, darkId)));
  12098. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, darkId)));
  12099. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, darkId)));
  12100. }
  12101. for (let i = 0; i < light.length; i++) {
  12102. let lightId = light[i];
  12103. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, lightId)));
  12104. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, lightId)));
  12105. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, lightId)));
  12106. }
  12107. let isFull = mode || i > 0;
  12108. for (let j = isFull ? i + 1 : 2; j < factors.length; j++) {
  12109. let extraId = factors[j].id;
  12110. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, extraId)));
  12111. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, extraId)));
  12112. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, extraId)));
  12113. }
  12114. }
  12115. if (aradgi) {
  12116. if (mode) {
  12117. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  12118. }
  12119. for (let i = 0; i < dark.length; i++) {
  12120. let darkId = dark[i];
  12121. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4001, 4013)));
  12122. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4002, 4013)));
  12123. }
  12124. for (let i = 0; i < light.length; i++) {
  12125. let lightId = light[i];
  12126. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4001, 4013)));
  12127. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4002, 4013)));
  12128. }
  12129. }
  12130. for (let i = 0; i < dark.length; i++) {
  12131. let firstId = dark[i];
  12132. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  12133. for (let j = i + 1; j < dark.length; j++) {
  12134. let secondId = dark[j];
  12135. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12136. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12137. }
  12138. }
  12139. for (let i = 0; i < light.length; i++) {
  12140. let firstId = light[i];
  12141. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  12142. for (let j = i + 1; j < light.length; j++) {
  12143. let secondId = light[j];
  12144. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  12145. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  12146. }
  12147. }
  12148. }
  12149. for (let result of await Promise.all(actions)) {
  12150. let recovery = getRecovery(result);
  12151. if (recovery > bestBattle.recovery) {
  12152. bestBattle.recovery = recovery;
  12153. bestBattle.attackers = result.progress[0].attackers.heroes;
  12154. }
  12155. }
  12156. }
  12157.  
  12158. /** Получаем нейтральную команду */
  12159. function getNeutralTeam(id, swapId, addId) {
  12160. let neutralTeam = clone(teams.water);
  12161. let neutral = neutralTeam.heroes;
  12162. if (neutral.length == 4) {
  12163. if (!!swapId) {
  12164. for (let i in neutral) {
  12165. if (neutral[i] == swapId) {
  12166. neutral[i] = addId;
  12167. }
  12168. }
  12169. }
  12170. } else if (!!addId) {
  12171. neutral.push(addId);
  12172. }
  12173. neutral.push(id);
  12174. return neutralTeam;
  12175. }
  12176.  
  12177. /** Получить команду титанов */
  12178. function getTeam(titans) {
  12179. return {
  12180. favor: {},
  12181. heroes: Object.keys(titans).map(id => parseInt(id)),
  12182. teamNum: 0,
  12183. };
  12184. }
  12185.  
  12186. /** Вычисляем фактор боеготовности титанов */
  12187. function calcFactor() {
  12188. let neutral = teams.neutral;
  12189. let factors = [];
  12190. for (let i in neutral) {
  12191. let titanId = neutral[i];
  12192. let titan = titansStates[titanId];
  12193. let factor = !!titan ? titan.hp / titan.maxHp + titan.energy / 10000.0 : 1;
  12194. if (factor > 0) {
  12195. factors.push({id: titanId, value: factor});
  12196. }
  12197. }
  12198. factors.sort(function(a, b) {
  12199. return a.value - b.value;
  12200. });
  12201. return factors;
  12202. }
  12203.  
  12204. /** Возвращает наилучший результат из нескольких боев */
  12205. async function getBestRecovery(teamNum, attackerType, team, countBattle) {
  12206. let bestRecovery = -1000;
  12207. let actions = [];
  12208. for (let i = 0; i < countBattle; i++) {
  12209. actions.push(startBattle(teamNum, attackerType, team));
  12210. }
  12211. for (let result of await Promise.all(actions)) {
  12212. let recovery = getRecovery(result);
  12213. if (recovery > bestRecovery) {
  12214. bestRecovery = recovery;
  12215. }
  12216. }
  12217. return bestRecovery;
  12218. }
  12219.  
  12220. /** Возвращает разницу в здоровье атакующей команды после и до битвы и проверяет здоровье титанов на необходимый минимум*/
  12221. function getRecovery(result) {
  12222. if (result.result.stars < 3) {
  12223. return -100;
  12224. }
  12225. let beforeSumFactor = 0;
  12226. let afterSumFactor = 0;
  12227. let beforeTitans = result.battleData.attackers;
  12228. let afterTitans = result.progress[0].attackers.heroes;
  12229. for (let i in afterTitans) {
  12230. let titan = afterTitans[i];
  12231. let percentHP = titan.hp / beforeTitans[i].hp;
  12232. let energy = titan.energy;
  12233. let factor = checkTitan(i, energy, percentHP) ? getFactor(i, energy, percentHP) : -100;
  12234. afterSumFactor += factor;
  12235. }
  12236. for (let i in beforeTitans) {
  12237. let titan = beforeTitans[i];
  12238. let state = titan.state;
  12239. beforeSumFactor += !!state ? getFactor(i, state.energy, state.hp / titan.hp) : 1;
  12240. }
  12241. return afterSumFactor - beforeSumFactor;
  12242. }
  12243.  
  12244. /** Возвращает состояние титана*/
  12245. function getFactor(id, energy, percentHP) {
  12246. let elemantId = id.slice(2, 3);
  12247. let isEarthOrFire = elemantId == '1' || elemantId == '2';
  12248. let energyBonus = id == '4020' && energy == 1000 ? 0.1 : energy / 20000.0;
  12249. let factor = percentHP + energyBonus;
  12250. return isEarthOrFire ? factor : factor / 10;
  12251. }
  12252.  
  12253. /** Проверяет состояние титана*/
  12254. function checkTitan(id, energy, percentHP) {
  12255. switch (id) {
  12256. case '4020':
  12257. return percentHP > 0.25 || (energy == 1000 && percentHP > 0.05);
  12258. break;
  12259. case '4010':
  12260. return percentHP + energy / 2000.0 > 0.63;
  12261. break;
  12262. case '4000':
  12263. return percentHP > 0.62 || (energy < 1000 && (
  12264. (percentHP > 0.45 && energy >= 400) ||
  12265. (percentHP > 0.3 && energy >= 670)));
  12266. }
  12267. return true;
  12268. }
  12269.  
  12270.  
  12271. /** Начинаем бой */
  12272. function startBattle(teamNum, attackerType, args) {
  12273. return new Promise(function (resolve, reject) {
  12274. args.teamNum = teamNum;
  12275. let startBattleCall = {
  12276. calls: [{
  12277. name: "dungeonStartBattle",
  12278. args,
  12279. ident: "body"
  12280. }]
  12281. }
  12282. send(JSON.stringify(startBattleCall), resultBattle, {
  12283. resolve,
  12284. teamNum,
  12285. attackerType
  12286. });
  12287. });
  12288. }
  12289.  
  12290. /** Возращает результат боя в промис */
  12291. /*function resultBattle(resultBattles, args) {
  12292. if (!!resultBattles && !!resultBattles.results) {
  12293. let battleData = resultBattles.results[0].result.response;
  12294. let battleType = "get_tower";
  12295. if (battleData.type == "dungeon_titan") {
  12296. battleType = "get_titan";
  12297. }
  12298. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];//тест подземка правки
  12299. BattleCalc(battleData, battleType, function (result) {
  12300. result.teamNum = args.teamNum;
  12301. result.attackerType = args.attackerType;
  12302. args.resolve(result);
  12303. });
  12304. } else {
  12305. endDungeon('Потеряна связь с сервером игры!', 'break');
  12306. }
  12307. }*/
  12308. function resultBattle(resultBattles, args) {
  12309. battleData = resultBattles.results[0].result.response;
  12310. battleType = "get_tower";
  12311. if (battleData.type == "dungeon_titan") {
  12312. battleType = "get_titan";
  12313. }
  12314. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  12315. BattleCalc(battleData, battleType, function (result) {
  12316. result.teamNum = args.teamNum;
  12317. result.attackerType = args.attackerType;
  12318. args.resolve(result);
  12319. });
  12320. }
  12321.  
  12322. /** Заканчиваем бой */
  12323.  
  12324. ////
  12325. async function endBattle(battleInfo) {
  12326. if (!!battleInfo) {
  12327. const args = {
  12328. result: battleInfo.result,
  12329. progress: battleInfo.progress,
  12330. }
  12331. if (battleInfo.result.stars < 3) {
  12332. endDungeon('Герой или Титан мог погибнуть в бою!', battleInfo);
  12333. return;
  12334. }
  12335. if (countPredictionCard > 0) {
  12336. args.isRaid = true;
  12337. } else {
  12338. const timer = getTimer(battleInfo.battleTime);
  12339. console.log(timer);
  12340. await countdownTimer(timer, `${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  12341. }
  12342. const calls = [{
  12343. name: "dungeonEndBattle",
  12344. args,
  12345. ident: "body"
  12346. }];
  12347. lastDungeonBattleData = null;
  12348. send(JSON.stringify({ calls }), resultEndBattle);
  12349. } else {
  12350. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  12351. }
  12352. }
  12353. /** Получаем и обрабатываем результаты боя */
  12354. function resultEndBattle(e) {
  12355. if (!!e && !!e.results) {
  12356. let battleResult = e.results[0].result.response;
  12357. if ('error' in battleResult) {
  12358. endDungeon('errorBattleResult', battleResult);
  12359. return;
  12360. }
  12361. let dungeonGetInfo = battleResult.dungeon ?? battleResult;
  12362. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  12363. checkFloor(dungeonGetInfo);
  12364. } else {
  12365. endDungeon('Потеряна связь с сервером игры!', 'break');
  12366. }
  12367. }
  12368.  
  12369. /** Добавить команду титанов в общий список команд */
  12370. function addTeam(team) {
  12371. for (let i in countTeam) {
  12372. if (equalsTeam(countTeam[i].team, team)) {
  12373. countTeam[i].count++;
  12374. return;
  12375. }
  12376. }
  12377. countTeam.push({team: team, count: 1});
  12378. }
  12379.  
  12380. /** Сравнить команды на равенство */
  12381. function equalsTeam(team1, team2) {
  12382. if (team1.length == team2.length) {
  12383. for (let i in team1) {
  12384. if (team1[i] != team2[i]) {
  12385. return false;
  12386. }
  12387. }
  12388. return true;
  12389. }
  12390. return false;
  12391. }
  12392.  
  12393. function saveProgress() {
  12394. let saveProgressCall = {
  12395. calls: [{
  12396. name: "dungeonSaveProgress",
  12397. args: {},
  12398. ident: "body"
  12399. }]
  12400. }
  12401. send(JSON.stringify(saveProgressCall), resultEndBattle);
  12402. }
  12403.  
  12404.  
  12405. /** Выводит статистику прохождения подземелья */
  12406. function showStats() {
  12407. let activity = dungeonActivity - startDungeonActivity;
  12408. let workTime = clone(timeDungeon);
  12409. workTime.all = new Date().getTime() - workTime.all;
  12410. for (let i in workTime) {
  12411. workTime[i] = (workTime[i] / 1000).round(0);
  12412. }
  12413. countTeam.sort(function(a, b) {
  12414. return b.count - a.count;
  12415. });
  12416. console.log(titansStates);
  12417. console.log("Собрано титанита: ", activity);
  12418. console.log("Скорость сбора: " + (3600 * activity / workTime.all).round(0) + " титанита/час");
  12419. console.log("Время раскопок: ");
  12420. for (let i in workTime) {
  12421. let timeNow = workTime[i];
  12422. console.log(i + ": ", (timeNow / 3600).round(0) + " ч. " + (timeNow % 3600 / 60).round(0) + " мин. " + timeNow % 60 + " сек.");
  12423. }
  12424. console.log("Частота использования команд: ");
  12425. for (let i in countTeam) {
  12426. let teams = countTeam[i];
  12427. console.log(teams.team + ": ", teams.count);
  12428. }
  12429. }
  12430.  
  12431. /** Заканчиваем копать подземелье */
  12432. function endDungeon(reason, info) {
  12433. if (!end) {
  12434. end = true;
  12435. console.log(reason, info);
  12436. showStats();
  12437. if (info == 'break') {
  12438. setProgress('Dungeon stoped: Титанит ' + dungeonActivity + '/' + maxDungeonActivity +
  12439. "\r\nПотеряна связь с сервером игры!", false, hideProgress);
  12440. } else {
  12441. setProgress('Dungeon completed: Титанит ' + dungeonActivity + '/' + maxDungeonActivity, false, hideProgress);
  12442. }
  12443. setTimeout(cheats.refreshGame, 1000);
  12444. resolve();
  12445. }
  12446. }
  12447. }
  12448.  
  12449. //дарим подарки участникам других гильдий не выходя из своей гильдии
  12450. function NewYearGift_Clan() {
  12451. console.log('NewYearGift_Clan called...');
  12452. const userID = getInput('userID');
  12453. const AmontID = getInput('AmontID');
  12454. const GiftNum = getInput('GiftNum');
  12455.  
  12456. const data = {
  12457. "calls": [{
  12458. "name": "newYearGiftSend",
  12459. "args": {
  12460. "userId": userID,
  12461. "amount": AmontID,
  12462. "giftNum": GiftNum,
  12463. "users": {
  12464. [userID]: AmontID
  12465. }
  12466. },
  12467. "ident": "body"
  12468. }
  12469. ]
  12470. }
  12471.  
  12472. const dataJson = JSON.stringify(data);
  12473.  
  12474. SendRequest(dataJson, e => {
  12475. let userInfo = e.results[0].result.response;
  12476. console.log(userInfo);
  12477. });
  12478. setProgress(I18N('SEND_GIFT'), true);
  12479. }
  12480. })();
  12481.  
  12482. /**
  12483. * TODO:
  12484. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  12485. * Добивание на арене титанов
  12486. * Закрытие окошек по Esc +-
  12487. * Починить работу скрипта на уровне команды ниже 10 +-
  12488. * Написать номальную синхронизацию
  12489. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  12490. */