HeroWarsHelper

Automation of actions for the game Hero Wars

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

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @name:ru HeroWarsHelper
  5. // @namespace HeroWarsHelper
  6. // @version 2.257
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY
  11. // @license Copyright ZingerY
  12. // @homepage https://zingery.ru/scripts/HeroWarsHelper.user.js
  13. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  14. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  15. // @match https://www.hero-wars.com/*
  16. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  33. ({name, version, author, homepage, lastModified, updateUrl, source}))
  34. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  35. /**
  36. * Information for completing daily quests
  37. *
  38. * Информация для выполнения ежендевных квестов
  39. */
  40. const questsInfo = {};
  41. /**
  42. * Is the game data loaded
  43. *
  44. * Загружены ли данные игры
  45. */
  46. let isLoadGame = false;
  47. /**
  48. * Headers of the last request
  49. *
  50. * Заголовки последнего запроса
  51. */
  52. let lastHeaders = {};
  53. /**
  54. * Information about sent gifts
  55. *
  56. * Информация об отправленных подарках
  57. */
  58. let freebieCheckInfo = null;
  59. /**
  60. * missionTimer
  61. *
  62. * missionTimer
  63. */
  64. let missionBattle = null;
  65. /**
  66. * User data
  67. *
  68. * Данные пользователя
  69. */
  70. let userInfo;
  71. /**
  72. * Original methods for working with AJAX
  73. *
  74. * Оригинальные методы для работы с AJAX
  75. */
  76. const original = {
  77. open: XMLHttpRequest.prototype.open,
  78. send: XMLHttpRequest.prototype.send,
  79. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  80. SendWebSocket: WebSocket.prototype.send,
  81. };
  82. /**
  83. * Decoder for converting byte data to JSON string
  84. *
  85. * Декодер для перобразования байтовых данных в JSON строку
  86. */
  87. const decoder = new TextDecoder("utf-8");
  88. /**
  89. * Stores a history of requests
  90. *
  91. * Хранит историю запросов
  92. */
  93. let requestHistory = {};
  94. /**
  95. * URL for API requests
  96. *
  97. * URL для запросов к API
  98. */
  99. let apiUrl = '';
  100.  
  101. /**
  102. * Connecting to the game code
  103. *
  104. * Подключение к коду игры
  105. */
  106. this.cheats = new hackGame();
  107. /**
  108. * The function of calculating the results of the battle
  109. *
  110. * Функция расчета результатов боя
  111. */
  112. this.BattleCalc = cheats.BattleCalc;
  113. /**
  114. * Sending a request available through the console
  115. *
  116. * Отправка запроса доступная через консоль
  117. */
  118. this.SendRequest = send;
  119. /**
  120. * Simple combat calculation available through the console
  121. *
  122. * Простой расчет боя доступный через консоль
  123. */
  124. this.Calc = function (data) {
  125. const type = getBattleType(data?.type);
  126. return new Promise((resolve, reject) => {
  127. try {
  128. BattleCalc(data, type, resolve);
  129. } catch (e) {
  130. reject(e);
  131. }
  132. })
  133. }
  134. /**
  135. * Short asynchronous request
  136. * Usage example (returns information about a character):
  137. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  138. *
  139. * Короткий асинхронный запрос
  140. * Пример использования (возвращает информацию о персонаже):
  141. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  142. */
  143. this.Send = function (json, pr) {
  144. return new Promise((resolve, reject) => {
  145. try {
  146. send(json, resolve, pr);
  147. } catch (e) {
  148. reject(e);
  149. }
  150. })
  151. }
  152.  
  153. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  154. const i18nLangData = {
  155. /* English translation by BaBa */
  156. en: {
  157. /* Checkboxes */
  158. SKIP_FIGHTS: 'Skip battle',
  159. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  160. ENDLESS_CARDS: 'Infinite cards',
  161. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  162. AUTO_EXPEDITION: 'Auto Expedition',
  163. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  164. CANCEL_FIGHT: 'Cancel battle',
  165. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  166. GIFTS: 'Gifts',
  167. GIFTS_TITLE: 'Collect gifts automatically',
  168. BATTLE_RECALCULATION: 'Battle recalculation',
  169. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  170. QUANTITY_CONTROL: 'Quantity control',
  171. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  172. REPEAT_CAMPAIGN: 'Repeat missions',
  173. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  174. DISABLE_DONAT: 'Disable donation',
  175. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  176. DAILY_QUESTS: 'Quests',
  177. DAILY_QUESTS_TITLE: 'Complete daily quests',
  178. AUTO_QUIZ: 'AutoQuiz',
  179. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  180. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  181. HIDE_SERVERS: 'Collapse servers',
  182. HIDE_SERVERS_TITLE: 'Hide unused servers',
  183. /* Input fields */
  184. HOW_MUCH_TITANITE: 'How much titanite to farm',
  185. COMBAT_SPEED: 'Combat Speed Multiplier',
  186. NUMBER_OF_TEST: 'Number of test fights',
  187. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  188. /* Buttons */
  189. RUN_SCRIPT: 'Run the',
  190. TO_DO_EVERYTHING: 'Do All',
  191. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  192. OUTLAND: 'Outland',
  193. OUTLAND_TITLE: 'Collect Outland',
  194. TITAN_ARENA: 'ToE',
  195. TITAN_ARENA_TITLE: 'Complete the titan arena',
  196. DUNGEON: 'Dungeon',
  197. DUNGEON_TITLE: 'Go through the dungeon',
  198. SEER: 'Seer',
  199. SEER_TITLE: 'Roll the Seer',
  200. TOWER: 'Tower',
  201. TOWER_TITLE: 'Pass the tower',
  202. EXPEDITIONS: 'Expeditions',
  203. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  204. SYNC: 'Sync',
  205. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  206. ARCHDEMON: 'Archdemon',
  207. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  208. ESTER_EGGS: 'Easter eggs',
  209. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  210. REWARDS: 'Rewards',
  211. REWARDS_TITLE: 'Collect all quest rewards',
  212. MAIL: 'Mail',
  213. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  214. MINIONS: 'Minions',
  215. MINIONS_TITLE: 'Attack minions with saved packs',
  216. ADVENTURE: 'Adventure',
  217. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  218. STORM: 'Storm',
  219. STORM_TITLE: 'Passes the Storm along the specified route',
  220. SANCTUARY: 'Sanctuary',
  221. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  222. GUILD_WAR: 'Guild War',
  223. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  224. SECRET_WEALTH: 'Secret Wealth',
  225. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  226. /* Misc */
  227. BOTTOM_URLS:
  228. '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a>',
  229. GIFTS_SENT: 'Gifts sent!',
  230. DO_YOU_WANT: 'Do you really want to do this?',
  231. BTN_RUN: 'Run',
  232. BTN_CANCEL: 'Cancel',
  233. BTN_OK: 'OK',
  234. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  235. BTN_AUTO: 'Auto',
  236. MSG_YOU_APPLIED: 'You applied',
  237. MSG_DAMAGE: 'damage',
  238. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  239. MSG_REPEAT_MISSION: 'Repeat the mission?',
  240. BTN_REPEAT: 'Repeat',
  241. BTN_NO: 'No',
  242. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  243. BTN_OPEN: 'Open',
  244. QUESTION_COPY: 'Question copied to clipboard',
  245. ANSWER_KNOWN: 'The answer is known',
  246. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  247. BEING_RECALC: 'The battle is being recalculated',
  248. THIS_TIME: 'This time',
  249. VICTORY: '<span style="color:green;">VICTORY</span>',
  250. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  251. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  252. OPEN_DOLLS: 'nesting dolls recursively',
  253. SENT_QUESTION: 'Question sent',
  254. SETTINGS: 'Settings',
  255. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  256. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  257. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  258. VALUES: 'Values',
  259. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  260. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  261. TITANIT: 'Titanit',
  262. COMPLETED: 'completed',
  263. FLOOR: 'Floor',
  264. LEVEL: 'Level',
  265. BATTLES: 'battles',
  266. EVENT: 'Event',
  267. NOT_AVAILABLE: 'not available',
  268. NO_HEROES: 'No heroes',
  269. DAMAGE_AMOUNT: 'Damage amount',
  270. NOTHING_TO_COLLECT: 'Nothing to collect',
  271. COLLECTED: 'Collected',
  272. REWARD: 'rewards',
  273. REMAINING_ATTEMPTS: 'Remaining attempts',
  274. BATTLES_CANCELED: 'Battles canceled',
  275. MINION_RAID: 'Minion Raid',
  276. STOPPED: 'Stopped',
  277. REPETITIONS: 'Repetitions',
  278. MISSIONS_PASSED: 'Missions passed',
  279. STOP: 'stop',
  280. TOTAL_OPEN: 'Total open',
  281. OPEN: 'Open',
  282. ROUND_STAT: 'Damage statistics for ',
  283. BATTLE: 'battles',
  284. MINIMUM: 'Minimum',
  285. MAXIMUM: 'Maximum',
  286. AVERAGE: 'Average',
  287. NOT_THIS_TIME: 'Not this time',
  288. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  289. SUCCESS: 'Success',
  290. RECEIVED: 'Received',
  291. LETTERS: 'letters',
  292. PORTALS: 'portals',
  293. ATTEMPTS: 'attempts',
  294. /* Quests */
  295. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  296. QUEST_10002: 'Complete 10 missions',
  297. QUEST_10003: 'Complete 3 heroic missions',
  298. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  299. QUEST_10006: 'Use the exchange of emeralds 1 time',
  300. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  301. QUEST_10016: 'Send gifts to guildmates',
  302. QUEST_10018: 'Use an experience potion',
  303. QUEST_10019: 'Open 1 chest in the Tower',
  304. QUEST_10020: 'Open 3 chests in Outland',
  305. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  306. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  307. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  308. QUEST_10024: 'Level up any artifact once',
  309. QUEST_10025: 'Start Expedition 1',
  310. QUEST_10026: 'Start 4 Expeditions',
  311. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  312. QUEST_10028: 'Level up any titan artifact',
  313. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  314. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  315. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  316. QUEST_10043: 'Start or Join an Adventure',
  317. QUEST_10044: 'Use Summon Pets 1 time',
  318. QUEST_10046: 'Open 3 chests in Adventure',
  319. QUEST_10047: 'Get 150 Guild Activity Points',
  320. NOTHING_TO_DO: 'Nothing to do',
  321. YOU_CAN_COMPLETE: 'You can complete quests',
  322. BTN_DO_IT: 'Do it',
  323. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  324. COMPLETED_QUESTS: 'Completed quests',
  325. /* everything button */
  326. ASSEMBLE_OUTLAND: 'Assemble Outland',
  327. PASS_THE_TOWER: 'Pass the tower',
  328. CHECK_EXPEDITIONS: 'Check Expeditions',
  329. COMPLETE_TOE: 'Complete ToE',
  330. COMPLETE_DUNGEON: 'Complete the dungeon',
  331. COLLECT_MAIL: 'Collect mail',
  332. COLLECT_MISC: 'Collect some bullshit',
  333. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  334. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  335. MAKE_A_SYNC: 'Make a sync',
  336.  
  337. RUN_FUNCTION: 'Run the following functions?',
  338. BTN_GO: 'Go!',
  339. PERFORMED: 'Performed',
  340. DONE: 'Done',
  341. ERRORS_OCCURRES: 'Errors occurred while executing',
  342. COPY_ERROR: 'Copy error information to clipboard',
  343. BTN_YES: 'Yes',
  344. ALL_TASK_COMPLETED: 'All tasks completed',
  345.  
  346. UNKNOWN: 'unknown',
  347. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  348. START_ADVENTURE: 'Start your adventure along this path!',
  349. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  350. BTN_CANCELED: 'Canceled',
  351. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  352. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  353. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  354. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  355. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  356. YES_CONTINUE: 'Yes, continue!',
  357. NOT_ENOUGH_AP: 'Not enough action points',
  358. ATTEMPTS_ARE_OVER: 'The attempts are over',
  359. MOVES: 'Moves',
  360. BUFF_GET_ERROR: 'Buff getting error',
  361. BATTLE_END_ERROR: 'Battle end error',
  362. AUTOBOT: 'Autobot',
  363. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  364. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  365. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  366. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  367. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  368. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  369. FIND_COEFF: 'Find the coefficient greater than',
  370. BTN_PASS: 'PASS',
  371. BRAWLS: 'Brawls',
  372. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  373. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  374. LOSSES: 'Losses',
  375. WINS: 'Wins',
  376. FIGHTS: 'Fights',
  377. STAGE: 'Stage',
  378. DONT_HAVE_LIVES: "You don't have lives",
  379. LIVES: 'Lives',
  380. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  381. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  382. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  383. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  384. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  385. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  386. DAILY_BONUS: 'Daily bonus',
  387. DO_DAILY_QUESTS: 'Do daily quests',
  388. ACTIONS: 'Actions',
  389. ACTIONS_TITLE: 'Dialog box with various actions',
  390. OTHERS: 'Others',
  391. OTHERS_TITLE: 'Others',
  392. CHOOSE_ACTION: 'Choose an action',
  393. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  394. STAMINA: 'Energy',
  395. BOXES_OVER: 'The boxes are over',
  396. NO_BOXES: 'No boxes',
  397. NO_MORE_ACTIVITY: 'No more activity for items today',
  398. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  399. GET_ACTIVITY: 'Get Activity',
  400. NOT_ENOUGH_ITEMS: 'Not enough items',
  401. ACTIVITY_RECEIVED: 'Activity received',
  402. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  403. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  404. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need 540 you have {currentStarMoney}',
  405. CHESTS_NOT_AVAILABLE: 'Chests not available',
  406. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  407. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  408. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  409. SOMETHING_WENT_WRONG: 'Something went wrong',
  410. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  411. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  412. GET_ENERGY: 'Get Energy',
  413. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  414. ITEM_EXCHANGE: 'Item Exchange',
  415. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  416. BUY_SOULS: 'Buy souls',
  417. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  418. BUY_OUTLAND: 'Buy Outland',
  419. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  420. RAID: 'Raid',
  421. AUTO_RAID_ADVENTURE: 'Raid adventure',
  422. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  423. CLAN_STAT: 'Clan statistics',
  424. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  425. BTN_AUTO_F5: 'Auto (F5)',
  426. BOSS_DAMAGE: 'Boss Damage: ',
  427. NOTHING_BUY: 'Nothing to buy',
  428. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  429. BUY_FOR_GOLD: 'Buy for gold',
  430. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  431. REWARDS_AND_MAIL: 'Rewars and Mail',
  432. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  433. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  434. TIMER_ALREADY: 'Timer already started {time}',
  435. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  436. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  437. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  438. EPIC_BRAWL: 'Cosmic Battle',
  439. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  440. RELOAD_GAME: 'Reload game',
  441. TIMER: 'Timer:',
  442. SHOW_ERRORS: 'Show errors',
  443. SHOW_ERRORS_TITLE: 'Show server request errors',
  444. ERROR_MSG: 'Error: {name}<br>{description}',
  445. EVENT_AUTO_BOSS:
  446. '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?',
  447. BEST_SLOW: 'Best (slower)',
  448. FIRST_FAST: 'First (faster)',
  449. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  450. ERROR_F12: 'Error, details in the console (F12)',
  451. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  452. BEST_PACK: 'Best pack:',
  453. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  454. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  455. BOSS_VICTORY_IMPOSSIBLE:
  456. '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?',
  457. BOSS_HAS_BEEN_DEF_TEXT:
  458. 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  459. MAP: 'Map: ',
  460. PLAYER_POS: 'Player positions:',
  461. NY_GIFTS: 'Gifts',
  462. NY_GIFTS_TITLE: "Open all New Year's gifts",
  463. NY_NO_GIFTS: 'No gifts not received',
  464. NY_GIFTS_COLLECTED: '{count} gifts collected',
  465. CHANGE_MAP: 'Island map',
  466. CHANGE_MAP_TITLE: 'Change island map',
  467. SELECT_ISLAND_MAP: 'Select an island map:',
  468. MAP_NUM: 'Map {num}',
  469. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  470. SHOPS: 'Shops',
  471. SHOPS_DEFAULT: 'Default',
  472. SHOPS_DEFAULT_TITLE: 'Default stores',
  473. SHOPS_LIST: 'Shops {number}',
  474. SHOPS_LIST_TITLE: 'List of shops {number}',
  475. SHOPS_WARNING:
  476. '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>',
  477. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  478. FAST_SEASON: 'Fast season',
  479. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  480. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  481. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  482. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  483. IMPROVED_LEVELS: 'Improved levels: {count}',
  484. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  485. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  486. SKINS_UPGRADE: 'Skins Upgrade',
  487. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  488. HINT: '<br>Hint: ',
  489. PICTURE: '<br>Picture: ',
  490. ANSWER: '<br>Answer: ',
  491. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  492. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  493. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  494. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  495. },
  496. ru: {
  497. /* Чекбоксы */
  498. SKIP_FIGHTS: 'Пропуск боев',
  499. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  500. ENDLESS_CARDS: 'Бесконечные карты',
  501. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  502. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  503. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  504. CANCEL_FIGHT: 'Отмена боя',
  505. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  506. GIFTS: 'Подарки',
  507. GIFTS_TITLE: 'Собирать подарки автоматически',
  508. BATTLE_RECALCULATION: 'Прерасчет боя',
  509. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  510. QUANTITY_CONTROL: 'Контроль кол-ва',
  511. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  512. REPEAT_CAMPAIGN: 'Повтор в кампании',
  513. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  514. DISABLE_DONAT: 'Отключить донат',
  515. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  516. DAILY_QUESTS: 'Квесты',
  517. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  518. AUTO_QUIZ: 'АвтоВикторина',
  519. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  520. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  521. HIDE_SERVERS: 'Свернуть сервера',
  522. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  523. /* Поля ввода */
  524. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  525. COMBAT_SPEED: 'Множитель ускорения боя',
  526. NUMBER_OF_TEST: 'Количество тестовых боев',
  527. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  528. /* Кнопки */
  529. RUN_SCRIPT: 'Запустить скрипт',
  530. TO_DO_EVERYTHING: 'Сделать все',
  531. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  532. OUTLAND: 'Запределье',
  533. OUTLAND_TITLE: 'Собрать Запределье',
  534. TITAN_ARENA: 'Турнир Стихий',
  535. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  536. DUNGEON: 'Подземелье',
  537. DUNGEON_TITLE: 'Автопрохождение подземелья',
  538. SEER: 'Провидец',
  539. SEER_TITLE: 'Покрутить Провидца',
  540. TOWER: 'Башня',
  541. TOWER_TITLE: 'Автопрохождение башни',
  542. EXPEDITIONS: 'Экспедиции',
  543. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  544. SYNC: 'Синхронизация',
  545. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  546. ARCHDEMON: 'Архидемон',
  547. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  548. ESTER_EGGS: 'Пасхалки',
  549. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  550. REWARDS: 'Награды',
  551. REWARDS_TITLE: 'Собрать все награды за задания',
  552. MAIL: 'Почта',
  553. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  554. MINIONS: 'Прислужники',
  555. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  556. ADVENTURE: 'Приключение',
  557. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  558. STORM: 'Буря',
  559. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  560. SANCTUARY: 'Святилище',
  561. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  562. GUILD_WAR: 'Война гильдий',
  563. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  564. SECRET_WEALTH: 'Тайное богатство',
  565. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  566. /* Разное */
  567. BOTTOM_URLS:
  568. '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  569. GIFTS_SENT: 'Подарки отправлены!',
  570. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  571. BTN_RUN: 'Запускай',
  572. BTN_CANCEL: 'Отмена',
  573. BTN_OK: 'Ок',
  574. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  575. BTN_AUTO: 'Авто',
  576. MSG_YOU_APPLIED: 'Вы нанесли',
  577. MSG_DAMAGE: 'урона',
  578. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  579. MSG_REPEAT_MISSION: 'Повторить миссию?',
  580. BTN_REPEAT: 'Повторить',
  581. BTN_NO: 'Нет',
  582. MSG_SPECIFY_QUANT: 'Указать количество:',
  583. BTN_OPEN: 'Открыть',
  584. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  585. ANSWER_KNOWN: 'Ответ известен',
  586. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  587. BEING_RECALC: 'Идет прерасчет боя',
  588. THIS_TIME: 'На этот раз',
  589. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  590. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  591. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  592. OPEN_DOLLS: 'матрешек рекурсивно',
  593. SENT_QUESTION: 'Вопрос отправлен',
  594. SETTINGS: 'Настройки',
  595. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  596. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  597. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  598. VALUES: 'Значения',
  599. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  600. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  601. TITANIT: 'Титанит',
  602. COMPLETED: 'завершено',
  603. FLOOR: 'Этаж',
  604. LEVEL: 'Уровень',
  605. BATTLES: 'бои',
  606. EVENT: 'Эвент',
  607. NOT_AVAILABLE: 'недоступен',
  608. NO_HEROES: 'Нет героев',
  609. DAMAGE_AMOUNT: 'Количество урона',
  610. NOTHING_TO_COLLECT: 'Нечего собирать',
  611. COLLECTED: 'Собрано',
  612. REWARD: 'наград',
  613. REMAINING_ATTEMPTS: 'Осталось попыток',
  614. BATTLES_CANCELED: 'Битв отменено',
  615. MINION_RAID: 'Рейд прислужников',
  616. STOPPED: 'Остановлено',
  617. REPETITIONS: 'Повторений',
  618. MISSIONS_PASSED: 'Миссий пройдено',
  619. STOP: 'остановить',
  620. TOTAL_OPEN: 'Всего открыто',
  621. OPEN: 'Открыто',
  622. ROUND_STAT: 'Статистика урона за',
  623. BATTLE: 'боев',
  624. MINIMUM: 'Минимальный',
  625. MAXIMUM: 'Максимальный',
  626. AVERAGE: 'Средний',
  627. NOT_THIS_TIME: 'Не в этот раз',
  628. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  629. SUCCESS: 'Успех',
  630. RECEIVED: 'Получено',
  631. LETTERS: 'писем',
  632. PORTALS: 'порталов',
  633. ATTEMPTS: 'попыток',
  634. QUEST_10001: 'Улучши умения героев 3 раза',
  635. QUEST_10002: 'Пройди 10 миссий',
  636. QUEST_10003: 'Пройди 3 героические миссии',
  637. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  638. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  639. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  640. QUEST_10016: 'Отправь подарки согильдийцам',
  641. QUEST_10018: 'Используй зелье опыта',
  642. QUEST_10019: 'Открой 1 сундук в Башне',
  643. QUEST_10020: 'Открой 3 сундука в Запределье',
  644. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  645. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  646. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  647. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  648. QUEST_10025: 'Начни 1 Экспедицию',
  649. QUEST_10026: 'Начни 4 Экспедиции',
  650. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  651. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  652. QUEST_10029: 'Открой сферу артефактов титанов',
  653. QUEST_10030: 'Улучши облик любого героя 1 раз',
  654. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  655. QUEST_10043: 'Начни или присоеденись к Приключению',
  656. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  657. QUEST_10046: 'Открой 3 сундука в Приключениях',
  658. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  659. NOTHING_TO_DO: 'Нечего выполнять',
  660. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  661. BTN_DO_IT: 'Выполняй',
  662. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  663. COMPLETED_QUESTS: 'Выполнено квестов',
  664. /* everything button */
  665. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  666. PASS_THE_TOWER: 'Пройти башню',
  667. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  668. COMPLETE_TOE: 'Пройти Турнир Стихий',
  669. COMPLETE_DUNGEON: 'Пройти подземелье',
  670. COLLECT_MAIL: 'Собрать почту',
  671. COLLECT_MISC: 'Собрать всякую херню',
  672. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  673. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  674. MAKE_A_SYNC: 'Сделать синхронизацию',
  675.  
  676. RUN_FUNCTION: 'Выполнить следующие функции?',
  677. BTN_GO: 'Погнали!',
  678. PERFORMED: 'Выполняется',
  679. DONE: 'Выполнено',
  680. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  681. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  682. BTN_YES: 'Да',
  683. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  684.  
  685. UNKNOWN: 'Неизвестно',
  686. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  687. START_ADVENTURE: 'Начать приключение по этому пути!',
  688. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  689. BTN_CANCELED: 'Отменено',
  690. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  691. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  692. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  693. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  694. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  695. YES_CONTINUE: 'Да, продолжай!',
  696. NOT_ENOUGH_AP: 'Попыток не достаточно',
  697. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  698. MOVES: 'Ходы',
  699. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  700. BATTLE_END_ERROR: 'Ошибка завершения боя',
  701. AUTOBOT: 'АвтоБой',
  702. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  703. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  704. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  705. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  706. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  707. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  708. FIND_COEFF: 'Поиск коэффициента больше чем',
  709. BTN_PASS: 'ПРОПУСК',
  710. BRAWLS: 'Потасовки',
  711. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  712. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  713. LOSSES: 'Поражений',
  714. WINS: 'Побед',
  715. FIGHTS: 'Боев',
  716. STAGE: 'Стадия',
  717. DONT_HAVE_LIVES: 'У Вас нет жизней',
  718. LIVES: 'Жизни',
  719. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  720. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  721. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  722. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  723. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  724. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  725. DAILY_BONUS: 'Ежедневная награда',
  726. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  727. ACTIONS: 'Действия',
  728. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  729. OTHERS: 'Разное',
  730. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  731. CHOOSE_ACTION: 'Выберите действие',
  732. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  733. STAMINA: 'Энергия',
  734. BOXES_OVER: 'Ящики закончились',
  735. NO_BOXES: 'Нет ящиков',
  736. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  737. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  738. GET_ACTIVITY: 'Получить активность',
  739. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  740. ACTIVITY_RECEIVED: 'Получено активности',
  741. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  742. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  743. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно 540 у Вас {currentStarMoney}',
  744. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  745. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  746. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  747. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  748. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  749. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  750. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  751. GET_ENERGY: 'Получить энергию',
  752. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  753. ITEM_EXCHANGE: 'Обмен предметов',
  754. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  755. BUY_SOULS: 'Купить души',
  756. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  757. BUY_OUTLAND: 'Купить Запределье',
  758. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  759. RAID: 'Рейд',
  760. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  761. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  762. CLAN_STAT: 'Клановая статистика',
  763. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  764. BTN_AUTO_F5: 'Авто (F5)',
  765. BOSS_DAMAGE: 'Урон по боссу: ',
  766. NOTHING_BUY: 'Нечего покупать',
  767. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  768. BUY_FOR_GOLD: 'Скупить за золото',
  769. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  770. REWARDS_AND_MAIL: 'Награды и почта',
  771. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  772. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  773. TIMER_ALREADY: 'Таймер уже запущен {time}',
  774. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  775. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  776. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  777. EPIC_BRAWL: 'Вселенская битва',
  778. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  779. RELOAD_GAME: 'Перезагрузить игру',
  780. TIMER: 'Таймер:',
  781. SHOW_ERRORS: 'Отображать ошибки',
  782. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  783. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  784. EVENT_AUTO_BOSS:
  785. 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  786. BEST_SLOW: 'Лучший (медленее)',
  787. FIRST_FAST: 'Первый (быстрее)',
  788. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  789. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  790. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  791. BEST_PACK: 'Наилучший пак: ',
  792. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  793. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  794. BOSS_VICTORY_IMPOSSIBLE:
  795. 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  796. BOSS_HAS_BEEN_DEF_TEXT:
  797. 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  798. MAP: 'Карта: ',
  799. PLAYER_POS: 'Позиции игроков:',
  800. NY_GIFTS: 'Подарки',
  801. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  802. NY_NO_GIFTS: 'Нет не полученных подарков',
  803. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  804. CHANGE_MAP: 'Карта острова',
  805. CHANGE_MAP_TITLE: 'Сменить карту острова',
  806. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  807. MAP_NUM: 'Карта {num}',
  808. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  809. SHOPS: 'Магазины',
  810. SHOPS_DEFAULT: 'Стандартные',
  811. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  812. SHOPS_LIST: 'Магазины {number}',
  813. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  814. SHOPS_WARNING:
  815. 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  816. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  817. FAST_SEASON: 'Быстрый сезон',
  818. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  819. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  820. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  821. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  822. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  823. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  824. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  825. SKINS_UPGRADE: 'Улучшение обликов',
  826. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  827. HINT: '<br>Подсказка: ',
  828. PICTURE: '<br>На картинке: ',
  829. ANSWER: '<br>Ответ: ',
  830. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  831. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  832. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  833. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  834. },
  835. };
  836.  
  837. function getLang() {
  838. let lang = '';
  839. if (typeof NXFlashVars !== 'undefined') {
  840. lang = NXFlashVars.interface_lang
  841. }
  842. if (!lang) {
  843. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  844. }
  845. if (lang == 'ru') {
  846. return lang;
  847. }
  848. return 'en';
  849. }
  850.  
  851. this.I18N = function (constant, replace) {
  852. const selectLang = getLang();
  853. if (constant && constant in i18nLangData[selectLang]) {
  854. const result = i18nLangData[selectLang][constant];
  855. if (replace) {
  856. return result.sprintf(replace);
  857. }
  858. return result;
  859. }
  860. return `% ${constant} %`;
  861. };
  862.  
  863. String.prototype.sprintf = String.prototype.sprintf ||
  864. function () {
  865. "use strict";
  866. var str = this.toString();
  867. if (arguments.length) {
  868. var t = typeof arguments[0];
  869. var key;
  870. var args = ("string" === t || "number" === t) ?
  871. Array.prototype.slice.call(arguments)
  872. : arguments[0];
  873.  
  874. for (key in args) {
  875. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  876. }
  877. }
  878.  
  879. return str;
  880. };
  881.  
  882. /**
  883. * Checkboxes
  884. *
  885. * Чекбоксы
  886. */
  887. const checkboxes = {
  888. passBattle: {
  889. label: I18N('SKIP_FIGHTS'),
  890. cbox: null,
  891. title: I18N('SKIP_FIGHTS_TITLE'),
  892. default: false
  893. },
  894. sendExpedition: {
  895. label: I18N('AUTO_EXPEDITION'),
  896. cbox: null,
  897. title: I18N('AUTO_EXPEDITION_TITLE'),
  898. default: false
  899. },
  900. cancelBattle: {
  901. label: I18N('CANCEL_FIGHT'),
  902. cbox: null,
  903. title: I18N('CANCEL_FIGHT_TITLE'),
  904. default: false,
  905. },
  906. preCalcBattle: {
  907. label: I18N('BATTLE_RECALCULATION'),
  908. cbox: null,
  909. title: I18N('BATTLE_RECALCULATION_TITLE'),
  910. default: false
  911. },
  912. countControl: {
  913. label: I18N('QUANTITY_CONTROL'),
  914. cbox: null,
  915. title: I18N('QUANTITY_CONTROL_TITLE'),
  916. default: true
  917. },
  918. repeatMission: {
  919. label: I18N('REPEAT_CAMPAIGN'),
  920. cbox: null,
  921. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  922. default: false
  923. },
  924. noOfferDonat: {
  925. label: I18N('DISABLE_DONAT'),
  926. cbox: null,
  927. title: I18N('DISABLE_DONAT_TITLE'),
  928. /**
  929. * A crutch to get the field before getting the character id
  930. *
  931. * Костыль чтоб получать поле до получения id персонажа
  932. */
  933. default: (() => {
  934. $result = false;
  935. try {
  936. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  937. } catch(e) {
  938. $result = false;
  939. }
  940. return $result || false;
  941. })(),
  942. },
  943. dailyQuests: {
  944. label: I18N('DAILY_QUESTS'),
  945. cbox: null,
  946. title: I18N('DAILY_QUESTS_TITLE'),
  947. default: false
  948. },
  949. // Потасовки
  950. autoBrawls: {
  951. label: I18N('BRAWLS'),
  952. cbox: null,
  953. title: I18N('BRAWLS_TITLE'),
  954. default: (() => {
  955. $result = false;
  956. try {
  957. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls'])
  958. } catch (e) {
  959. $result = false;
  960. }
  961. return $result || false;
  962. })(),
  963. hide: false,
  964. },
  965. getAnswer: {
  966. label: I18N('AUTO_QUIZ'),
  967. cbox: null,
  968. title: I18N('AUTO_QUIZ_TITLE'),
  969. default: false,
  970. hide: true,
  971. },
  972. showErrors: {
  973. label: I18N('SHOW_ERRORS'),
  974. cbox: null,
  975. title: I18N('SHOW_ERRORS_TITLE'),
  976. default: true
  977. },
  978. buyForGold: {
  979. label: I18N('BUY_FOR_GOLD'),
  980. cbox: null,
  981. title: I18N('BUY_FOR_GOLD_TITLE'),
  982. default: false
  983. },
  984. hideServers: {
  985. label: I18N('HIDE_SERVERS'),
  986. cbox: null,
  987. title: I18N('HIDE_SERVERS_TITLE'),
  988. default: false
  989. },
  990. fastSeason: {
  991. label: I18N('FAST_SEASON'),
  992. cbox: null,
  993. title: I18N('FAST_SEASON_TITLE'),
  994. default: false
  995. },
  996. };
  997. /**
  998. * Get checkbox state
  999. *
  1000. * Получить состояние чекбокса
  1001. */
  1002. function isChecked(checkBox) {
  1003. if (!(checkBox in checkboxes)) {
  1004. return false;
  1005. }
  1006. return checkboxes[checkBox].cbox?.checked;
  1007. }
  1008. /**
  1009. * Input fields
  1010. *
  1011. * Поля ввода
  1012. */
  1013. const inputs = {
  1014. countTitanit: {
  1015. input: null,
  1016. title: I18N('HOW_MUCH_TITANITE'),
  1017. default: 150,
  1018. },
  1019. speedBattle: {
  1020. input: null,
  1021. title: I18N('COMBAT_SPEED'),
  1022. default: 5,
  1023. },
  1024. countTestBattle: {
  1025. input: null,
  1026. title: I18N('NUMBER_OF_TEST'),
  1027. default: 10,
  1028. },
  1029. countAutoBattle: {
  1030. input: null,
  1031. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1032. default: 10,
  1033. },
  1034. FPS: {
  1035. input: null,
  1036. title: 'FPS',
  1037. default: 60,
  1038. }
  1039. }
  1040. /**
  1041. * Checks the checkbox
  1042. *
  1043. * Поплучить данные поля ввода
  1044. */
  1045. function getInput(inputName) {
  1046. return inputs[inputName]?.input?.value;
  1047. }
  1048.  
  1049. /**
  1050. * Control FPS
  1051. *
  1052. * Контроль FPS
  1053. */
  1054. let nextAnimationFrame = Date.now();
  1055. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1056. this.requestAnimationFrame = async function (e) {
  1057. const FPS = Number(getInput('FPS')) || -1;
  1058. const now = Date.now();
  1059. const delay = nextAnimationFrame - now;
  1060. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1061. if (delay > 0) {
  1062. await new Promise((e) => setTimeout(e, delay));
  1063. }
  1064. oldRequestAnimationFrame(e);
  1065. };
  1066. /**
  1067. * Button List
  1068. *
  1069. * Список кнопочек
  1070. */
  1071. const buttons = {
  1072. getOutland: {
  1073. name: I18N('TO_DO_EVERYTHING'),
  1074. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1075. func: testDoYourBest,
  1076. },
  1077. doActions: {
  1078. name: I18N('ACTIONS'),
  1079. title: I18N('ACTIONS_TITLE'),
  1080. func: async function () {
  1081. const popupButtons = [
  1082. {
  1083. msg: I18N('OUTLAND'),
  1084. result: function () {
  1085. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1086. },
  1087. title: I18N('OUTLAND_TITLE'),
  1088. },
  1089. {
  1090. msg: I18N('TOWER'),
  1091. result: function () {
  1092. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1093. },
  1094. title: I18N('TOWER_TITLE'),
  1095. },
  1096. {
  1097. msg: I18N('EXPEDITIONS'),
  1098. result: function () {
  1099. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1100. },
  1101. title: I18N('EXPEDITIONS_TITLE'),
  1102. },
  1103. {
  1104. msg: I18N('MINIONS'),
  1105. result: function () {
  1106. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1107. },
  1108. title: I18N('MINIONS_TITLE'),
  1109. },
  1110. {
  1111. msg: I18N('ESTER_EGGS'),
  1112. result: function () {
  1113. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1114. },
  1115. title: I18N('ESTER_EGGS_TITLE'),
  1116. },
  1117. {
  1118. msg: I18N('STORM'),
  1119. result: function () {
  1120. testAdventure('solo');
  1121. },
  1122. title: I18N('STORM_TITLE'),
  1123. },
  1124. {
  1125. msg: I18N('REWARDS'),
  1126. result: function () {
  1127. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1128. },
  1129. title: I18N('REWARDS_TITLE'),
  1130. },
  1131. {
  1132. msg: I18N('MAIL'),
  1133. result: function () {
  1134. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1135. },
  1136. title: I18N('MAIL_TITLE'),
  1137. },
  1138. {
  1139. msg: I18N('SEER'),
  1140. result: function () {
  1141. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1142. },
  1143. title: I18N('SEER_TITLE'),
  1144. },
  1145. /*
  1146. {
  1147. msg: I18N('NY_GIFTS'),
  1148. result: getGiftNewYear,
  1149. title: I18N('NY_GIFTS_TITLE'),
  1150. },
  1151. */
  1152. ];
  1153. popupButtons.push({ result: false, isClose: true })
  1154. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1155. if (typeof answer === 'function') {
  1156. answer();
  1157. }
  1158. }
  1159. },
  1160. doOthers: {
  1161. name: I18N('OTHERS'),
  1162. title: I18N('OTHERS_TITLE'),
  1163. func: async function () {
  1164. const popupButtons = [
  1165. {
  1166. msg: I18N('GET_ENERGY'),
  1167. result: farmStamina,
  1168. title: I18N('GET_ENERGY_TITLE'),
  1169. },
  1170. {
  1171. msg: I18N('ITEM_EXCHANGE'),
  1172. result: fillActive,
  1173. title: I18N('ITEM_EXCHANGE_TITLE'),
  1174. },
  1175. {
  1176. msg: I18N('BUY_SOULS'),
  1177. result: function () {
  1178. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1179. },
  1180. title: I18N('BUY_SOULS_TITLE'),
  1181. },
  1182. {
  1183. msg: I18N('BUY_FOR_GOLD'),
  1184. result: function () {
  1185. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1186. },
  1187. title: I18N('BUY_FOR_GOLD_TITLE'),
  1188. },
  1189. {
  1190. msg: I18N('BUY_OUTLAND'),
  1191. result: function () {
  1192. confShow(I18N('BUY_OUTLAND_TITLE') + '?', bossOpenChestPay);
  1193. },
  1194. title: I18N('BUY_OUTLAND_TITLE'),
  1195. },
  1196. {
  1197. msg: I18N('AUTO_RAID_ADVENTURE'),
  1198. result: autoRaidAdventure,
  1199. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1200. },
  1201. {
  1202. msg: I18N('CLAN_STAT'),
  1203. result: clanStatistic,
  1204. title: I18N('CLAN_STAT_TITLE'),
  1205. },
  1206. {
  1207. msg: I18N('EPIC_BRAWL'),
  1208. result: async function () {
  1209. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1210. const brawl = new epicBrawl;
  1211. brawl.start();
  1212. });
  1213. },
  1214. title: I18N('EPIC_BRAWL_TITLE'),
  1215. },
  1216. {
  1217. msg: I18N('ARTIFACTS_UPGRADE'),
  1218. result: updateArtifacts,
  1219. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1220. },
  1221. {
  1222. msg: I18N('SKINS_UPGRADE'),
  1223. result: updateSkins,
  1224. title: I18N('SKINS_UPGRADE_TITLE'),
  1225. },
  1226. {
  1227. msg: I18N('CHANGE_MAP'),
  1228. result: async function () {
  1229. const maps = [];
  1230. for (let num = 1; num < 5; num++) {
  1231. maps.push({
  1232. msg: I18N('MAP_NUM', { num }),
  1233. result: num,
  1234. });
  1235. }
  1236.  
  1237. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1238. ...maps,
  1239. { result: false, isClose: true },
  1240. ]);
  1241. if (result) {
  1242. cheats.changeIslandMap(result);
  1243. }
  1244. },
  1245. title: I18N('CHANGE_MAP_TITLE'),
  1246. },
  1247. ];
  1248. popupButtons.push({ result: false, isClose: true })
  1249. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1250. if (typeof answer === 'function') {
  1251. answer();
  1252. }
  1253. }
  1254. },
  1255. testTitanArena: {
  1256. name: I18N('TITAN_ARENA'),
  1257. title: I18N('TITAN_ARENA_TITLE'),
  1258. func: function () {
  1259. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1260. },
  1261. },
  1262. testDungeon: {
  1263. name: I18N('DUNGEON'),
  1264. title: I18N('DUNGEON_TITLE'),
  1265. func: function () {
  1266. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1267. },
  1268. },
  1269. // Архидемон
  1270. bossRatingEvent: {
  1271. name: I18N('ARCHDEMON'),
  1272. title: I18N('ARCHDEMON_TITLE'),
  1273. func: function () {
  1274. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1275. },
  1276. hide: true,
  1277. },
  1278. /*
  1279. // Горнило душ
  1280. bossRatingEvent: {
  1281. name: I18N('ARCHDEMON'),
  1282. title: I18N('ARCHDEMON_TITLE'),
  1283. func: function () {
  1284. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEventSouls);
  1285. },
  1286. },
  1287. */
  1288. rewardsAndMailFarm: {
  1289. name: I18N('REWARDS_AND_MAIL'),
  1290. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1291. func: function () {
  1292. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1293. },
  1294. },
  1295. testAdventure: {
  1296. name: I18N('ADVENTURE'),
  1297. title: I18N('ADVENTURE_TITLE'),
  1298. func: () => {
  1299. testAdventure();
  1300. },
  1301. },
  1302. goToSanctuary: {
  1303. name: I18N('SANCTUARY'),
  1304. title: I18N('SANCTUARY_TITLE'),
  1305. func: cheats.goSanctuary,
  1306. },
  1307. goToClanWar: {
  1308. name: I18N('GUILD_WAR'),
  1309. title: I18N('GUILD_WAR_TITLE'),
  1310. func: cheats.goClanWar,
  1311. },
  1312. dailyQuests: {
  1313. name: I18N('DAILY_QUESTS'),
  1314. title: I18N('DAILY_QUESTS_TITLE'),
  1315. func: async function () {
  1316. const quests = new dailyQuests(() => { }, () => { });
  1317. await quests.autoInit();
  1318. quests.start();
  1319. },
  1320. },
  1321. newDay: {
  1322. name: I18N('SYNC'),
  1323. title: I18N('SYNC_TITLE'),
  1324. func: function () {
  1325. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1326. },
  1327. },
  1328. }
  1329. /**
  1330. * Display buttons
  1331. *
  1332. * Вывести кнопочки
  1333. */
  1334. function addControlButtons() {
  1335. for (let name in buttons) {
  1336. button = buttons[name];
  1337. if (button.hide) {
  1338. continue;
  1339. }
  1340. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1341. }
  1342. }
  1343. /**
  1344. * Adds links
  1345. *
  1346. * Добавляет ссылки
  1347. */
  1348. function addBottomUrls() {
  1349. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1350. }
  1351. /**
  1352. * Stop repetition of the mission
  1353. *
  1354. * Остановить повтор миссии
  1355. */
  1356. let isStopSendMission = false;
  1357. /**
  1358. * There is a repetition of the mission
  1359. *
  1360. * Идет повтор миссии
  1361. */
  1362. let isSendsMission = false;
  1363. /**
  1364. * Data on the past mission
  1365. *
  1366. * Данные о прошедшей мисии
  1367. */
  1368. let lastMissionStart = {}
  1369. /**
  1370. * Start time of the last battle in the company
  1371. *
  1372. * Время начала последнего боя в кампании
  1373. */
  1374. let lastMissionBattleStart = 0;
  1375. /**
  1376. * Data on the past attack on the boss
  1377. *
  1378. * Данные о прошедшей атаке на босса
  1379. */
  1380. let lastBossBattle = {}
  1381. /**
  1382. * Data for calculating the last battle with the boss
  1383. *
  1384. * Данные для расчете последнего боя с боссом
  1385. */
  1386. let lastBossBattleInfo = null;
  1387. /**
  1388. * Ability to cancel the battle in Asgard
  1389. *
  1390. * Возможность отменить бой в Астгарде
  1391. */
  1392. let isCancalBossBattle = true;
  1393. /**
  1394. * Information about the last battle
  1395. *
  1396. * Данные о прошедшей битве
  1397. */
  1398. let lastBattleArg = {}
  1399. let lastBossBattleStart = null;
  1400. this.addBattleTimer = 4;
  1401. this.invasionTimer = 2500;
  1402. /**
  1403. * The name of the function of the beginning of the battle
  1404. *
  1405. * Имя функции начала боя
  1406. */
  1407. let nameFuncStartBattle = '';
  1408. /**
  1409. * The name of the function of the end of the battle
  1410. *
  1411. * Имя функции конца боя
  1412. */
  1413. let nameFuncEndBattle = '';
  1414. /**
  1415. * Data for calculating the last battle
  1416. *
  1417. * Данные для расчета последнего боя
  1418. */
  1419. let lastBattleInfo = null;
  1420. /**
  1421. * The ability to cancel the battle
  1422. *
  1423. * Возможность отменить бой
  1424. */
  1425. let isCancalBattle = true;
  1426.  
  1427. /**
  1428. * Certificator of the last open nesting doll
  1429. *
  1430. * Идетификатор последней открытой матрешки
  1431. */
  1432. let lastRussianDollId = null;
  1433. /**
  1434. * Cancel the training guide
  1435. *
  1436. * Отменить обучающее руководство
  1437. */
  1438. this.isCanceledTutorial = false;
  1439.  
  1440. /**
  1441. * Data from the last question of the quiz
  1442. *
  1443. * Данные последнего вопроса викторины
  1444. */
  1445. let lastQuestion = null;
  1446. /**
  1447. * Answer to the last question of the quiz
  1448. *
  1449. * Ответ на последний вопрос викторины
  1450. */
  1451. let lastAnswer = null;
  1452. /**
  1453. * Flag for opening keys or titan artifact spheres
  1454. *
  1455. * Флаг открытия ключей или сфер артефактов титанов
  1456. */
  1457. let artifactChestOpen = false;
  1458. /**
  1459. * The name of the function to open keys or orbs of titan artifacts
  1460. *
  1461. * Имя функции открытия ключей или сфер артефактов титанов
  1462. */
  1463. let artifactChestOpenCallName = '';
  1464. let correctShowOpenArtifact = 0;
  1465. /**
  1466. * Data for the last battle in the dungeon
  1467. * (Fix endless cards)
  1468. *
  1469. * Данные для последнего боя в подземке
  1470. * (Исправление бесконечных карт)
  1471. */
  1472. let lastDungeonBattleData = null;
  1473. /**
  1474. * Start time of the last battle in the dungeon
  1475. *
  1476. * Время начала последнего боя в подземелье
  1477. */
  1478. let lastDungeonBattleStart = 0;
  1479. /**
  1480. * Subscription end time
  1481. *
  1482. * Время окончания подписки
  1483. */
  1484. let subEndTime = 0;
  1485. /**
  1486. * Number of prediction cards
  1487. *
  1488. * Количество карт предсказаний
  1489. */
  1490. let countPredictionCard = 0;
  1491.  
  1492. /**
  1493. * Brawl pack
  1494. *
  1495. * Пачка для потасовок
  1496. */
  1497. let brawlsPack = null;
  1498. /**
  1499. * Autobrawl started
  1500. *
  1501. * Автопотасовка запущена
  1502. */
  1503. let isBrawlsAutoStart = false;
  1504. /**
  1505. * Copies the text to the clipboard
  1506. *
  1507. * Копирует тест в буфер обмена
  1508. * @param {*} text copied text // копируемый текст
  1509. */
  1510. function copyText(text) {
  1511. let copyTextarea = document.createElement("textarea");
  1512. copyTextarea.style.opacity = "0";
  1513. copyTextarea.textContent = text;
  1514. document.body.appendChild(copyTextarea);
  1515. copyTextarea.select();
  1516. document.execCommand("copy");
  1517. document.body.removeChild(copyTextarea);
  1518. delete copyTextarea;
  1519. }
  1520. /**
  1521. * Returns the history of requests
  1522. *
  1523. * Возвращает историю запросов
  1524. */
  1525. this.getRequestHistory = function() {
  1526. return requestHistory;
  1527. }
  1528. /**
  1529. * Generates a random integer from min to max
  1530. *
  1531. * Гененирует случайное целое число от min до max
  1532. */
  1533. const random = function (min, max) {
  1534. return Math.floor(Math.random() * (max - min + 1) + min);
  1535. }
  1536. /**
  1537. * Clearing the request history
  1538. *
  1539. * Очистка истоии запросов
  1540. */
  1541. setInterval(function () {
  1542. let now = Date.now();
  1543. for (let i in requestHistory) {
  1544. const time = +i.split('_')[0];
  1545. if (now - time > 300000) {
  1546. delete requestHistory[i];
  1547. }
  1548. }
  1549. }, 300000);
  1550. /**
  1551. * Displays the dialog box
  1552. *
  1553. * Отображает диалоговое окно
  1554. */
  1555. function confShow(message, yesCallback, noCallback) {
  1556. let buts = [];
  1557. message = message || I18N('DO_YOU_WANT');
  1558. noCallback = noCallback || (() => {});
  1559. if (yesCallback) {
  1560. buts = [
  1561. { msg: I18N('BTN_RUN'), result: true},
  1562. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1563. ]
  1564. } else {
  1565. yesCallback = () => {};
  1566. buts = [
  1567. { msg: I18N('BTN_OK'), result: true},
  1568. ];
  1569. }
  1570. popup.confirm(message, buts).then((e) => {
  1571. // dialogPromice = null;
  1572. if (e) {
  1573. yesCallback();
  1574. } else {
  1575. noCallback();
  1576. }
  1577. });
  1578. }
  1579. /**
  1580. * Override/proxy the method for creating a WS package send
  1581. *
  1582. * Переопределяем/проксируем метод создания отправки WS пакета
  1583. */
  1584. WebSocket.prototype.send = function (data) {
  1585. if (!this.isSetOnMessage) {
  1586. const oldOnmessage = this.onmessage;
  1587. this.onmessage = function (event) {
  1588. try {
  1589. const data = JSON.parse(event.data);
  1590. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1591. this.isWebSocketLogin = true;
  1592. } else if (data.result.type == "iframeEvent.login") {
  1593. return;
  1594. }
  1595. } catch (e) { }
  1596. return oldOnmessage.apply(this, arguments);
  1597. }
  1598. this.isSetOnMessage = true;
  1599. }
  1600. original.SendWebSocket.call(this, data);
  1601. }
  1602. /**
  1603. * Overriding/Proxying the Ajax Request Creation Method
  1604. *
  1605. * Переопределяем/проксируем метод создания Ajax запроса
  1606. */
  1607. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1608. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1609. this.errorRequest = false;
  1610. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1611. if (!apiUrl) {
  1612. apiUrl = url;
  1613. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1614. console.log(socialInfo);
  1615. }
  1616. requestHistory[this.uniqid] = {
  1617. method,
  1618. url,
  1619. error: [],
  1620. headers: {},
  1621. request: null,
  1622. response: null,
  1623. signature: [],
  1624. calls: {},
  1625. };
  1626. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1627. this.errorRequest = true;
  1628. }
  1629. return original.open.call(this, method, url, async, user, password);
  1630. };
  1631. /**
  1632. * Overriding/Proxying the header setting method for the AJAX request
  1633. *
  1634. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1635. */
  1636. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1637. if (this.uniqid in requestHistory) {
  1638. requestHistory[this.uniqid].headers[name] = value;
  1639. } else {
  1640. check = true;
  1641. }
  1642.  
  1643. if (name == 'X-Auth-Signature') {
  1644. requestHistory[this.uniqid].signature.push(value);
  1645. if (!check) {
  1646. return;
  1647. }
  1648. }
  1649.  
  1650. return original.setRequestHeader.call(this, name, value);
  1651. };
  1652. /**
  1653. * Overriding/Proxying the AJAX Request Sending Method
  1654. *
  1655. * Переопределяем/проксируем метод отправки AJAX запроса
  1656. */
  1657. XMLHttpRequest.prototype.send = async function (sourceData) {
  1658. if (this.uniqid in requestHistory) {
  1659. let tempData = null;
  1660. if (getClass(sourceData) == "ArrayBuffer") {
  1661. tempData = decoder.decode(sourceData);
  1662. } else {
  1663. tempData = sourceData;
  1664. }
  1665. requestHistory[this.uniqid].request = tempData;
  1666. let headers = requestHistory[this.uniqid].headers;
  1667. lastHeaders = Object.assign({}, headers);
  1668. /**
  1669. * Game loading event
  1670. *
  1671. * Событие загрузки игры
  1672. */
  1673. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1674. isLoadGame = true;
  1675. await lib.load();
  1676. addControls();
  1677. addControlButtons();
  1678. addBottomUrls();
  1679.  
  1680. if (isChecked('sendExpedition')) {
  1681. checkExpedition();
  1682. }
  1683.  
  1684. getAutoGifts();
  1685.  
  1686. cheats.activateHacks();
  1687. justInfo();
  1688. if (isChecked('dailyQuests')) {
  1689. testDailyQuests();
  1690. }
  1691.  
  1692. if (isChecked('buyForGold')) {
  1693. buyInStoreForGold();
  1694. }
  1695. }
  1696. /**
  1697. * Outgoing request data processing
  1698. *
  1699. * Обработка данных исходящего запроса
  1700. */
  1701. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1702. /**
  1703. * Handling incoming request data
  1704. *
  1705. * Обработка данных входящего запроса
  1706. */
  1707. const oldReady = this.onreadystatechange;
  1708. this.onreadystatechange = async function (e) {
  1709. if (this.errorRequest) {
  1710. return oldReady.apply(this, arguments);
  1711. }
  1712. if(this.readyState == 4 && this.status == 200) {
  1713. isTextResponse = this.responseType === "text" || this.responseType === "";
  1714. let response = isTextResponse ? this.responseText : this.response;
  1715. requestHistory[this.uniqid].response = response;
  1716. /**
  1717. * Replacing incoming request data
  1718. *
  1719. * Заменна данных входящего запроса
  1720. */
  1721. if (isTextResponse) {
  1722. await checkChangeResponse.call(this, response);
  1723. }
  1724. /**
  1725. * A function to run after the request is executed
  1726. *
  1727. * Функция запускаемая после выполения запроса
  1728. */
  1729. if (typeof this.onReadySuccess == 'function') {
  1730. setTimeout(this.onReadySuccess, 500);
  1731. }
  1732. /** Удаляем из истории запросов битвы с боссом */
  1733. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1734. }
  1735. if (oldReady) {
  1736. return oldReady.apply(this, arguments);
  1737. }
  1738. }
  1739. }
  1740. if (this.errorRequest) {
  1741. const oldReady = this.onreadystatechange;
  1742. this.onreadystatechange = function () {
  1743. Object.defineProperty(this, 'status', {
  1744. writable: true
  1745. });
  1746. this.status = 200;
  1747. Object.defineProperty(this, 'readyState', {
  1748. writable: true
  1749. });
  1750. this.readyState = 4;
  1751. Object.defineProperty(this, 'responseText', {
  1752. writable: true
  1753. });
  1754. this.responseText = JSON.stringify({
  1755. "result": true
  1756. });
  1757. if (typeof this.onReadySuccess == 'function') {
  1758. setTimeout(this.onReadySuccess, 500);
  1759. }
  1760. return oldReady.apply(this, arguments);
  1761. }
  1762. this.onreadystatechange();
  1763. } else {
  1764. try {
  1765. return original.send.call(this, sourceData);
  1766. } catch(e) {
  1767. debugger;
  1768. }
  1769. }
  1770. };
  1771. /**
  1772. * Processing and substitution of outgoing data
  1773. *
  1774. * Обработка и подмена исходящих данных
  1775. */
  1776. async function checkChangeSend(sourceData, tempData) {
  1777. try {
  1778. /**
  1779. * A function that replaces battle data with incorrect ones to cancel combatя
  1780. *
  1781. * Функция заменяющая данные боя на неверные для отмены боя
  1782. */
  1783. const fixBattle = function (heroes) {
  1784. for (const ids in heroes) {
  1785. hero = heroes[ids];
  1786. hero.energy = random(1, 999);
  1787. if (hero.hp > 0) {
  1788. hero.hp = random(1, hero.hp);
  1789. }
  1790. }
  1791. }
  1792. /**
  1793. * Dialog window 2
  1794. *
  1795. * Диалоговое окно 2
  1796. */
  1797. const showMsg = async function (msg, ansF, ansS) {
  1798. if (typeof popup == 'object') {
  1799. return await popup.confirm(msg, [
  1800. {msg: ansF, result: false},
  1801. {msg: ansS, result: true},
  1802. ]);
  1803. } else {
  1804. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  1805. }
  1806. }
  1807. /**
  1808. * Dialog window 3
  1809. *
  1810. * Диалоговое окно 3
  1811. */
  1812. const showMsgs = async function (msg, ansF, ansS, ansT) {
  1813. return await popup.confirm(msg, [
  1814. {msg: ansF, result: 0},
  1815. {msg: ansS, result: 1},
  1816. {msg: ansT, result: 2},
  1817. ]);
  1818. }
  1819.  
  1820. let changeRequest = false;
  1821. testData = JSON.parse(tempData);
  1822. for (const call of testData.calls) {
  1823. if (!artifactChestOpen) {
  1824. requestHistory[this.uniqid].calls[call.name] = call.ident;
  1825. }
  1826. /**
  1827. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  1828. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  1829. */
  1830. if ((call.name == 'adventure_endBattle' ||
  1831. call.name == 'adventureSolo_endBattle' ||
  1832. call.name == 'clanWarEndBattle' &&
  1833. isChecked('cancelBattle') ||
  1834. call.name == 'crossClanWar_endBattle' &&
  1835. isChecked('cancelBattle') ||
  1836. call.name == 'brawl_endBattle' ||
  1837. call.name == 'towerEndBattle' ||
  1838. call.name == 'invasion_bossEnd' ||
  1839. call.name == 'bossEndBattle' ||
  1840. call.name == 'clanRaid_endNodeBattle') &&
  1841. isCancalBattle) {
  1842. nameFuncEndBattle = call.name;
  1843. if (!call.args.result.win) {
  1844. let resultPopup = false;
  1845. if (call.name == 'adventure_endBattle' ||
  1846. call.name == 'invasion_bossEnd' ||
  1847. call.name == 'bossEndBattle' ||
  1848. call.name == 'adventureSolo_endBattle') {
  1849. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1850. } else if (call.name == 'clanWarEndBattle' ||
  1851. call.name == 'crossClanWar_endBattle') {
  1852. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  1853. } else {
  1854. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  1855. }
  1856. if (resultPopup) {
  1857. if (call.name == 'invasion_bossEnd') {
  1858. this.errorRequest = true;
  1859. }
  1860. fixBattle(call.args.progress[0].attackers.heroes);
  1861. fixBattle(call.args.progress[0].defenders.heroes);
  1862. changeRequest = true;
  1863. if (resultPopup > 1) {
  1864. this.onReadySuccess = testAutoBattle;
  1865. // setTimeout(bossBattle, 1000);
  1866. }
  1867. }
  1868. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  1869. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  1870. if (resultPopup) {
  1871. fixBattle(call.args.progress[0].attackers.heroes);
  1872. fixBattle(call.args.progress[0].defenders.heroes);
  1873. changeRequest = true;
  1874. if (resultPopup > 1) {
  1875. this.onReadySuccess = testAutoBattle;
  1876. }
  1877. }
  1878. }
  1879. // Потасовки
  1880. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  1881. }
  1882. /**
  1883. * Save pack for Brawls
  1884. *
  1885. * Сохраняем пачку для потасовок
  1886. */
  1887. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  1888. console.log(JSON.stringify(call.args));
  1889. brawlsPack = call.args;
  1890. if (
  1891. await popup.confirm(
  1892. I18N('START_AUTO_BRAWLS'),
  1893. [
  1894. { msg: I18N('BTN_NO'), result: false },
  1895. { msg: I18N('BTN_YES'), result: true },
  1896. ],
  1897. [
  1898. {
  1899. name: 'isAuto',
  1900. label: I18N('BRAWL_AUTO_PACK'),
  1901. checked: false,
  1902. },
  1903. ]
  1904. )
  1905. ) {
  1906. isBrawlsAutoStart = true;
  1907. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  1908. this.errorRequest = true;
  1909. testBrawls(isAuto.checked);
  1910. }
  1911. }
  1912. /**
  1913. * Canceled fight in Asgard
  1914. * Отмена боя в Асгарде
  1915. */
  1916. if (call.name == 'clanRaid_endBossBattle' &&
  1917. isCancalBossBattle &&
  1918. isChecked('cancelBattle')) {
  1919. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  1920. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  1921. let resultPopup = await showMsgs(
  1922. `${I18N('MSG_YOU_APPLIED')} ${sumDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  1923. I18N('BTN_OK'), I18N('BTN_AUTO_F5'), I18N('MSG_CANCEL_AND_STAT'))
  1924. if (resultPopup) {
  1925. fixBattle(call.args.progress[0].attackers.heroes);
  1926. fixBattle(call.args.progress[0].defenders.heroes);
  1927. changeRequest = true;
  1928. if (resultPopup > 1) {
  1929. this.onReadySuccess = testBossBattle;
  1930. // setTimeout(bossBattle, 1000);
  1931. }
  1932. }
  1933. }
  1934. /**
  1935. * Save the Asgard Boss Attack Pack
  1936. * Сохраняем пачку для атаки босса Асгарда
  1937. */
  1938. if (call.name == 'clanRaid_startBossBattle') {
  1939. lastBossBattle = call.args;
  1940. }
  1941. /**
  1942. * Saving the request to start the last battle
  1943. * Сохранение запроса начала последнего боя
  1944. */
  1945. if (call.name == 'clanWarAttack' ||
  1946. call.name == 'crossClanWar_startBattle' ||
  1947. call.name == 'adventure_turnStartBattle' ||
  1948. call.name == 'bossAttack' ||
  1949. call.name == 'invasion_bossStart' ||
  1950. call.name == 'towerStartBattle') {
  1951. nameFuncStartBattle = call.name;
  1952. lastBattleArg = call.args;
  1953.  
  1954. if (call.name == 'invasion_bossStart') {
  1955. const timePassed = Date.now() - lastBossBattleStart;
  1956. if (timePassed < invasionTimer) {
  1957. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  1958. }
  1959. invasionTimer -= 1;
  1960. }
  1961. lastBossBattleStart = Date.now();
  1962. }
  1963. if (call.name == 'invasion_bossEnd') {
  1964. const lastBattle = lastBattleInfo;
  1965. if (lastBattle && call.args.result.win) {
  1966. lastBattle.progress = call.args.progress;
  1967. const result = await Calc(lastBattle);
  1968. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  1969. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  1970. console.log(timer, period);
  1971. if (period < timer) {
  1972. timer = timer - period;
  1973. await countdownTimer(timer);
  1974. }
  1975. }
  1976. }
  1977. /**
  1978. * Disable spending divination cards
  1979. * Отключить трату карт предсказаний
  1980. */
  1981. if (call.name == 'dungeonEndBattle') {
  1982. if (call.args.isRaid) {
  1983. if (countPredictionCard <= 0) {
  1984. delete call.args.isRaid;
  1985. changeRequest = true;
  1986. } else if (countPredictionCard > 0) {
  1987. countPredictionCard--;
  1988. }
  1989. }
  1990. console.log(`Cards: ${countPredictionCard}`);
  1991. /**
  1992. * Fix endless cards
  1993. * Исправление бесконечных карт
  1994. */
  1995. const lastBattle = lastDungeonBattleData;
  1996. if (lastBattle && !call.args.isRaid) {
  1997. if (changeRequest) {
  1998. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  1999. } else {
  2000. lastBattle.progress = call.args.progress;
  2001. }
  2002. const result = await Calc(lastBattle);
  2003.  
  2004. if (changeRequest) {
  2005. call.args.progress = result.progress;
  2006. call.args.result = result.result;
  2007. }
  2008. let timer = getTimer(result.battleTime) + addBattleTimer;
  2009. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2010. console.log(timer, period);
  2011. if (period < timer) {
  2012. timer = timer - period;
  2013. await countdownTimer(timer);
  2014. }
  2015. }
  2016. }
  2017. /**
  2018. * Quiz Answer
  2019. * Ответ на викторину
  2020. */
  2021. if (call.name == 'quizAnswer') {
  2022. /**
  2023. * Automatically changes the answer to the correct one if there is one.
  2024. * Автоматически меняет ответ на правильный если он есть
  2025. */
  2026. if (lastAnswer && isChecked('getAnswer')) {
  2027. call.args.answerId = lastAnswer;
  2028. lastAnswer = null;
  2029. changeRequest = true;
  2030. }
  2031. }
  2032. /**
  2033. * Present
  2034. * Подарки
  2035. */
  2036. if (call.name == 'freebieCheck') {
  2037. freebieCheckInfo = call;
  2038. }
  2039. /** missionTimer */
  2040. if (call.name == 'missionEnd' && missionBattle) {
  2041. missionBattle.progress = call.args.progress;
  2042. missionBattle.result = call.args.result;
  2043. const result = await Calc(missionBattle);
  2044.  
  2045. let timer = getTimer(result.battleTime) + addBattleTimer;
  2046. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2047. if (period < timer) {
  2048. timer = timer - period;
  2049. await countdownTimer(timer);
  2050. }
  2051. missionBattle = null;
  2052. }
  2053. /**
  2054. * Getting mission data for auto-repeat
  2055. * Получение данных миссии для автоповтора
  2056. */
  2057. if (isChecked('repeatMission') &&
  2058. call.name == 'missionEnd') {
  2059. let missionInfo = {
  2060. id: call.args.id,
  2061. result: call.args.result,
  2062. heroes: call.args.progress[0].attackers.heroes,
  2063. count: 0,
  2064. }
  2065. setTimeout(async () => {
  2066. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2067. { msg: I18N('BTN_REPEAT'), result: true},
  2068. { msg: I18N('BTN_NO'), result: false},
  2069. ])) {
  2070. isStopSendMission = false;
  2071. isSendsMission = true;
  2072. sendsMission(missionInfo);
  2073. }
  2074. }, 0);
  2075. }
  2076. /**
  2077. * Getting mission data
  2078. * Получение данных миссии
  2079. * missionTimer
  2080. */
  2081. if (call.name == 'missionStart') {
  2082. lastMissionStart = call.args;
  2083. lastMissionBattleStart = Date.now();
  2084. }
  2085. /**
  2086. * Specify the quantity for Titan Orbs and Pet Eggs
  2087. * Указать количество для сфер титанов и яиц петов
  2088. */
  2089. if (isChecked('countControl') &&
  2090. (call.name == 'pet_chestOpen' ||
  2091. call.name == 'titanUseSummonCircle') &&
  2092. call.args.amount > 1) {
  2093. call.args.amount = 1;
  2094. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2095. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2096. ]);
  2097. if (result) {
  2098. call.args.amount = result;
  2099. changeRequest = true;
  2100. }
  2101. }
  2102. /**
  2103. * Specify the amount for keys and spheres of titan artifacts
  2104. * Указать колличество для ключей и сфер артефактов титанов
  2105. */
  2106. if (isChecked('countControl') &&
  2107. (call.name == 'artifactChestOpen' ||
  2108. call.name == 'titanArtifactChestOpen') &&
  2109. call.args.amount > 1 &&
  2110. call.args.free &&
  2111. !changeRequest) {
  2112. artifactChestOpenCallName = call.name;
  2113. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2114. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2115. ]);
  2116. if (result) {
  2117. let sphere = result < 10 ? 1 : 10;
  2118.  
  2119. call.args.amount = sphere;
  2120. result -= sphere;
  2121.  
  2122. for (let count = result; count > 0; count -= sphere) {
  2123. if (count < 10) sphere = 1;
  2124. const ident = artifactChestOpenCallName + "_" + count;
  2125. testData.calls.push({
  2126. name: artifactChestOpenCallName,
  2127. args: {
  2128. amount: sphere,
  2129. free: true,
  2130. },
  2131. ident: ident
  2132. });
  2133. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2134. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2135. }
  2136. requestHistory[this.uniqid].calls[call.name].push(ident);
  2137. }
  2138.  
  2139. artifactChestOpen = true;
  2140. changeRequest = true;
  2141. }
  2142. }
  2143. if (call.name == 'consumableUseLootBox') {
  2144. lastRussianDollId = call.args.libId;
  2145. /**
  2146. * Specify quantity for gold caskets
  2147. * Указать количество для золотых шкатулок
  2148. */
  2149. if (isChecked('countControl') &&
  2150. call.args.libId == 148 &&
  2151. call.args.amount > 1) {
  2152. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2153. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2154. ]);
  2155. call.args.amount = result;
  2156. changeRequest = true;
  2157. }
  2158. }
  2159. /**
  2160. * Changing the maximum number of raids in the campaign
  2161. * Изменение максимального количества рейдов в кампании
  2162. */
  2163. // if (call.name == 'missionRaid') {
  2164. // if (isChecked('countControl') && call.args.times > 1) {
  2165. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2166. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2167. // ]));
  2168. // call.args.times = result > call.args.times ? call.args.times : result;
  2169. // changeRequest = true;
  2170. // }
  2171. // }
  2172. }
  2173.  
  2174. let headers = requestHistory[this.uniqid].headers;
  2175. if (changeRequest) {
  2176. sourceData = JSON.stringify(testData);
  2177. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2178. }
  2179.  
  2180. let signature = headers['X-Auth-Signature'];
  2181. if (signature) {
  2182. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2183. }
  2184. } catch (err) {
  2185. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2186. }
  2187. return sourceData;
  2188. }
  2189. /**
  2190. * Processing and substitution of incoming data
  2191. *
  2192. * Обработка и подмена входящих данных
  2193. */
  2194. async function checkChangeResponse(response) {
  2195. try {
  2196. isChange = false;
  2197. let nowTime = Math.round(Date.now() / 1000);
  2198. callsIdent = requestHistory[this.uniqid].calls;
  2199. respond = JSON.parse(response);
  2200. /**
  2201. * If the request returned an error removes the error (removes synchronization errors)
  2202. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2203. */
  2204. if (respond.error) {
  2205. isChange = true;
  2206. console.error(respond.error);
  2207. if (isChecked('showErrors')) {
  2208. popup.confirm(I18N('ERROR_MSG', {
  2209. name: respond.error.name,
  2210. description: respond.error.description,
  2211. }));
  2212. }
  2213. delete respond.error;
  2214. respond.results = [];
  2215. }
  2216. let mainReward = null;
  2217. const allReward = {};
  2218. let countTypeReward = 0;
  2219. let readQuestInfo = false;
  2220. for (const call of respond.results) {
  2221. /**
  2222. * Obtaining initial data for completing quests
  2223. * Получение исходных данных для выполнения квестов
  2224. */
  2225. if (readQuestInfo) {
  2226. questsInfo[call.ident] = call.result.response;
  2227. }
  2228. /**
  2229. * Getting a user ID
  2230. * Получение идетификатора пользователя
  2231. */
  2232. if (call.ident == callsIdent['registration']) {
  2233. userId = call.result.response.userId;
  2234. if (localStorage['userId'] != userId) {
  2235. localStorage['newGiftSendIds'] = '';
  2236. localStorage['userId'] = userId;
  2237. }
  2238. await openOrMigrateDatabase(userId);
  2239. readQuestInfo = true;
  2240. }
  2241. /**
  2242. * Hiding donation offers 1
  2243. * Скрываем предложения доната 1
  2244. */
  2245. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2246. const billings = call.result.response?.billings;
  2247. const bundle = call.result.response?.bundle;
  2248. if (billings && bundle) {
  2249. call.result.response.billings = [];
  2250. call.result.response.bundle = [];
  2251. isChange = true;
  2252. }
  2253. }
  2254. /**
  2255. * Hiding donation offers 2
  2256. * Скрываем предложения доната 2
  2257. */
  2258. if (getSaveVal('noOfferDonat') &&
  2259. (call.ident == callsIdent['offerGetAll'] ||
  2260. call.ident == callsIdent['specialOffer_getAll'])) {
  2261. let offers = call.result.response;
  2262. if (offers) {
  2263. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2264. isChange = true;
  2265. }
  2266. }
  2267. /**
  2268. * Hiding donation offers 3
  2269. * Скрываем предложения доната 3
  2270. */
  2271. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2272. delete call.result.bundleUpdate;
  2273. isChange = true;
  2274. }
  2275. /**
  2276. * Copies a quiz question to the clipboard
  2277. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2278. */
  2279. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2280. let quest = call.result.response;
  2281. console.log(quest.question);
  2282. copyText(quest.question);
  2283. setProgress(I18N('QUESTION_COPY'), true);
  2284. quest.lang = null;
  2285. if (typeof NXFlashVars !== 'undefined') {
  2286. quest.lang = NXFlashVars.interface_lang;
  2287. }
  2288. lastQuestion = quest;
  2289. if (isChecked('getAnswer')) {
  2290. const answer = await getAnswer(lastQuestion);
  2291. let showText = '';
  2292. if (answer) {
  2293. lastAnswer = answer;
  2294. console.log(answer);
  2295. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2296. } else {
  2297. showText = I18N('ANSWER_NOT_KNOWN');
  2298. }
  2299.  
  2300. try {
  2301. const hint = hintQuest(quest);
  2302. if (hint) {
  2303. showText += I18N('HINT') + hint;
  2304. }
  2305. } catch(e) {}
  2306.  
  2307. setProgress(showText, true);
  2308. }
  2309. }
  2310. /**
  2311. * Submits a question with an answer to the database
  2312. * Отправляет вопрос с ответом в базу данных
  2313. */
  2314. if (call.ident == callsIdent['quizAnswer']) {
  2315. const answer = call.result.response;
  2316. if (lastQuestion) {
  2317. const answerInfo = {
  2318. answer,
  2319. question: lastQuestion,
  2320. lang: null,
  2321. }
  2322. if (typeof NXFlashVars !== 'undefined') {
  2323. answerInfo.lang = NXFlashVars.interface_lang;
  2324. }
  2325. lastQuestion = null;
  2326. setTimeout(sendAnswerInfo, 0, answerInfo);
  2327. }
  2328. }
  2329. /**
  2330. * Get user data
  2331. * Получить даныне пользователя
  2332. */
  2333. if (call.ident == callsIdent['userGetInfo']) {
  2334. let user = call.result.response;
  2335. userInfo = Object.assign({}, user);
  2336. delete userInfo.refillable;
  2337. if (!questsInfo['userGetInfo']) {
  2338. questsInfo['userGetInfo'] = user;
  2339. }
  2340. }
  2341. /**
  2342. * Start of the battle for recalculation
  2343. * Начало боя для прерасчета
  2344. */
  2345. if (call.ident == callsIdent['clanWarAttack'] ||
  2346. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2347. call.ident == callsIdent['bossAttack'] ||
  2348. call.ident == callsIdent['battleGetReplay'] ||
  2349. call.ident == callsIdent['brawl_startBattle'] ||
  2350. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2351. call.ident == callsIdent['invasion_bossStart'] ||
  2352. call.ident == callsIdent['towerStartBattle'] ||
  2353. call.ident == callsIdent['adventure_turnStartBattle']) {
  2354. let battle = call.result.response.battle || call.result.response.replay;
  2355. if (call.ident == callsIdent['brawl_startBattle'] ||
  2356. call.ident == callsIdent['bossAttack'] ||
  2357. call.ident == callsIdent['towerStartBattle'] ||
  2358. call.ident == callsIdent['invasion_bossStart']) {
  2359. battle = call.result.response;
  2360. }
  2361. lastBattleInfo = battle;
  2362. if (!isChecked('preCalcBattle')) {
  2363. continue;
  2364. }
  2365. setProgress(I18N('BEING_RECALC'));
  2366. let battleDuration = 120;
  2367. try {
  2368. const typeBattle = getBattleType(battle.type);
  2369. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2370. } catch (e) { }
  2371. //console.log(battle.type);
  2372. function getBattleInfo(battle, isRandSeed) {
  2373. return new Promise(function (resolve) {
  2374. if (isRandSeed) {
  2375. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2376. }
  2377. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2378. });
  2379. }
  2380. let actions = [getBattleInfo(battle, false)]
  2381. const countTestBattle = getInput('countTestBattle');
  2382. if (call.ident == callsIdent['battleGetReplay']) {
  2383. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2384. }
  2385. for (let i = 0; i < countTestBattle; i++) {
  2386. actions.push(getBattleInfo(battle, true));
  2387. }
  2388. Promise.all(actions)
  2389. .then(e => {
  2390. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2391. let firstBattle = e.shift();
  2392. const timer = Math.floor(battleDuration - firstBattle.time);
  2393. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2394. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2395. const countWin = e.reduce((w, s) => w + s.win, 0);
  2396. 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)
  2397. });
  2398. }
  2399. /**
  2400. * Start of the Asgard boss fight
  2401. * Начало боя с боссом Асгарда
  2402. */
  2403. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2404. lastBossBattleInfo = call.result.response.battle;
  2405. if (isChecked('preCalcBattle')) {
  2406. const result = await Calc(lastBossBattleInfo).then(e => e.progress[0].defenders.heroes[1].extra);
  2407. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2408. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2409. }
  2410. }
  2411. /**
  2412. * Cancel tutorial
  2413. * Отмена туториала
  2414. */
  2415. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2416. let chains = call.result.response.chains;
  2417. for (let n in chains) {
  2418. chains[n] = 9999;
  2419. }
  2420. isChange = true;
  2421. }
  2422. /**
  2423. * Opening keys and spheres of titan artifacts
  2424. * Открытие ключей и сфер артефактов титанов
  2425. */
  2426. if (artifactChestOpen &&
  2427. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2428. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2429. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2430.  
  2431. reward.forEach(e => {
  2432. for (let f in e) {
  2433. if (!allReward[f]) {
  2434. allReward[f] = {};
  2435. }
  2436. for (let o in e[f]) {
  2437. if (!allReward[f][o]) {
  2438. allReward[f][o] = e[f][o];
  2439. countTypeReward++;
  2440. } else {
  2441. allReward[f][o] += e[f][o];
  2442. }
  2443. }
  2444. }
  2445. });
  2446.  
  2447. if (!call.ident.includes(artifactChestOpenCallName)) {
  2448. mainReward = call.result.response;
  2449. }
  2450. }
  2451.  
  2452. if (countTypeReward > 20) {
  2453. correctShowOpenArtifact = 3;
  2454. } else {
  2455. correctShowOpenArtifact = 0;
  2456. }
  2457. /**
  2458. * Sum the result of opening Pet Eggs
  2459. * Суммирование результата открытия яиц питомцев
  2460. */
  2461. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2462. const rewards = call.result.response.rewards;
  2463. if (rewards.length > 10) {
  2464. /**
  2465. * Removing pet cards
  2466. * Убираем карточки петов
  2467. */
  2468. for (const reward of rewards) {
  2469. if (reward.petCard) {
  2470. delete reward.petCard;
  2471. }
  2472. }
  2473. }
  2474. rewards.forEach(e => {
  2475. for (let f in e) {
  2476. if (!allReward[f]) {
  2477. allReward[f] = {};
  2478. }
  2479. for (let o in e[f]) {
  2480. if (!allReward[f][o]) {
  2481. allReward[f][o] = e[f][o];
  2482. } else {
  2483. allReward[f][o] += e[f][o];
  2484. }
  2485. }
  2486. }
  2487. });
  2488. call.result.response.rewards = [allReward];
  2489. isChange = true;
  2490. }
  2491. /**
  2492. * Removing titan cards
  2493. * Убираем карточки титанов
  2494. */
  2495. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2496. if (call.result.response.rewards.length > 10) {
  2497. for (const reward of call.result.response.rewards) {
  2498. if (reward.titanCard) {
  2499. delete reward.titanCard;
  2500. }
  2501. }
  2502. isChange = true;
  2503. }
  2504. }
  2505. /**
  2506. * Auto-repeat opening matryoshkas
  2507. * АвтоПовтор открытия матрешек
  2508. */
  2509. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2510. let lootBox = call.result.response;
  2511. let newCount = 0;
  2512. for (let n of lootBox) {
  2513. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2514. newCount += n.consumable[lastRussianDollId]
  2515. }
  2516. }
  2517. if (newCount && await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2518. { msg: I18N('BTN_OPEN'), result: true},
  2519. { msg: I18N('BTN_NO'), result: false},
  2520. ])) {
  2521. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2522. lootBox = [...lootBox, ...recursionResult];
  2523. }
  2524.  
  2525. /** Объединение результата лутбоксов */
  2526. const allLootBox = {};
  2527. lootBox.forEach(e => {
  2528. for (let f in e) {
  2529. if (!allLootBox[f]) {
  2530. if (typeof e[f] == 'object') {
  2531. allLootBox[f] = {};
  2532. } else {
  2533. allLootBox[f] = 0;
  2534. }
  2535. }
  2536. if (typeof e[f] == 'object') {
  2537. for (let o in e[f]) {
  2538. if (newCount && o == lastRussianDollId) {
  2539. continue;
  2540. }
  2541. if (!allLootBox[f][o]) {
  2542. allLootBox[f][o] = e[f][o];
  2543. } else {
  2544. allLootBox[f][o] += e[f][o];
  2545. }
  2546. }
  2547. } else {
  2548. allLootBox[f] += e[f];
  2549. }
  2550. }
  2551. });
  2552. /** Разбитие результата */
  2553. const output = [];
  2554. const maxCount = 5;
  2555. let currentObj = {};
  2556. let count = 0;
  2557. for (let f in allLootBox) {
  2558. if (!currentObj[f]) {
  2559. if (typeof allLootBox[f] == 'object') {
  2560. for (let o in allLootBox[f]) {
  2561. currentObj[f] ||= {}
  2562. if (!currentObj[f][o]) {
  2563. currentObj[f][o] = allLootBox[f][o];
  2564. count++;
  2565. if (count === maxCount) {
  2566. output.push(currentObj);
  2567. currentObj = {};
  2568. count = 0;
  2569. }
  2570. }
  2571. }
  2572. } else {
  2573. currentObj[f] = allLootBox[f];
  2574. count++;
  2575. if (count === maxCount) {
  2576. output.push(currentObj);
  2577. currentObj = {};
  2578. count = 0;
  2579. }
  2580. }
  2581. }
  2582. }
  2583. if (count > 0) {
  2584. output.push(currentObj);
  2585. }
  2586.  
  2587. console.log(output);
  2588. call.result.response = output;
  2589. isChange = true;
  2590. }
  2591. /**
  2592. * Dungeon recalculation (fix endless cards)
  2593. * Прерасчет подземки (исправление бесконечных карт)
  2594. */
  2595. if (call.ident == callsIdent['dungeonStartBattle']) {
  2596. lastDungeonBattleData = call.result.response;
  2597. lastDungeonBattleStart = Date.now();
  2598. }
  2599. /**
  2600. * Getting the number of prediction cards
  2601. * Получение количества карт предсказаний
  2602. */
  2603. if (call.ident == callsIdent['inventoryGet']) {
  2604. countPredictionCard = call.result.response.consumable[81] || 0;
  2605. }
  2606. /**
  2607. * Getting subscription status
  2608. * Получение состояния подписки
  2609. */
  2610. if (call.ident == callsIdent['subscriptionGetInfo']) {
  2611. const subscription = call.result.response.subscription;
  2612. if (subscription) {
  2613. subEndTime = subscription.endTime * 1000;
  2614. }
  2615. }
  2616. /**
  2617. * Getting prediction cards
  2618. * Получение карт предсказаний
  2619. */
  2620. if (call.ident == callsIdent['questFarm']) {
  2621. const consumable = call.result.response?.consumable;
  2622. if (consumable && consumable[81]) {
  2623. countPredictionCard += consumable[81];
  2624. console.log(`Cards: ${countPredictionCard}`);
  2625. }
  2626. }
  2627. /**
  2628. * Hiding extra servers
  2629. * Скрытие лишних серверов
  2630. */
  2631. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  2632. let servers = call.result.response.users.map(s => s.serverId)
  2633. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  2634. isChange = true;
  2635. }
  2636. /**
  2637. * Displays player positions in the adventure
  2638. * Отображает позиции игроков в приключении
  2639. */
  2640. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  2641. const users = Object.values(call.result.response.users);
  2642. const mapIdent = call.result.response.mapIdent;
  2643. const adventureId = call.result.response.adventureId;
  2644. const maps = {
  2645. adv_strongford_3pl_hell: 9,
  2646. adv_valley_3pl_hell: 10,
  2647. adv_ghirwil_3pl_hell: 11,
  2648. adv_angels_3pl_hell: 12,
  2649. }
  2650. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  2651. msg += '<br>' + I18N('PLAYER_POS');
  2652. for (const user of users) {
  2653. msg += `<br>${user.user.name} - ${user.currentNode}`;
  2654. }
  2655. setProgress(msg, false, hideProgress);
  2656. }
  2657. /**
  2658. * Automatic launch of a raid at the end of the adventure
  2659. * Автоматический запуск рейда при окончании приключения
  2660. */
  2661. if (call.ident == callsIdent['adventure_end']) {
  2662. autoRaidAdventure()
  2663. }
  2664. /** Удаление лавки редкостей */
  2665. if (call.ident == callsIdent['missionRaid']) {
  2666. if (call.result?.heroesMerchant) {
  2667. delete call.result.heroesMerchant;
  2668. isChange = true;
  2669. }
  2670. }
  2671. /** missionTimer */
  2672. if (call.ident == callsIdent['missionStart']) {
  2673. missionBattle = call.result.response;
  2674. }
  2675. }
  2676.  
  2677. if (mainReward && artifactChestOpen) {
  2678. console.log(allReward);
  2679. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  2680. artifactChestOpen = false;
  2681. artifactChestOpenCallName = '';
  2682. isChange = true;
  2683. }
  2684. } catch(err) {
  2685. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  2686. }
  2687.  
  2688. if (isChange) {
  2689. Object.defineProperty(this, 'responseText', {
  2690. writable: true
  2691. });
  2692. this.responseText = JSON.stringify(respond);
  2693. }
  2694. }
  2695.  
  2696. /**
  2697. * Request an answer to a question
  2698. *
  2699. * Запрос ответа на вопрос
  2700. */
  2701. async function getAnswer(question) {
  2702. const now = Date.now();
  2703. const body = JSON.stringify({ ...question, now });
  2704. const signature = window['\x73\x69\x67\x6e'](now);
  2705. return new Promise(resolve => {
  2706. fetch('https://zingery.ru/heroes/getAnswer.php', {
  2707. method: 'POST',
  2708. headers: {
  2709. 'X-Request-Signature': signature,
  2710. 'X-Script-Name': GM_info.script.name,
  2711. 'X-Script-Version': GM_info.script.version,
  2712. 'X-Script-Author': GM_info.script.author,
  2713. },
  2714. body,
  2715. }).then(
  2716. response => response.json()
  2717. ).then(
  2718. data => {
  2719. if (data.result) {
  2720. resolve(data.result);
  2721. } else {
  2722. resolve(false);
  2723. }
  2724. }
  2725. ).catch((error) => {
  2726. console.error(error);
  2727. resolve(false);
  2728. });
  2729. })
  2730. }
  2731.  
  2732. /**
  2733. * Submitting a question and answer to a database
  2734. *
  2735. * Отправка вопроса и ответа в базу данных
  2736. */
  2737. function sendAnswerInfo(answerInfo) {
  2738. fetch('https://zingery.ru/heroes/setAnswer.php', {
  2739. method: 'POST',
  2740. body: JSON.stringify(answerInfo)
  2741. }).then(
  2742. response => response.json()
  2743. ).then(
  2744. data => {
  2745. if (data.result) {
  2746. console.log(I18N('SENT_QUESTION'));
  2747. }
  2748. }
  2749. )
  2750. }
  2751.  
  2752. /**
  2753. * Returns the battle type by preset type
  2754. *
  2755. * Возвращает тип боя по типу пресета
  2756. */
  2757. function getBattleType(strBattleType) {
  2758. if (strBattleType.includes("invasion")) {
  2759. return "get_invasion";
  2760. }
  2761. if (strBattleType.includes("boss")) {
  2762. return "get_boss";
  2763. }
  2764. switch (strBattleType) {
  2765. case "invasion":
  2766. return "get_invasion";
  2767. case "titan_pvp_manual":
  2768. return "get_titanPvpManual";
  2769. case "titan_pvp":
  2770. return "get_titanPvp";
  2771. case "titan_clan_pvp":
  2772. case "clan_pvp_titan":
  2773. case "clan_global_pvp_titan":
  2774. case "brawl_titan":
  2775. case "challenge_titan":
  2776. return "get_titanClanPvp";
  2777. case "clan_raid": // Asgard Boss // Босс асгарда
  2778. case "adventure": // Adventures // Приключения
  2779. case "clan_global_pvp":
  2780. case "clan_pvp":
  2781. return "get_clanPvp";
  2782. case "dungeon_titan":
  2783. case "titan_tower":
  2784. return "get_titan";
  2785. case "tower":
  2786. case "clan_dungeon":
  2787. return "get_tower";
  2788. case "pve":
  2789. return "get_pve";
  2790. case "pvp_manual":
  2791. return "get_pvpManual";
  2792. case "grand":
  2793. case "arena":
  2794. case "pvp":
  2795. case "challenge":
  2796. return "get_pvp";
  2797. case "core":
  2798. return "get_core";
  2799. case "boss_10":
  2800. case "boss_11":
  2801. case "boss_12":
  2802. return "get_boss";
  2803. default:
  2804. return "get_clanPvp";
  2805. }
  2806. }
  2807. /**
  2808. * Returns the class name of the passed object
  2809. *
  2810. * Возвращает название класса переданного объекта
  2811. */
  2812. function getClass(obj) {
  2813. return {}.toString.call(obj).slice(8, -1);
  2814. }
  2815. /**
  2816. * Calculates the request signature
  2817. *
  2818. * Расчитывает сигнатуру запроса
  2819. */
  2820. this.getSignature = function(headers, data) {
  2821. const sign = {
  2822. signature: '',
  2823. length: 0,
  2824. add: function (text) {
  2825. this.signature += text;
  2826. if (this.length < this.signature.length) {
  2827. this.length = 3 * (this.signature.length + 1) >> 1;
  2828. }
  2829. },
  2830. }
  2831. sign.add(headers["X-Request-Id"]);
  2832. sign.add(':');
  2833. sign.add(headers["X-Auth-Token"]);
  2834. sign.add(':');
  2835. sign.add(headers["X-Auth-Session-Id"]);
  2836. sign.add(':');
  2837. sign.add(data);
  2838. sign.add(':');
  2839. sign.add('LIBRARY-VERSION=1');
  2840. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  2841.  
  2842. return md5(sign.signature);
  2843. }
  2844. /**
  2845. * Creates an interface
  2846. *
  2847. * Создает интерфейс
  2848. */
  2849. function createInterface() {
  2850. popup.init();
  2851. scriptMenu.init({
  2852. showMenu: true
  2853. });
  2854. scriptMenu.addHeader(GM_info.script.name, justInfo);
  2855. scriptMenu.addHeader('v' + GM_info.script.version);
  2856. }
  2857.  
  2858. function addControls() {
  2859. createInterface();
  2860. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  2861. for (let name in checkboxes) {
  2862. if (checkboxes[name].hide) {
  2863. continue;
  2864. }
  2865. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  2866. /**
  2867. * Getting the state of checkboxes from storage
  2868. * Получаем состояние чекбоксов из storage
  2869. */
  2870. let val = storage.get(name, null);
  2871. if (val != null) {
  2872. checkboxes[name].cbox.checked = val;
  2873. } else {
  2874. storage.set(name, checkboxes[name].default);
  2875. checkboxes[name].cbox.checked = checkboxes[name].default;
  2876. }
  2877. /**
  2878. * Tracing the change event of the checkbox for writing to storage
  2879. * Отсеживание события изменения чекбокса для записи в storage
  2880. */
  2881. checkboxes[name].cbox.dataset['name'] = name;
  2882. checkboxes[name].cbox.addEventListener('change', async function (event) {
  2883. const nameCheckbox = this.dataset['name'];
  2884. /*
  2885. if (this.checked && nameCheckbox == 'cancelBattle') {
  2886. this.checked = false;
  2887. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  2888. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  2889. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  2890. ])) {
  2891. return;
  2892. }
  2893. this.checked = true;
  2894. }
  2895. */
  2896. storage.set(nameCheckbox, this.checked);
  2897. })
  2898. }
  2899.  
  2900. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  2901. for (let name in inputs) {
  2902. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  2903. /**
  2904. * Get inputText state from storage
  2905. * Получаем состояние inputText из storage
  2906. */
  2907. let val = storage.get(name, null);
  2908. if (val != null) {
  2909. inputs[name].input.value = val;
  2910. } else {
  2911. storage.set(name, inputs[name].default);
  2912. inputs[name].input.value = inputs[name].default;
  2913. }
  2914. /**
  2915. * Tracing a field change event for a record in storage
  2916. * Отсеживание события изменения поля для записи в storage
  2917. */
  2918. inputs[name].input.dataset['name'] = name;
  2919. inputs[name].input.addEventListener('input', function () {
  2920. const inputName = this.dataset['name'];
  2921. let value = +this.value;
  2922. if (!value || Number.isNaN(value)) {
  2923. value = storage.get(inputName, inputs[inputName].default);
  2924. inputs[name].input.value = value;
  2925. }
  2926. storage.set(inputName, value);
  2927. })
  2928. }
  2929. }
  2930.  
  2931. /**
  2932. * Sending a request
  2933. *
  2934. * Отправка запроса
  2935. */
  2936. function send(json, callback, pr) {
  2937. if (typeof json == 'string') {
  2938. json = JSON.parse(json);
  2939. }
  2940. for (const call of json.calls) {
  2941. if (!call?.context?.actionTs) {
  2942. call.context = {
  2943. actionTs: Math.floor(performance.now())
  2944. }
  2945. }
  2946. }
  2947. json = JSON.stringify(json);
  2948. /**
  2949. * We get the headlines of the previous intercepted request
  2950. * Получаем заголовки предыдущего перехваченого запроса
  2951. */
  2952. let headers = lastHeaders;
  2953. /**
  2954. * We increase the header of the query Certifier by 1
  2955. * Увеличиваем заголовок идетификатора запроса на 1
  2956. */
  2957. headers["X-Request-Id"]++;
  2958. /**
  2959. * We calculate the title with the signature
  2960. * Расчитываем заголовок с сигнатурой
  2961. */
  2962. headers["X-Auth-Signature"] = getSignature(headers, json);
  2963. /**
  2964. * Create a new ajax request
  2965. * Создаем новый AJAX запрос
  2966. */
  2967. let xhr = new XMLHttpRequest;
  2968. /**
  2969. * Indicate the previously saved URL for API queries
  2970. * Указываем ранее сохраненный URL для API запросов
  2971. */
  2972. xhr.open('POST', apiUrl, true);
  2973. /**
  2974. * Add the function to the event change event
  2975. * Добавляем функцию к событию смены статуса запроса
  2976. */
  2977. xhr.onreadystatechange = function() {
  2978. /**
  2979. * If the result of the request is obtained, we call the flask function
  2980. * Если результат запроса получен вызываем колбек функцию
  2981. */
  2982. if(xhr.readyState == 4) {
  2983. callback(xhr.response, pr);
  2984. }
  2985. };
  2986. /**
  2987. * Indicate the type of request
  2988. * Указываем тип запроса
  2989. */
  2990. xhr.responseType = 'json';
  2991. /**
  2992. * We set the request headers
  2993. * Задаем заголовки запроса
  2994. */
  2995. for(let nameHeader in headers) {
  2996. let head = headers[nameHeader];
  2997. xhr.setRequestHeader(nameHeader, head);
  2998. }
  2999. /**
  3000. * Sending a request
  3001. * Отправляем запрос
  3002. */
  3003. xhr.send(json);
  3004. }
  3005.  
  3006. let hideTimeoutProgress = 0;
  3007. /**
  3008. * Hide progress
  3009. *
  3010. * Скрыть прогресс
  3011. */
  3012. function hideProgress(timeout) {
  3013. timeout = timeout || 0;
  3014. clearTimeout(hideTimeoutProgress);
  3015. hideTimeoutProgress = setTimeout(function () {
  3016. scriptMenu.setStatus('');
  3017. }, timeout);
  3018. }
  3019. /**
  3020. * Progress display
  3021. *
  3022. * Отображение прогресса
  3023. */
  3024. function setProgress(text, hide, onclick) {
  3025. scriptMenu.setStatus(text, onclick);
  3026. hide = hide || false;
  3027. if (hide) {
  3028. hideProgress(3000);
  3029. }
  3030. }
  3031.  
  3032. /**
  3033. * Returns the timer value depending on the subscription
  3034. *
  3035. * Возвращает значение таймера в зависимости от подписки
  3036. */
  3037. function getTimer(time, div) {
  3038. let speedDiv = 5;
  3039. if (subEndTime < Date.now()) {
  3040. speedDiv = div || 1.5;
  3041. }
  3042. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3043. }
  3044.  
  3045. /**
  3046. * Calculates HASH MD5 from string
  3047. *
  3048. * Расчитывает HASH MD5 из строки
  3049. *
  3050. * [js-md5]{@link https://github.com/emn178/js-md5}
  3051. *
  3052. * @namespace md5
  3053. * @version 0.7.3
  3054. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3055. * @copyright Chen, Yi-Cyuan 2014-2017
  3056. * @license MIT
  3057. */
  3058. !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 _}))}();
  3059.  
  3060. /**
  3061. * Script for beautiful dialog boxes
  3062. *
  3063. * Скрипт для красивых диалоговых окошек
  3064. */
  3065. const popup = new (function () {
  3066. this.popUp,
  3067. this.downer,
  3068. this.middle,
  3069. this.msgText,
  3070. this.buttons = [];
  3071. this.checkboxes = [];
  3072. this.dialogPromice = null;
  3073.  
  3074. this.init = function () {
  3075. addStyle();
  3076. addBlocks();
  3077. addEventListeners();
  3078. }
  3079.  
  3080. const addEventListeners = () => {
  3081. document.addEventListener('keyup', (e) => {
  3082. if (e.key == 'Escape') {
  3083. if (this.dialogPromice) {
  3084. const { func, result } = this.dialogPromice;
  3085. this.dialogPromice = null;
  3086. popup.hide();
  3087. func(result);
  3088. }
  3089. }
  3090. });
  3091. }
  3092.  
  3093. const addStyle = () => {
  3094. let style = document.createElement('style');
  3095. style.innerText = `
  3096. .PopUp_ {
  3097. position: absolute;
  3098. min-width: 300px;
  3099. max-width: 500px;
  3100. max-height: 600px;
  3101. background-color: #190e08e6;
  3102. z-index: 10001;
  3103. top: 169px;
  3104. left: 345px;
  3105. border: 3px #ce9767 solid;
  3106. border-radius: 10px;
  3107. display: flex;
  3108. flex-direction: column;
  3109. justify-content: space-around;
  3110. padding: 15px 9px;
  3111. box-sizing: border-box;
  3112. }
  3113.  
  3114. .PopUp_back {
  3115. position: absolute;
  3116. background-color: #00000066;
  3117. width: 100%;
  3118. height: 100%;
  3119. z-index: 10000;
  3120. top: 0;
  3121. left: 0;
  3122. }
  3123.  
  3124. .PopUp_close {
  3125. width: 40px;
  3126. height: 40px;
  3127. position: absolute;
  3128. right: -18px;
  3129. top: -18px;
  3130. border: 3px solid #c18550;
  3131. border-radius: 20px;
  3132. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3133. background-position-y: 3px;
  3134. box-shadow: -1px 1px 3px black;
  3135. cursor: pointer;
  3136. box-sizing: border-box;
  3137. }
  3138.  
  3139. .PopUp_close:hover {
  3140. filter: brightness(1.2);
  3141. }
  3142.  
  3143. .PopUp_crossClose {
  3144. width: 100%;
  3145. height: 100%;
  3146. background-size: 65%;
  3147. background-position: center;
  3148. background-repeat: no-repeat;
  3149. 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")
  3150. }
  3151.  
  3152. .PopUp_blocks {
  3153. width: 100%;
  3154. height: 50%;
  3155. display: flex;
  3156. justify-content: space-evenly;
  3157. align-items: center;
  3158. flex-wrap: wrap;
  3159. justify-content: center;
  3160. }
  3161.  
  3162. .PopUp_blocks:last-child {
  3163. margin-top: 25px;
  3164. }
  3165.  
  3166. .PopUp_buttons {
  3167. display: flex;
  3168. margin: 7px 10px;
  3169. flex-direction: column;
  3170. }
  3171.  
  3172. .PopUp_button {
  3173. background-color: #52A81C;
  3174. border-radius: 5px;
  3175. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3176. cursor: pointer;
  3177. padding: 4px 12px 6px;
  3178. }
  3179.  
  3180. .PopUp_input {
  3181. text-align: center;
  3182. font-size: 16px;
  3183. height: 27px;
  3184. border: 1px solid #cf9250;
  3185. border-radius: 9px 9px 0px 0px;
  3186. background: transparent;
  3187. color: #fce1ac;
  3188. padding: 1px 10px;
  3189. box-sizing: border-box;
  3190. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3191. }
  3192.  
  3193. .PopUp_checkboxes {
  3194. display: flex;
  3195. flex-direction: column;
  3196. margin: 15px 15px -5px 15px;
  3197. align-items: flex-start;
  3198. }
  3199.  
  3200. .PopUp_ContCheckbox {
  3201. margin: 2px 0px;
  3202. }
  3203.  
  3204. .PopUp_checkbox {
  3205. position: absolute;
  3206. z-index: -1;
  3207. opacity: 0;
  3208. }
  3209. .PopUp_checkbox+label {
  3210. display: inline-flex;
  3211. align-items: center;
  3212. user-select: none;
  3213.  
  3214. font-size: 15px;
  3215. font-family: sans-serif;
  3216. font-weight: 600;
  3217. font-stretch: condensed;
  3218. letter-spacing: 1px;
  3219. color: #fce1ac;
  3220. text-shadow: 0px 0px 1px;
  3221. }
  3222. .PopUp_checkbox+label::before {
  3223. content: '';
  3224. display: inline-block;
  3225. width: 20px;
  3226. height: 20px;
  3227. border: 1px solid #cf9250;
  3228. border-radius: 7px;
  3229. margin-right: 7px;
  3230. }
  3231. .PopUp_checkbox:checked+label::before {
  3232. 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");
  3233. }
  3234.  
  3235. .PopUp_input::placeholder {
  3236. color: #fce1ac75;
  3237. }
  3238.  
  3239. .PopUp_input:focus {
  3240. outline: 0;
  3241. }
  3242.  
  3243. .PopUp_input + .PopUp_button {
  3244. border-radius: 0px 0px 5px 5px;
  3245. padding: 2px 18px 5px;
  3246. }
  3247.  
  3248. .PopUp_button:hover {
  3249. filter: brightness(1.2);
  3250. }
  3251.  
  3252. .PopUp_button:active {
  3253. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3254. }
  3255.  
  3256. .PopUp_text {
  3257. font-size: 22px;
  3258. font-family: sans-serif;
  3259. font-weight: 600;
  3260. font-stretch: condensed;
  3261. letter-spacing: 1px;
  3262. text-align: center;
  3263. }
  3264.  
  3265. .PopUp_buttonText {
  3266. color: #E4FF4C;
  3267. text-shadow: 0px 1px 2px black;
  3268. }
  3269.  
  3270. .PopUp_msgText {
  3271. color: #FDE5B6;
  3272. text-shadow: 0px 0px 2px;
  3273. }
  3274.  
  3275. .PopUp_hideBlock {
  3276. display: none;
  3277. }
  3278. `;
  3279. document.head.appendChild(style);
  3280. }
  3281.  
  3282. const addBlocks = () => {
  3283. this.back = document.createElement('div');
  3284. this.back.classList.add('PopUp_back');
  3285. this.back.classList.add('PopUp_hideBlock');
  3286. document.body.append(this.back);
  3287.  
  3288. this.popUp = document.createElement('div');
  3289. this.popUp.classList.add('PopUp_');
  3290. this.back.append(this.popUp);
  3291.  
  3292. let upper = document.createElement('div')
  3293. upper.classList.add('PopUp_blocks');
  3294. this.popUp.append(upper);
  3295.  
  3296. this.middle = document.createElement('div')
  3297. this.middle.classList.add('PopUp_blocks');
  3298. this.middle.classList.add('PopUp_checkboxes');
  3299. this.popUp.append(this.middle);
  3300.  
  3301. this.downer = document.createElement('div')
  3302. this.downer.classList.add('PopUp_blocks');
  3303. this.popUp.append(this.downer);
  3304.  
  3305. this.msgText = document.createElement('div');
  3306. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3307. upper.append(this.msgText);
  3308. }
  3309.  
  3310. this.showBack = function () {
  3311. this.back.classList.remove('PopUp_hideBlock');
  3312. }
  3313.  
  3314. this.hideBack = function () {
  3315. this.back.classList.add('PopUp_hideBlock');
  3316. }
  3317.  
  3318. this.show = function () {
  3319. if (this.checkboxes.length) {
  3320. this.middle.classList.remove('PopUp_hideBlock');
  3321. }
  3322. this.showBack();
  3323. this.popUp.classList.remove('PopUp_hideBlock');
  3324. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3325. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3326. }
  3327.  
  3328. this.hide = function () {
  3329. this.hideBack();
  3330. this.popUp.classList.add('PopUp_hideBlock');
  3331. }
  3332.  
  3333. this.addAnyButton = (option) => {
  3334. const contButton = document.createElement('div');
  3335. contButton.classList.add('PopUp_buttons');
  3336. this.downer.append(contButton);
  3337.  
  3338. let inputField = {
  3339. value: option.result || option.default
  3340. }
  3341. if (option.isInput) {
  3342. inputField = document.createElement('input');
  3343. inputField.type = 'text';
  3344. if (option.placeholder) {
  3345. inputField.placeholder = option.placeholder;
  3346. }
  3347. if (option.default) {
  3348. inputField.value = option.default;
  3349. }
  3350. inputField.classList.add('PopUp_input');
  3351. contButton.append(inputField);
  3352. }
  3353.  
  3354. const button = document.createElement('div');
  3355. button.classList.add('PopUp_button');
  3356. button.title = option.title || '';
  3357. contButton.append(button);
  3358.  
  3359. const buttonText = document.createElement('div');
  3360. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  3361. buttonText.innerText = option.msg;
  3362. button.append(buttonText);
  3363.  
  3364. return { button, contButton, inputField };
  3365. }
  3366.  
  3367. this.addCloseButton = () => {
  3368. let button = document.createElement('div')
  3369. button.classList.add('PopUp_close');
  3370. this.popUp.append(button);
  3371.  
  3372. let crossClose = document.createElement('div')
  3373. crossClose.classList.add('PopUp_crossClose');
  3374. button.append(crossClose);
  3375.  
  3376. return { button, contButton: button };
  3377. }
  3378.  
  3379. this.addButton = (option, buttonClick) => {
  3380.  
  3381. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  3382. if (option.isClose) {
  3383. this.dialogPromice = {func: buttonClick, result: option.result};
  3384. }
  3385. button.addEventListener('click', () => {
  3386. let result = '';
  3387. if (option.isInput) {
  3388. result = inputField.value;
  3389. }
  3390. if (option.isClose || option.isCancel) {
  3391. this.dialogPromice = null;
  3392. }
  3393. buttonClick(result);
  3394. });
  3395.  
  3396. this.buttons.push(contButton);
  3397. }
  3398.  
  3399. this.clearButtons = () => {
  3400. while (this.buttons.length) {
  3401. this.buttons.pop().remove();
  3402. }
  3403. }
  3404.  
  3405. this.addCheckBox = (checkBox) => {
  3406. const contCheckbox = document.createElement('div');
  3407. contCheckbox.classList.add('PopUp_ContCheckbox');
  3408. this.middle.append(contCheckbox);
  3409.  
  3410. const checkbox = document.createElement('input');
  3411. checkbox.type = 'checkbox';
  3412. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  3413. checkbox.dataset.name = checkBox.name;
  3414. checkbox.checked = checkBox.checked;
  3415. checkbox.label = checkBox.label;
  3416. checkbox.title = checkBox.title || '';
  3417. checkbox.classList.add('PopUp_checkbox');
  3418. contCheckbox.appendChild(checkbox)
  3419.  
  3420. const checkboxLabel = document.createElement('label');
  3421. checkboxLabel.innerText = checkBox.label;
  3422. checkboxLabel.title = checkBox.title || '';
  3423. checkboxLabel.setAttribute('for', checkbox.id);
  3424. contCheckbox.appendChild(checkboxLabel);
  3425.  
  3426. this.checkboxes.push(checkbox);
  3427. }
  3428.  
  3429. this.clearCheckBox = () => {
  3430. this.middle.classList.add('PopUp_hideBlock');
  3431. while (this.checkboxes.length) {
  3432. this.checkboxes.pop().parentNode.remove();
  3433. }
  3434. }
  3435.  
  3436. this.setMsgText = (text) => {
  3437. this.msgText.innerHTML = text;
  3438. }
  3439.  
  3440. this.getCheckBoxes = () => {
  3441. const checkBoxes = [];
  3442.  
  3443. for (const checkBox of this.checkboxes) {
  3444. checkBoxes.push({
  3445. name: checkBox.dataset.name,
  3446. label: checkBox.label,
  3447. checked: checkBox.checked
  3448. });
  3449. }
  3450.  
  3451. return checkBoxes;
  3452. }
  3453.  
  3454. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  3455. this.clearButtons();
  3456. this.clearCheckBox();
  3457. return new Promise((complete, failed) => {
  3458. this.setMsgText(msg);
  3459. if (!buttOpt) {
  3460. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  3461. }
  3462. for (const checkBox of checkBoxes) {
  3463. this.addCheckBox(checkBox);
  3464. }
  3465. for (let butt of buttOpt) {
  3466. this.addButton(butt, (result) => {
  3467. result = result || butt.result;
  3468. complete(result);
  3469. popup.hide();
  3470. });
  3471. if (butt.isCancel) {
  3472. this.dialogPromice = {func: complete, result: butt.result};
  3473. }
  3474. }
  3475. this.show();
  3476. });
  3477. }
  3478. });
  3479.  
  3480. /**
  3481. * Script control panel
  3482. *
  3483. * Панель управления скриптом
  3484. */
  3485. const scriptMenu = new (function () {
  3486.  
  3487. this.mainMenu,
  3488. this.buttons = [],
  3489. this.checkboxes = [];
  3490. this.option = {
  3491. showMenu: false,
  3492. showDetails: {}
  3493. };
  3494.  
  3495. this.init = function (option = {}) {
  3496. this.option = Object.assign(this.option, option);
  3497. this.option.showDetails = this.loadShowDetails();
  3498. addStyle();
  3499. addBlocks();
  3500. }
  3501.  
  3502. const addStyle = () => {
  3503. style = document.createElement('style');
  3504. style.innerText = `
  3505. .scriptMenu_status {
  3506. position: absolute;
  3507. z-index: 10001;
  3508. /* max-height: 30px; */
  3509. top: -1px;
  3510. left: 30%;
  3511. cursor: pointer;
  3512. border-radius: 0px 0px 10px 10px;
  3513. background: #190e08e6;
  3514. border: 1px #ce9767 solid;
  3515. font-size: 18px;
  3516. font-family: sans-serif;
  3517. font-weight: 600;
  3518. font-stretch: condensed;
  3519. letter-spacing: 1px;
  3520. color: #fce1ac;
  3521. text-shadow: 0px 0px 1px;
  3522. transition: 0.5s;
  3523. padding: 2px 10px 3px;
  3524. }
  3525. .scriptMenu_statusHide {
  3526. top: -35px;
  3527. height: 30px;
  3528. overflow: hidden;
  3529. }
  3530. .scriptMenu_label {
  3531. position: absolute;
  3532. top: 30%;
  3533. left: -4px;
  3534. z-index: 9999;
  3535. cursor: pointer;
  3536. width: 30px;
  3537. height: 30px;
  3538. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  3539. border: 1px solid #1a2f04;
  3540. border-radius: 5px;
  3541. box-shadow:
  3542. inset 0px 2px 4px #83ce26,
  3543. inset 0px -4px 6px #1a2f04,
  3544. 0px 0px 2px black,
  3545. 0px 0px 0px 2px #ce9767;
  3546. }
  3547. .scriptMenu_label:hover {
  3548. filter: brightness(1.2);
  3549. }
  3550. .scriptMenu_arrowLabel {
  3551. width: 100%;
  3552. height: 100%;
  3553. background-size: 75%;
  3554. background-position: center;
  3555. background-repeat: no-repeat;
  3556. 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");
  3557. box-shadow: 0px 1px 2px #000;
  3558. border-radius: 5px;
  3559. filter: drop-shadow(0px 1px 2px #000D);
  3560. }
  3561. .scriptMenu_main {
  3562. position: absolute;
  3563. max-width: 285px;
  3564. z-index: 9999;
  3565. top: 50%;
  3566. transform: translateY(-40%);
  3567. background: #190e08e6;
  3568. border: 1px #ce9767 solid;
  3569. border-radius: 0px 10px 10px 0px;
  3570. border-left: none;
  3571. padding: 5px 10px 5px 5px;
  3572. box-sizing: border-box;
  3573. font-size: 15px;
  3574. font-family: sans-serif;
  3575. font-weight: 600;
  3576. font-stretch: condensed;
  3577. letter-spacing: 1px;
  3578. color: #fce1ac;
  3579. text-shadow: 0px 0px 1px;
  3580. transition: 1s;
  3581. display: flex;
  3582. flex-direction: column;
  3583. flex-wrap: nowrap;
  3584. }
  3585. .scriptMenu_showMenu {
  3586. display: none;
  3587. }
  3588. .scriptMenu_showMenu:checked~.scriptMenu_main {
  3589. left: 0px;
  3590. }
  3591. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  3592. left: -300px;
  3593. }
  3594. .scriptMenu_divInput {
  3595. margin: 2px;
  3596. }
  3597. .scriptMenu_divInputText {
  3598. margin: 2px;
  3599. align-self: center;
  3600. display: flex;
  3601. }
  3602. .scriptMenu_checkbox {
  3603. position: absolute;
  3604. z-index: -1;
  3605. opacity: 0;
  3606. }
  3607. .scriptMenu_checkbox+label {
  3608. display: inline-flex;
  3609. align-items: center;
  3610. user-select: none;
  3611. }
  3612. .scriptMenu_checkbox+label::before {
  3613. content: '';
  3614. display: inline-block;
  3615. width: 20px;
  3616. height: 20px;
  3617. border: 1px solid #cf9250;
  3618. border-radius: 7px;
  3619. margin-right: 7px;
  3620. }
  3621. .scriptMenu_checkbox:checked+label::before {
  3622. 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");
  3623. }
  3624. .scriptMenu_close {
  3625. width: 40px;
  3626. height: 40px;
  3627. position: absolute;
  3628. right: -18px;
  3629. top: -18px;
  3630. border: 3px solid #c18550;
  3631. border-radius: 20px;
  3632. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3633. background-position-y: 3px;
  3634. box-shadow: -1px 1px 3px black;
  3635. cursor: pointer;
  3636. box-sizing: border-box;
  3637. }
  3638. .scriptMenu_close:hover {
  3639. filter: brightness(1.2);
  3640. }
  3641. .scriptMenu_crossClose {
  3642. width: 100%;
  3643. height: 100%;
  3644. background-size: 65%;
  3645. background-position: center;
  3646. background-repeat: no-repeat;
  3647. 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")
  3648. }
  3649. .scriptMenu_button {
  3650. user-select: none;
  3651. border-radius: 5px;
  3652. cursor: pointer;
  3653. padding: 5px 14px 8px;
  3654. margin: 4px;
  3655. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  3656. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3657. }
  3658. .scriptMenu_button:hover {
  3659. filter: brightness(1.2);
  3660. }
  3661. .scriptMenu_button:active {
  3662. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  3663. }
  3664. .scriptMenu_buttonText {
  3665. color: #fce5b7;
  3666. text-shadow: 0px 1px 2px black;
  3667. text-align: center;
  3668. }
  3669. .scriptMenu_header {
  3670. text-align: center;
  3671. align-self: center;
  3672. font-size: 15px;
  3673. margin: 0px 15px;
  3674. }
  3675. .scriptMenu_header a {
  3676. color: #fce5b7;
  3677. text-decoration: none;
  3678. }
  3679. .scriptMenu_InputText {
  3680. text-align: center;
  3681. width: 130px;
  3682. height: 24px;
  3683. border: 1px solid #cf9250;
  3684. border-radius: 9px;
  3685. background: transparent;
  3686. color: #fce1ac;
  3687. padding: 0px 10px;
  3688. box-sizing: border-box;
  3689. }
  3690. .scriptMenu_InputText:focus {
  3691. filter: brightness(1.2);
  3692. outline: 0;
  3693. }
  3694. .scriptMenu_InputText::placeholder {
  3695. color: #fce1ac75;
  3696. }
  3697. .scriptMenu_Summary {
  3698. cursor: pointer;
  3699. margin-left: 7px;
  3700. }
  3701. .scriptMenu_Details {
  3702. align-self: center;
  3703. }
  3704. `;
  3705. document.head.appendChild(style);
  3706. }
  3707.  
  3708. const addBlocks = () => {
  3709. const main = document.createElement('div');
  3710. document.body.appendChild(main);
  3711.  
  3712. this.status = document.createElement('div');
  3713. this.status.classList.add('scriptMenu_status');
  3714. this.setStatus('');
  3715. main.appendChild(this.status);
  3716.  
  3717. const label = document.createElement('label');
  3718. label.classList.add('scriptMenu_label');
  3719. label.setAttribute('for', 'checkbox_showMenu');
  3720. main.appendChild(label);
  3721.  
  3722. const arrowLabel = document.createElement('div');
  3723. arrowLabel.classList.add('scriptMenu_arrowLabel');
  3724. label.appendChild(arrowLabel);
  3725.  
  3726. const checkbox = document.createElement('input');
  3727. checkbox.type = 'checkbox';
  3728. checkbox.id = 'checkbox_showMenu';
  3729. checkbox.checked = this.option.showMenu;
  3730. checkbox.classList.add('scriptMenu_showMenu');
  3731. main.appendChild(checkbox);
  3732.  
  3733. this.mainMenu = document.createElement('div');
  3734. this.mainMenu.classList.add('scriptMenu_main');
  3735. main.appendChild(this.mainMenu);
  3736.  
  3737. const closeButton = document.createElement('label');
  3738. closeButton.classList.add('scriptMenu_close');
  3739. closeButton.setAttribute('for', 'checkbox_showMenu');
  3740. this.mainMenu.appendChild(closeButton);
  3741.  
  3742. const crossClose = document.createElement('div');
  3743. crossClose.classList.add('scriptMenu_crossClose');
  3744. closeButton.appendChild(crossClose);
  3745. }
  3746.  
  3747. this.setStatus = (text, onclick) => {
  3748. if (!text) {
  3749. this.status.classList.add('scriptMenu_statusHide');
  3750. } else {
  3751. this.status.classList.remove('scriptMenu_statusHide');
  3752. this.status.innerHTML = text;
  3753. }
  3754.  
  3755. if (typeof onclick == 'function') {
  3756. this.status.addEventListener("click", onclick, {
  3757. once: true
  3758. });
  3759. }
  3760. }
  3761.  
  3762. /**
  3763. * Adding a text element
  3764. *
  3765. * Добавление текстового элемента
  3766. * @param {String} text text // текст
  3767. * @param {Function} func Click function // функция по клику
  3768. * @param {HTMLDivElement} main parent // родитель
  3769. */
  3770. this.addHeader = (text, func, main) => {
  3771. main = main || this.mainMenu;
  3772. const header = document.createElement('div');
  3773. header.classList.add('scriptMenu_header');
  3774. header.innerHTML = text;
  3775. if (typeof func == 'function') {
  3776. header.addEventListener('click', func);
  3777. }
  3778. main.appendChild(header);
  3779. }
  3780.  
  3781. /**
  3782. * Adding a button
  3783. *
  3784. * Добавление кнопки
  3785. * @param {String} text
  3786. * @param {Function} func
  3787. * @param {String} title
  3788. * @param {HTMLDivElement} main parent // родитель
  3789. */
  3790. this.addButton = (text, func, title, main) => {
  3791. main = main || this.mainMenu;
  3792. const button = document.createElement('div');
  3793. button.classList.add('scriptMenu_button');
  3794. button.title = title;
  3795. button.addEventListener('click', func);
  3796. main.appendChild(button);
  3797.  
  3798. const buttonText = document.createElement('div');
  3799. buttonText.classList.add('scriptMenu_buttonText');
  3800. buttonText.innerText = text;
  3801. button.appendChild(buttonText);
  3802. this.buttons.push(button);
  3803.  
  3804. return button;
  3805. }
  3806.  
  3807. /**
  3808. * Adding checkbox
  3809. *
  3810. * Добавление чекбокса
  3811. * @param {String} label
  3812. * @param {String} title
  3813. * @param {HTMLDivElement} main parent // родитель
  3814. * @returns
  3815. */
  3816. this.addCheckbox = (label, title, main) => {
  3817. main = main || this.mainMenu;
  3818. const divCheckbox = document.createElement('div');
  3819. divCheckbox.classList.add('scriptMenu_divInput');
  3820. divCheckbox.title = title;
  3821. main.appendChild(divCheckbox);
  3822.  
  3823. const checkbox = document.createElement('input');
  3824. checkbox.type = 'checkbox';
  3825. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  3826. checkbox.classList.add('scriptMenu_checkbox');
  3827. divCheckbox.appendChild(checkbox)
  3828.  
  3829. const checkboxLabel = document.createElement('label');
  3830. checkboxLabel.innerText = label;
  3831. checkboxLabel.setAttribute('for', checkbox.id);
  3832. divCheckbox.appendChild(checkboxLabel);
  3833.  
  3834. this.checkboxes.push(checkbox);
  3835. return checkbox;
  3836. }
  3837.  
  3838. /**
  3839. * Adding input field
  3840. *
  3841. * Добавление поля ввода
  3842. * @param {String} title
  3843. * @param {String} placeholder
  3844. * @param {HTMLDivElement} main parent // родитель
  3845. * @returns
  3846. */
  3847. this.addInputText = (title, placeholder, main) => {
  3848. main = main || this.mainMenu;
  3849. const divInputText = document.createElement('div');
  3850. divInputText.classList.add('scriptMenu_divInputText');
  3851. divInputText.title = title;
  3852. main.appendChild(divInputText);
  3853.  
  3854. const newInputText = document.createElement('input');
  3855. newInputText.type = 'text';
  3856. if (placeholder) {
  3857. newInputText.placeholder = placeholder;
  3858. }
  3859. newInputText.classList.add('scriptMenu_InputText');
  3860. divInputText.appendChild(newInputText)
  3861. return newInputText;
  3862. }
  3863.  
  3864. /**
  3865. * Adds a dropdown block
  3866. *
  3867. * Добавляет раскрывающийся блок
  3868. * @param {String} summary
  3869. * @param {String} name
  3870. * @returns
  3871. */
  3872. this.addDetails = (summaryText, name = null) => {
  3873. const details = document.createElement('details');
  3874. details.classList.add('scriptMenu_Details');
  3875. this.mainMenu.appendChild(details);
  3876.  
  3877. const summary = document.createElement('summary');
  3878. summary.classList.add('scriptMenu_Summary');
  3879. summary.innerText = summaryText;
  3880. if (name) {
  3881. const self = this;
  3882. details.open = this.option.showDetails[name];
  3883. details.dataset.name = name;
  3884. summary.addEventListener('click', () => {
  3885. self.option.showDetails[details.dataset.name] = !details.open;
  3886. self.saveShowDetails(self.option.showDetails);
  3887. });
  3888. }
  3889. details.appendChild(summary);
  3890.  
  3891. return details;
  3892. }
  3893.  
  3894. /**
  3895. * Saving the expanded state of the details blocks
  3896. *
  3897. * Сохранение состояния развенутости блоков details
  3898. * @param {*} value
  3899. */
  3900. this.saveShowDetails = (value) => {
  3901. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  3902. }
  3903.  
  3904. /**
  3905. * Loading the state of expanded blocks details
  3906. *
  3907. * Загрузка состояния развенутости блоков details
  3908. * @returns
  3909. */
  3910. this.loadShowDetails = () => {
  3911. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  3912.  
  3913. if (!showDetails) {
  3914. return {};
  3915. }
  3916.  
  3917. try {
  3918. showDetails = JSON.parse(showDetails);
  3919. } catch (e) {
  3920. return {};
  3921. }
  3922.  
  3923. return showDetails;
  3924. }
  3925. });
  3926.  
  3927. /**
  3928. * Пример использования
  3929. scriptMenu.init();
  3930. scriptMenu.addHeader('v1.508');
  3931. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  3932. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  3933. scriptMenu.addInputText('input подсказака');
  3934. */
  3935. /**
  3936. * Game Library
  3937. *
  3938. * Игровая библиотека
  3939. */
  3940. class Library {
  3941. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  3942.  
  3943. constructor() {
  3944. if (!Library.instance) {
  3945. Library.instance = this;
  3946. }
  3947.  
  3948. return Library.instance;
  3949. }
  3950.  
  3951. async load() {
  3952. try {
  3953. await this.getUrlLib();
  3954. console.log(this.defaultLibUrl);
  3955. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  3956. } catch (error) {
  3957. console.error('Не удалось загрузить библиотеку', error)
  3958. }
  3959. }
  3960.  
  3961. async getUrlLib() {
  3962. try {
  3963. const db = new Database('hw_cache', 'cache');
  3964. await db.open();
  3965. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  3966. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  3967. } catch(e) {}
  3968. }
  3969.  
  3970. getData(id) {
  3971. return this.data[id];
  3972. }
  3973. }
  3974.  
  3975. this.lib = new Library();
  3976. /**
  3977. * Database
  3978. *
  3979. * База данных
  3980. */
  3981. class Database {
  3982. constructor(dbName, storeName) {
  3983. this.dbName = dbName;
  3984. this.storeName = storeName;
  3985. this.db = null;
  3986. }
  3987.  
  3988. async open() {
  3989. return new Promise((resolve, reject) => {
  3990. const request = indexedDB.open(this.dbName);
  3991.  
  3992. request.onerror = () => {
  3993. reject(new Error(`Failed to open database ${this.dbName}`));
  3994. };
  3995.  
  3996. request.onsuccess = () => {
  3997. this.db = request.result;
  3998. resolve();
  3999. };
  4000.  
  4001. request.onupgradeneeded = (event) => {
  4002. const db = event.target.result;
  4003. if (!db.objectStoreNames.contains(this.storeName)) {
  4004. db.createObjectStore(this.storeName);
  4005. }
  4006. };
  4007. });
  4008. }
  4009.  
  4010. async set(key, value) {
  4011. return new Promise((resolve, reject) => {
  4012. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4013. const store = transaction.objectStore(this.storeName);
  4014. const request = store.put(value, key);
  4015.  
  4016. request.onerror = () => {
  4017. reject(new Error(`Failed to save value with key ${key}`));
  4018. };
  4019.  
  4020. request.onsuccess = () => {
  4021. resolve();
  4022. };
  4023. });
  4024. }
  4025.  
  4026. async get(key, def) {
  4027. return new Promise((resolve, reject) => {
  4028. const transaction = this.db.transaction([this.storeName], 'readonly');
  4029. const store = transaction.objectStore(this.storeName);
  4030. const request = store.get(key);
  4031.  
  4032. request.onerror = () => {
  4033. resolve(def);
  4034. };
  4035.  
  4036. request.onsuccess = () => {
  4037. resolve(request.result);
  4038. };
  4039. });
  4040. }
  4041.  
  4042. async delete(key) {
  4043. return new Promise((resolve, reject) => {
  4044. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4045. const store = transaction.objectStore(this.storeName);
  4046. const request = store.delete(key);
  4047.  
  4048. request.onerror = () => {
  4049. reject(new Error(`Failed to delete value with key ${key}`));
  4050. };
  4051.  
  4052. request.onsuccess = () => {
  4053. resolve();
  4054. };
  4055. });
  4056. }
  4057. }
  4058.  
  4059. /**
  4060. * Returns the stored value
  4061. *
  4062. * Возвращает сохраненное значение
  4063. */
  4064. function getSaveVal(saveName, def) {
  4065. const result = storage.get(saveName, def);
  4066. return result;
  4067. }
  4068.  
  4069. /**
  4070. * Stores value
  4071. *
  4072. * Сохраняет значение
  4073. */
  4074. function setSaveVal(saveName, value) {
  4075. storage.set(saveName, value);
  4076. }
  4077.  
  4078. /**
  4079. * Database initialization
  4080. *
  4081. * Инициализация базы данных
  4082. */
  4083. const db = new Database(GM_info.script.name, 'settings');
  4084.  
  4085. /**
  4086. * Data store
  4087. *
  4088. * Хранилище данных
  4089. */
  4090. const storage = {
  4091. userId: 0,
  4092. /**
  4093. * Default values
  4094. *
  4095. * Значения по умолчанию
  4096. */
  4097. values: [
  4098. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4099. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4100. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4101. name: GM_info.script.name,
  4102. get: function (key, def) {
  4103. if (key in this.values) {
  4104. return this.values[key];
  4105. }
  4106. return def;
  4107. },
  4108. set: function (key, value) {
  4109. this.values[key] = value;
  4110. db.set(this.userId, this.values).catch(
  4111. e => null
  4112. );
  4113. localStorage[this.name + ':' + key] = value;
  4114. },
  4115. delete: function (key) {
  4116. delete this.values[key];
  4117. db.set(this.userId, this.values);
  4118. delete localStorage[this.name + ':' + key];
  4119. }
  4120. }
  4121.  
  4122. /**
  4123. * Returns all keys from localStorage that start with prefix (for migration)
  4124. *
  4125. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4126. */
  4127. function getAllValuesStartingWith(prefix) {
  4128. const values = [];
  4129. for (let i = 0; i < localStorage.length; i++) {
  4130. const key = localStorage.key(i);
  4131. if (key.startsWith(prefix)) {
  4132. const val = localStorage.getItem(key);
  4133. const keyValue = key.split(':')[1];
  4134. values.push({ key: keyValue, val });
  4135. }
  4136. }
  4137. return values;
  4138. }
  4139.  
  4140. /**
  4141. * Opens or migrates to a database
  4142. *
  4143. * Открывает или мигрирует в базу данных
  4144. */
  4145. async function openOrMigrateDatabase(userId) {
  4146. storage.userId = userId;
  4147. try {
  4148. await db.open();
  4149. } catch(e) {
  4150. return;
  4151. }
  4152. let settings = await db.get(userId, false);
  4153.  
  4154. if (settings) {
  4155. storage.values = settings;
  4156. return;
  4157. }
  4158.  
  4159. const values = getAllValuesStartingWith(GM_info.script.name);
  4160. for (const value of values) {
  4161. let val = null;
  4162. try {
  4163. val = JSON.parse(value.val);
  4164. } catch {
  4165. break;
  4166. }
  4167. storage.values[value.key] = val;
  4168. }
  4169. await db.set(userId, storage.values);
  4170. }
  4171.  
  4172. /**
  4173. * Sending expeditions
  4174. *
  4175. * Отправка экспедиций
  4176. */
  4177. function checkExpedition() {
  4178. return new Promise((resolve, reject) => {
  4179. const expedition = new Expedition(resolve, reject);
  4180. expedition.start();
  4181. });
  4182. }
  4183.  
  4184. class Expedition {
  4185. checkExpedInfo = {
  4186. calls: [
  4187. {
  4188. name: 'expeditionGet',
  4189. args: {},
  4190. ident: 'expeditionGet',
  4191. },
  4192. {
  4193. name: 'heroGetAll',
  4194. args: {},
  4195. ident: 'heroGetAll',
  4196. },
  4197. ],
  4198. };
  4199.  
  4200. constructor(resolve, reject) {
  4201. this.resolve = resolve;
  4202. this.reject = reject;
  4203. }
  4204.  
  4205. async start() {
  4206. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4207.  
  4208. const expedInfo = data.results[0].result.response;
  4209. const dataHeroes = data.results[1].result.response;
  4210. const dataExped = { useHeroes: [], exped: [] };
  4211. const calls = [];
  4212.  
  4213. /**
  4214. * Adding expeditions to collect
  4215. * Добавляем экспедиции для сбора
  4216. */
  4217. let countGet = 0;
  4218. for (var n in expedInfo) {
  4219. const exped = expedInfo[n];
  4220. const dateNow = Date.now() / 1000;
  4221. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4222. countGet++;
  4223. calls.push({
  4224. name: 'expeditionFarm',
  4225. args: { expeditionId: exped.id },
  4226. ident: 'expeditionFarm_' + exped.id,
  4227. });
  4228. } else {
  4229. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4230. }
  4231. if (exped.status == 1) {
  4232. dataExped.exped.push({ id: exped.id, power: exped.power });
  4233. }
  4234. }
  4235. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  4236.  
  4237. /**
  4238. * Putting together a list of heroes
  4239. * Собираем список героев
  4240. */
  4241. const heroesArr = [];
  4242. for (let n in dataHeroes) {
  4243. const hero = dataHeroes[n];
  4244. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4245. let heroPower = hero.power;
  4246. // Лара Крофт * 3
  4247. if (hero.id == 63 && hero.color >= 16) {
  4248. heroPower *= 3;
  4249. }
  4250. heroesArr.push({ id: hero.id, power: heroPower });
  4251. }
  4252. }
  4253.  
  4254. /**
  4255. * Adding expeditions to send
  4256. * Добавляем экспедиции для отправки
  4257. */
  4258. let countSend = 0;
  4259. heroesArr.sort((a, b) => a.power - b.power);
  4260. for (const exped of dataExped.exped) {
  4261. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4262. if (heroesIds && heroesIds.length > 4) {
  4263. for (let q in heroesArr) {
  4264. if (heroesIds.includes(heroesArr[q].id)) {
  4265. delete heroesArr[q];
  4266. }
  4267. }
  4268. countSend++;
  4269. calls.push({
  4270. name: 'expeditionSendHeroes',
  4271. args: {
  4272. expeditionId: exped.id,
  4273. heroes: heroesIds,
  4274. },
  4275. ident: 'expeditionSendHeroes_' + exped.id,
  4276. });
  4277. }
  4278. }
  4279.  
  4280. if (calls.length) {
  4281. await Send({ calls });
  4282. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  4283. return;
  4284. }
  4285.  
  4286. this.end(I18N('EXPEDITIONS_NOTHING'));
  4287. }
  4288.  
  4289. /**
  4290. * Selection of heroes for expeditions
  4291. *
  4292. * Подбор героев для экспедиций
  4293. */
  4294. selectionHeroes(heroes, power) {
  4295. const resultHeroers = [];
  4296. const heroesIds = [];
  4297. for (let q = 0; q < 5; q++) {
  4298. for (let i in heroes) {
  4299. let hero = heroes[i];
  4300. if (heroesIds.includes(hero.id)) {
  4301. continue;
  4302. }
  4303.  
  4304. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4305. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  4306. if (hero.power > need) {
  4307. resultHeroers.push(hero);
  4308. heroesIds.push(hero.id);
  4309. break;
  4310. }
  4311. }
  4312. }
  4313.  
  4314. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  4315. if (summ < power) {
  4316. return false;
  4317. }
  4318. return heroesIds;
  4319. }
  4320.  
  4321. /**
  4322. * Ends expedition script
  4323. *
  4324. * Завершает скрипт экспедиции
  4325. */
  4326. end(msg) {
  4327. setProgress(msg, true);
  4328. this.resolve();
  4329. }
  4330. }
  4331.  
  4332. /**
  4333. * Walkthrough of the dungeon
  4334. *
  4335. * Прохождение подземелья
  4336. */
  4337. function testDungeon() {
  4338. return new Promise((resolve, reject) => {
  4339. const dung = new executeDungeon(resolve, reject);
  4340. const titanit = getInput('countTitanit');
  4341. dung.start(titanit);
  4342. });
  4343. }
  4344.  
  4345. /**
  4346. * Walkthrough of the dungeon
  4347. *
  4348. * Прохождение подземелья
  4349. */
  4350. function executeDungeon(resolve, reject) {
  4351. dungeonActivity = 0;
  4352. maxDungeonActivity = 150;
  4353.  
  4354. titanGetAll = [];
  4355.  
  4356. teams = {
  4357. heroes: [],
  4358. earth: [],
  4359. fire: [],
  4360. neutral: [],
  4361. water: [],
  4362. }
  4363.  
  4364. titanStats = [];
  4365.  
  4366. titansStates = {};
  4367.  
  4368. callsExecuteDungeon = {
  4369. calls: [{
  4370. name: "dungeonGetInfo",
  4371. args: {},
  4372. ident: "dungeonGetInfo"
  4373. }, {
  4374. name: "teamGetAll",
  4375. args: {},
  4376. ident: "teamGetAll"
  4377. }, {
  4378. name: "teamGetFavor",
  4379. args: {},
  4380. ident: "teamGetFavor"
  4381. }, {
  4382. name: "clanGetInfo",
  4383. args: {},
  4384. ident: "clanGetInfo"
  4385. }, {
  4386. name: "titanGetAll",
  4387. args: {},
  4388. ident: "titanGetAll"
  4389. }, {
  4390. name: "inventoryGet",
  4391. args: {},
  4392. ident: "inventoryGet"
  4393. }]
  4394. }
  4395.  
  4396. this.start = function(titanit) {
  4397. maxDungeonActivity = titanit || getInput('countTitanit');
  4398. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  4399. }
  4400.  
  4401. /**
  4402. * Getting data on the dungeon
  4403. *
  4404. * Получаем данные по подземелью
  4405. */
  4406. function startDungeon(e) {
  4407. res = e.results;
  4408. dungeonGetInfo = res[0].result.response;
  4409. if (!dungeonGetInfo) {
  4410. endDungeon('noDungeon', res);
  4411. return;
  4412. }
  4413. teamGetAll = res[1].result.response;
  4414. teamGetFavor = res[2].result.response;
  4415. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  4416. titanGetAll = Object.values(res[4].result.response);
  4417. countPredictionCard = res[5].result.response.consumable[81];
  4418.  
  4419. teams.hero = {
  4420. favor: teamGetFavor.dungeon_hero,
  4421. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  4422. teamNum: 0,
  4423. }
  4424. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  4425. if (heroPet) {
  4426. teams.hero.pet = heroPet;
  4427. }
  4428.  
  4429. teams.neutral = {
  4430. favor: {},
  4431. heroes: getTitanTeam(titanGetAll, 'neutral'),
  4432. teamNum: 0,
  4433. };
  4434. teams.water = {
  4435. favor: {},
  4436. heroes: getTitanTeam(titanGetAll, 'water'),
  4437. teamNum: 0,
  4438. };
  4439. teams.fire = {
  4440. favor: {},
  4441. heroes: getTitanTeam(titanGetAll, 'fire'),
  4442. teamNum: 0,
  4443. };
  4444. teams.earth = {
  4445. favor: {},
  4446. heroes: getTitanTeam(titanGetAll, 'earth'),
  4447. teamNum: 0,
  4448. };
  4449.  
  4450.  
  4451. checkFloor(dungeonGetInfo);
  4452. }
  4453.  
  4454. function getTitanTeam(titans, type) {
  4455. switch (type) {
  4456. case 'neutral':
  4457. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4458. case 'water':
  4459. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  4460. case 'fire':
  4461. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  4462. case 'earth':
  4463. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  4464. }
  4465. }
  4466.  
  4467. function getNeutralTeam() {
  4468. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4469. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4470. }
  4471.  
  4472. function fixTitanTeam(titans) {
  4473. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  4474. return titans;
  4475. }
  4476.  
  4477. /**
  4478. * Checking the floor
  4479. *
  4480. * Проверяем этаж
  4481. */
  4482. async function checkFloor(dungeonInfo) {
  4483. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  4484. saveProgress();
  4485. return;
  4486. }
  4487. // console.log(dungeonInfo, dungeonActivity);
  4488. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4489. if (dungeonActivity >= maxDungeonActivity) {
  4490. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  4491. return;
  4492. }
  4493. titansStates = dungeonInfo.states.titans;
  4494. titanStats = titanObjToArray(titansStates);
  4495. const floorChoices = dungeonInfo.floor.userData;
  4496. const floorType = dungeonInfo.floorType;
  4497. //const primeElement = dungeonInfo.elements.prime;
  4498. if (floorType == "battle") {
  4499. const calls = [];
  4500. for (let teamNum in floorChoices) {
  4501. attackerType = floorChoices[teamNum].attackerType;
  4502. const args = fixTitanTeam(teams[attackerType]);
  4503. if (attackerType == 'neutral') {
  4504. args.heroes = getNeutralTeam();
  4505. }
  4506. if (!args.heroes.length) {
  4507. continue;
  4508. }
  4509. args.teamNum = teamNum;
  4510. calls.push({
  4511. name: "dungeonStartBattle",
  4512. args,
  4513. ident: "body_" + teamNum
  4514. })
  4515. }
  4516. if (!calls.length) {
  4517. endDungeon('endDungeon', 'All Dead');
  4518. return;
  4519. }
  4520. const battleDatas = await Send(JSON.stringify({ calls }))
  4521. .then(e => e.results.map(n => n.result.response))
  4522. const battleResults = [];
  4523. for (n in battleDatas) {
  4524. battleData = battleDatas[n]
  4525. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4526. battleResults.push(await Calc(battleData).then(result => {
  4527. result.teamNum = n;
  4528. result.attackerType = floorChoices[n].attackerType;
  4529. return result;
  4530. }));
  4531. }
  4532. processingPromises(battleResults)
  4533. }
  4534. }
  4535.  
  4536. function processingPromises(results) {
  4537. let selectBattle = results[0];
  4538. if (results.length < 2) {
  4539. // console.log(selectBattle);
  4540. if (!selectBattle.result.win) {
  4541. endDungeon('dungeonEndBattle\n', selectBattle);
  4542. return;
  4543. }
  4544. endBattle(selectBattle);
  4545. return;
  4546. }
  4547.  
  4548. selectBattle = false;
  4549. let bestState = -1000;
  4550. for (const result of results) {
  4551. const recovery = getState(result);
  4552. if (recovery > bestState) {
  4553. bestState = recovery;
  4554. selectBattle = result
  4555. }
  4556. }
  4557. // console.log(selectBattle.teamNum, results);
  4558. if (!selectBattle || bestState <= -1000) {
  4559. endDungeon('dungeonEndBattle\n', results);
  4560. return;
  4561. }
  4562.  
  4563. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  4564. .then(endBattle);
  4565. }
  4566.  
  4567. /**
  4568. * Let's start the fight
  4569. *
  4570. * Начинаем бой
  4571. */
  4572. function startBattle(teamNum, attackerType) {
  4573. return new Promise(function (resolve, reject) {
  4574. args = fixTitanTeam(teams[attackerType]);
  4575. args.teamNum = teamNum;
  4576. if (attackerType == 'neutral') {
  4577. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  4578. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4579. }
  4580. startBattleCall = {
  4581. calls: [{
  4582. name: "dungeonStartBattle",
  4583. args,
  4584. ident: "body"
  4585. }]
  4586. }
  4587. send(JSON.stringify(startBattleCall), resultBattle, {
  4588. resolve,
  4589. teamNum,
  4590. attackerType
  4591. });
  4592. });
  4593. }
  4594. /**
  4595. * Returns the result of the battle in a promise
  4596. *
  4597. * Возращает резульат боя в промис
  4598. */
  4599. function resultBattle(resultBattles, args) {
  4600. battleData = resultBattles.results[0].result.response;
  4601. battleType = "get_tower";
  4602. if (battleData.type == "dungeon_titan") {
  4603. battleType = "get_titan";
  4604. }
  4605. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  4606. BattleCalc(battleData, battleType, function (result) {
  4607. result.teamNum = args.teamNum;
  4608. result.attackerType = args.attackerType;
  4609. args.resolve(result);
  4610. });
  4611. }
  4612. /**
  4613. * Finishing the fight
  4614. *
  4615. * Заканчиваем бой
  4616. */
  4617. async function endBattle(battleInfo) {
  4618. if (battleInfo.result.win) {
  4619. const args = {
  4620. result: battleInfo.result,
  4621. progress: battleInfo.progress,
  4622. }
  4623. if (countPredictionCard > 0) {
  4624. args.isRaid = true;
  4625. } else {
  4626. const timer = getTimer(battleInfo.battleTime);
  4627. console.log(timer);
  4628. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  4629. }
  4630. const calls = [{
  4631. name: "dungeonEndBattle",
  4632. args,
  4633. ident: "body"
  4634. }];
  4635. lastDungeonBattleData = null;
  4636. send(JSON.stringify({ calls }), resultEndBattle);
  4637. } else {
  4638. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  4639. }
  4640. }
  4641.  
  4642. /**
  4643. * Getting and processing battle results
  4644. *
  4645. * Получаем и обрабатываем результаты боя
  4646. */
  4647. function resultEndBattle(e) {
  4648. if ('error' in e) {
  4649. popup.confirm(I18N('ERROR_MSG', {
  4650. name: e.error.name,
  4651. description: e.error.description,
  4652. }));
  4653. endDungeon('errorRequest', e);
  4654. return;
  4655. }
  4656. battleResult = e.results[0].result.response;
  4657. if ('error' in battleResult) {
  4658. endDungeon('errorBattleResult', battleResult);
  4659. return;
  4660. }
  4661. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  4662. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  4663. checkFloor(dungeonGetInfo);
  4664. }
  4665.  
  4666. /**
  4667. * Returns the coefficient of condition of the
  4668. * difference in titanium before and after the battle
  4669. *
  4670. * Возвращает коэффициент состояния титанов после боя
  4671. */
  4672. function getState(result) {
  4673. if (!result.result.win) {
  4674. return -1000;
  4675. }
  4676.  
  4677. let beforeSumFactor = 0;
  4678. const beforeTitans = result.battleData.attackers;
  4679. for (let titanId in beforeTitans) {
  4680. const titan = beforeTitans[titanId];
  4681. const state = titan.state;
  4682. let factor = 1;
  4683. if (state) {
  4684. const hp = state.hp / titan.hp;
  4685. const energy = state.energy / 1e3;
  4686. factor = hp + energy / 20
  4687. }
  4688. beforeSumFactor += factor;
  4689. }
  4690.  
  4691. let afterSumFactor = 0;
  4692. const afterTitans = result.progress[0].attackers.heroes;
  4693. for (let titanId in afterTitans) {
  4694. const titan = afterTitans[titanId];
  4695. const hp = titan.hp / beforeTitans[titanId].hp;
  4696. const energy = titan.energy / 1e3;
  4697. const factor = hp + energy / 20;
  4698. afterSumFactor += factor;
  4699. }
  4700. return afterSumFactor - beforeSumFactor;
  4701. }
  4702.  
  4703. /**
  4704. * Converts an object with IDs to an array with IDs
  4705. *
  4706. * Преобразует объект с идетификаторами в массив с идетификаторами
  4707. */
  4708. function titanObjToArray(obj) {
  4709. let titans = [];
  4710. for (let id in obj) {
  4711. obj[id].id = id;
  4712. titans.push(obj[id]);
  4713. }
  4714. return titans;
  4715. }
  4716.  
  4717. function saveProgress() {
  4718. let saveProgressCall = {
  4719. calls: [{
  4720. name: "dungeonSaveProgress",
  4721. args: {},
  4722. ident: "body"
  4723. }]
  4724. }
  4725. send(JSON.stringify(saveProgressCall), resultEndBattle);
  4726. }
  4727.  
  4728. function endDungeon(reason, info) {
  4729. console.warn(reason, info);
  4730. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  4731. resolve();
  4732. }
  4733. }
  4734.  
  4735. /**
  4736. * Passing the tower
  4737. *
  4738. * Прохождение башни
  4739. */
  4740. function testTower() {
  4741. return new Promise((resolve, reject) => {
  4742. tower = new executeTower(resolve, reject);
  4743. tower.start();
  4744. });
  4745. }
  4746.  
  4747. /**
  4748. * Passing the tower
  4749. *
  4750. * Прохождение башни
  4751. */
  4752. function executeTower(resolve, reject) {
  4753. lastTowerInfo = {};
  4754.  
  4755. scullCoin = 0;
  4756.  
  4757. heroGetAll = [];
  4758.  
  4759. heroesStates = {};
  4760.  
  4761. argsBattle = {
  4762. heroes: [],
  4763. favor: {},
  4764. };
  4765.  
  4766. callsExecuteTower = {
  4767. calls: [{
  4768. name: "towerGetInfo",
  4769. args: {},
  4770. ident: "towerGetInfo"
  4771. }, {
  4772. name: "teamGetAll",
  4773. args: {},
  4774. ident: "teamGetAll"
  4775. }, {
  4776. name: "teamGetFavor",
  4777. args: {},
  4778. ident: "teamGetFavor"
  4779. }, {
  4780. name: "inventoryGet",
  4781. args: {},
  4782. ident: "inventoryGet"
  4783. }, {
  4784. name: "heroGetAll",
  4785. args: {},
  4786. ident: "heroGetAll"
  4787. }]
  4788. }
  4789.  
  4790. buffIds = [
  4791. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  4792. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  4793. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  4794. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  4795. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  4796. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  4797. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  4798. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  4799. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  4800. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4801. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  4802. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  4803. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  4804. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  4805. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  4806. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  4807. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  4808. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4809. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  4810. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  4811. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  4812. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  4813. ]
  4814.  
  4815. this.start = function () {
  4816. send(JSON.stringify(callsExecuteTower), startTower);
  4817. }
  4818.  
  4819. /**
  4820. * Getting data on the Tower
  4821. *
  4822. * Получаем данные по башне
  4823. */
  4824. function startTower(e) {
  4825. res = e.results;
  4826. towerGetInfo = res[0].result.response;
  4827. if (!towerGetInfo) {
  4828. endTower('noTower', res);
  4829. return;
  4830. }
  4831. teamGetAll = res[1].result.response;
  4832. teamGetFavor = res[2].result.response;
  4833. inventoryGet = res[3].result.response;
  4834. heroGetAll = Object.values(res[4].result.response);
  4835.  
  4836. scullCoin = inventoryGet.coin[7] ?? 0;
  4837.  
  4838. argsBattle.favor = teamGetFavor.tower;
  4839. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4840. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  4841. if (pet) {
  4842. argsBattle.pet = pet;
  4843. }
  4844.  
  4845. checkFloor(towerGetInfo);
  4846. }
  4847.  
  4848. function fixHeroesTeam(argsBattle) {
  4849. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  4850. if (fixHeroes.length < 5) {
  4851. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  4852. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  4853. Object.keys(argsBattle.favor).forEach(e => {
  4854. if (!fixHeroes.includes(+e)) {
  4855. delete argsBattle.favor[e];
  4856. }
  4857. })
  4858. }
  4859. argsBattle.heroes = fixHeroes;
  4860. return argsBattle;
  4861. }
  4862.  
  4863. /**
  4864. * Check the floor
  4865. *
  4866. * Проверяем этаж
  4867. */
  4868. function checkFloor(towerInfo) {
  4869. lastTowerInfo = towerInfo;
  4870. maySkipFloor = +towerInfo.maySkipFloor;
  4871. floorNumber = +towerInfo.floorNumber;
  4872. heroesStates = towerInfo.states.heroes;
  4873. floorInfo = towerInfo.floor;
  4874.  
  4875. /**
  4876. * Is there at least one chest open on the floor
  4877. * Открыт ли на этаже хоть один сундук
  4878. */
  4879. isOpenChest = false;
  4880. if (towerInfo.floorType == "chest") {
  4881. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  4882. }
  4883.  
  4884. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  4885. if (floorNumber > 49) {
  4886. if (isOpenChest) {
  4887. endTower('alreadyOpenChest 50 floor', floorNumber);
  4888. return;
  4889. }
  4890. }
  4891. /**
  4892. * If the chest is open and you can skip floors, then move on
  4893. * Если сундук открыт и можно скипать этажи, то переходим дальше
  4894. */
  4895. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  4896. if (isOpenChest) {
  4897. nextOpenChest(floorNumber);
  4898. } else {
  4899. nextChestOpen(floorNumber);
  4900. }
  4901. return;
  4902. }
  4903.  
  4904. // console.log(towerInfo, scullCoin);
  4905. switch (towerInfo.floorType) {
  4906. case "battle":
  4907. if (floorNumber <= maySkipFloor) {
  4908. skipFloor();
  4909. return;
  4910. }
  4911. if (floorInfo.state == 2) {
  4912. nextFloor();
  4913. return;
  4914. }
  4915. startBattle().then(endBattle);
  4916. return;
  4917. case "buff":
  4918. checkBuff(towerInfo);
  4919. return;
  4920. case "chest":
  4921. openChest(floorNumber);
  4922. return;
  4923. default:
  4924. console.log('!', towerInfo.floorType, towerInfo);
  4925. break;
  4926. }
  4927. }
  4928.  
  4929. /**
  4930. * Let's start the fight
  4931. *
  4932. * Начинаем бой
  4933. */
  4934. function startBattle() {
  4935. return new Promise(function (resolve, reject) {
  4936. towerStartBattle = {
  4937. calls: [{
  4938. name: "towerStartBattle",
  4939. args: fixHeroesTeam(argsBattle),
  4940. ident: "body"
  4941. }]
  4942. }
  4943. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  4944. });
  4945. }
  4946. /**
  4947. * Returns the result of the battle in a promise
  4948. *
  4949. * Возращает резульат боя в промис
  4950. */
  4951. function resultBattle(resultBattles, resolve) {
  4952. battleData = resultBattles.results[0].result.response;
  4953. battleType = "get_tower";
  4954. BattleCalc(battleData, battleType, function (result) {
  4955. resolve(result);
  4956. });
  4957. }
  4958. /**
  4959. * Finishing the fight
  4960. *
  4961. * Заканчиваем бой
  4962. */
  4963. function endBattle(battleInfo) {
  4964. if (battleInfo.result.stars >= 3) {
  4965. endBattleCall = {
  4966. calls: [{
  4967. name: "towerEndBattle",
  4968. args: {
  4969. result: battleInfo.result,
  4970. progress: battleInfo.progress,
  4971. },
  4972. ident: "body"
  4973. }]
  4974. }
  4975. send(JSON.stringify(endBattleCall), resultEndBattle);
  4976. } else {
  4977. endTower('towerEndBattle win: false\n', battleInfo);
  4978. }
  4979. }
  4980.  
  4981. /**
  4982. * Getting and processing battle results
  4983. *
  4984. * Получаем и обрабатываем результаты боя
  4985. */
  4986. function resultEndBattle(e) {
  4987. battleResult = e.results[0].result.response;
  4988. if ('error' in battleResult) {
  4989. endTower('errorBattleResult', battleResult);
  4990. return;
  4991. }
  4992. if ('reward' in battleResult) {
  4993. scullCoin += battleResult.reward?.coin[7] ?? 0;
  4994. }
  4995. nextFloor();
  4996. }
  4997.  
  4998. function nextFloor() {
  4999. nextFloorCall = {
  5000. calls: [{
  5001. name: "towerNextFloor",
  5002. args: {},
  5003. ident: "body"
  5004. }]
  5005. }
  5006. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5007. }
  5008.  
  5009. function openChest(floorNumber) {
  5010. floorNumber = floorNumber || 0;
  5011. openChestCall = {
  5012. calls: [{
  5013. name: "towerOpenChest",
  5014. args: {
  5015. num: 2
  5016. },
  5017. ident: "body"
  5018. }]
  5019. }
  5020. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5021. }
  5022.  
  5023. function lastChest() {
  5024. endTower('openChest 50 floor', floorNumber);
  5025. }
  5026.  
  5027. function skipFloor() {
  5028. skipFloorCall = {
  5029. calls: [{
  5030. name: "towerSkipFloor",
  5031. args: {},
  5032. ident: "body"
  5033. }]
  5034. }
  5035. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5036. }
  5037.  
  5038. function checkBuff(towerInfo) {
  5039. buffArr = towerInfo.floor;
  5040. promises = [];
  5041. for (let buff of buffArr) {
  5042. buffInfo = buffIds[buff.id];
  5043. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5044. scullCoin -= buffInfo.cost;
  5045. promises.push(buyBuff(buff.id));
  5046. }
  5047. }
  5048. Promise.all(promises).then(nextFloor);
  5049. }
  5050.  
  5051. function buyBuff(buffId) {
  5052. return new Promise(function (resolve, reject) {
  5053. buyBuffCall = {
  5054. calls: [{
  5055. name: "towerBuyBuff",
  5056. args: {
  5057. buffId
  5058. },
  5059. ident: "body"
  5060. }]
  5061. }
  5062. send(JSON.stringify(buyBuffCall), resolve);
  5063. });
  5064. }
  5065.  
  5066. function checkDataFloor(result) {
  5067. towerInfo = result.results[0].result.response;
  5068. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5069. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5070. }
  5071. if ('tower' in towerInfo) {
  5072. towerInfo = towerInfo.tower;
  5073. }
  5074. if ('skullReward' in towerInfo) {
  5075. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5076. }
  5077. checkFloor(towerInfo);
  5078. }
  5079. /**
  5080. * Getting tower rewards
  5081. *
  5082. * Получаем награды башни
  5083. */
  5084. function farmTowerRewards(reason) {
  5085. let { pointRewards, points } = lastTowerInfo;
  5086. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5087. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5088. if (!farmPoints.length) {
  5089. return;
  5090. }
  5091. let farmTowerRewardsCall = {
  5092. calls: [{
  5093. name: "tower_farmPointRewards",
  5094. args: {
  5095. points: farmPoints
  5096. },
  5097. ident: "tower_farmPointRewards"
  5098. }]
  5099. }
  5100.  
  5101. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5102. farmTowerRewardsCall.calls.push({
  5103. name: "tower_farmSkullReward",
  5104. args: {},
  5105. ident: "tower_farmSkullReward"
  5106. });
  5107. }
  5108.  
  5109. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5110. }
  5111.  
  5112. function fullSkipTower() {
  5113. /**
  5114. * Next chest
  5115. *
  5116. * Следующий сундук
  5117. */
  5118. function nextChest(n) {
  5119. return {
  5120. name: "towerNextChest",
  5121. args: {},
  5122. ident: "group_" + n + "_body"
  5123. }
  5124. }
  5125. /**
  5126. * Open chest
  5127. *
  5128. * Открыть сундук
  5129. */
  5130. function openChest(n) {
  5131. return {
  5132. name: "towerOpenChest",
  5133. args: {
  5134. "num": 2
  5135. },
  5136. ident: "group_" + n + "_body"
  5137. }
  5138. }
  5139.  
  5140. const fullSkipTowerCall = {
  5141. calls: []
  5142. }
  5143.  
  5144. let n = 0;
  5145. for (let i = 0; i < 15; i++) {
  5146. fullSkipTowerCall.calls.push(nextChest(++n));
  5147. fullSkipTowerCall.calls.push(openChest(++n));
  5148. }
  5149.  
  5150. send(JSON.stringify(fullSkipTowerCall), data => {
  5151. data.results[0] = data.results[28];
  5152. checkDataFloor(data);
  5153. });
  5154. }
  5155.  
  5156. function nextChestOpen(floorNumber) {
  5157. const calls = [{
  5158. name: "towerOpenChest",
  5159. args: {
  5160. num: 2
  5161. },
  5162. ident: "towerOpenChest"
  5163. }];
  5164.  
  5165. Send(JSON.stringify({ calls })).then(e => {
  5166. nextOpenChest(floorNumber);
  5167. });
  5168. }
  5169.  
  5170. function nextOpenChest(floorNumber) {
  5171. if (floorNumber > 49) {
  5172. endTower('openChest 50 floor', floorNumber);
  5173. return;
  5174. }
  5175. if (floorNumber == 1) {
  5176. fullSkipTower();
  5177. return;
  5178. }
  5179.  
  5180. let nextOpenChestCall = {
  5181. calls: [{
  5182. name: "towerNextChest",
  5183. args: {},
  5184. ident: "towerNextChest"
  5185. }, {
  5186. name: "towerOpenChest",
  5187. args: {
  5188. num: 2
  5189. },
  5190. ident: "towerOpenChest"
  5191. }]
  5192. }
  5193. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5194. }
  5195.  
  5196. function endTower(reason, info) {
  5197. console.log(reason, info);
  5198. if (reason != 'noTower') {
  5199. farmTowerRewards(reason);
  5200. }
  5201. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5202. resolve();
  5203. }
  5204. }
  5205.  
  5206. /**
  5207. * Passage of the arena of the titans
  5208. *
  5209. * Прохождение арены титанов
  5210. */
  5211. function testTitanArena() {
  5212. return new Promise((resolve, reject) => {
  5213. titAren = new executeTitanArena(resolve, reject);
  5214. titAren.start();
  5215. });
  5216. }
  5217.  
  5218. /**
  5219. * Passage of the arena of the titans
  5220. *
  5221. * Прохождение арены титанов
  5222. */
  5223. function executeTitanArena(resolve, reject) {
  5224. let titan_arena = [];
  5225. let finishListBattle = [];
  5226. /**
  5227. * ID of the current batch
  5228. *
  5229. * Идетификатор текущей пачки
  5230. */
  5231. let currentRival = 0;
  5232. /**
  5233. * Number of attempts to finish off the pack
  5234. *
  5235. * Количество попыток добития пачки
  5236. */
  5237. let attempts = 0;
  5238. /**
  5239. * Was there an attempt to finish off the current shooting range
  5240. *
  5241. * Была ли попытка добития текущего тира
  5242. */
  5243. let isCheckCurrentTier = false;
  5244. /**
  5245. * Current shooting range
  5246. *
  5247. * Текущий тир
  5248. */
  5249. let currTier = 0;
  5250. /**
  5251. * Number of battles on the current dash
  5252. *
  5253. * Количество битв на текущем тире
  5254. */
  5255. let countRivalsTier = 0;
  5256.  
  5257. let callsStart = {
  5258. calls: [{
  5259. name: "titanArenaGetStatus",
  5260. args: {},
  5261. ident: "titanArenaGetStatus"
  5262. }, {
  5263. name: "teamGetAll",
  5264. args: {},
  5265. ident: "teamGetAll"
  5266. }]
  5267. }
  5268.  
  5269. this.start = function () {
  5270. send(JSON.stringify(callsStart), startTitanArena);
  5271. }
  5272.  
  5273. function startTitanArena(data) {
  5274. let titanArena = data.results[0].result.response;
  5275. if (titanArena.status == 'disabled') {
  5276. endTitanArena('disabled', titanArena);
  5277. return;
  5278. }
  5279.  
  5280. let teamGetAll = data.results[1].result.response;
  5281. titan_arena = teamGetAll.titan_arena;
  5282.  
  5283. checkTier(titanArena)
  5284. }
  5285.  
  5286. function checkTier(titanArena) {
  5287. if (titanArena.status == "peace_time") {
  5288. endTitanArena('Peace_time', titanArena);
  5289. return;
  5290. }
  5291. currTier = titanArena.tier;
  5292. if (currTier) {
  5293. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  5294. }
  5295.  
  5296. if (titanArena.status == "completed_tier") {
  5297. titanArenaCompleteTier();
  5298. return;
  5299. }
  5300. /**
  5301. * Checking for the possibility of a raid
  5302. * Проверка на возможность рейда
  5303. */
  5304. if (titanArena.canRaid) {
  5305. titanArenaStartRaid();
  5306. return;
  5307. }
  5308. /**
  5309. * Check was an attempt to achieve the current shooting range
  5310. * Проверка была ли попытка добития текущего тира
  5311. */
  5312. if (!isCheckCurrentTier) {
  5313. checkRivals(titanArena.rivals);
  5314. return;
  5315. }
  5316.  
  5317. endTitanArena('Done or not canRaid', titanArena);
  5318. }
  5319. /**
  5320. * Submit dash information for verification
  5321. *
  5322. * Отправка информации о тире на проверку
  5323. */
  5324. function checkResultInfo(data) {
  5325. let titanArena = data.results[0].result.response;
  5326. checkTier(titanArena);
  5327. }
  5328. /**
  5329. * Finish the current tier
  5330. *
  5331. * Завершить текущий тир
  5332. */
  5333. function titanArenaCompleteTier() {
  5334. isCheckCurrentTier = false;
  5335. let calls = [{
  5336. name: "titanArenaCompleteTier",
  5337. args: {},
  5338. ident: "body"
  5339. }];
  5340. send(JSON.stringify({calls}), checkResultInfo);
  5341. }
  5342. /**
  5343. * Gathering points to be completed
  5344. *
  5345. * Собираем точки которые нужно добить
  5346. */
  5347. function checkRivals(rivals) {
  5348. finishListBattle = [];
  5349. for (let n in rivals) {
  5350. if (rivals[n].attackScore < 250) {
  5351. finishListBattle.push(n);
  5352. }
  5353. }
  5354. console.log('checkRivals', finishListBattle);
  5355. countRivalsTier = finishListBattle.length;
  5356. roundRivals();
  5357. }
  5358. /**
  5359. * Selecting the next point to finish off
  5360. *
  5361. * Выбор следующей точки для добития
  5362. */
  5363. function roundRivals() {
  5364. let countRivals = finishListBattle.length;
  5365. if (!countRivals) {
  5366. /**
  5367. * Whole range checked
  5368. *
  5369. * Весь тир проверен
  5370. */
  5371. isCheckCurrentTier = true;
  5372. titanArenaGetStatus();
  5373. return;
  5374. }
  5375. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  5376. currentRival = finishListBattle.pop();
  5377. attempts = +currentRival;
  5378. // console.log('roundRivals', currentRival);
  5379. titanArenaStartBattle(currentRival);
  5380. }
  5381. /**
  5382. * The start of a solo battle
  5383. *
  5384. * Начало одиночной битвы
  5385. */
  5386. function titanArenaStartBattle(rivalId) {
  5387. let calls = [{
  5388. name: "titanArenaStartBattle",
  5389. args: {
  5390. rivalId: rivalId,
  5391. titans: titan_arena
  5392. },
  5393. ident: "body"
  5394. }];
  5395. send(JSON.stringify({calls}), calcResult);
  5396. }
  5397. /**
  5398. * Calculation of the results of the battle
  5399. *
  5400. * Расчет результатов боя
  5401. */
  5402. function calcResult(data) {
  5403. let battlesInfo = data.results[0].result.response.battle;
  5404. /**
  5405. * If attempts are equal to the current battle number we make
  5406. * Если попытки равны номеру текущего боя делаем прерасчет
  5407. */
  5408. if (attempts == currentRival) {
  5409. preCalcBattle(battlesInfo);
  5410. return;
  5411. }
  5412. /**
  5413. * If there are still attempts, we calculate a new battle
  5414. * Если попытки еще есть делаем расчет нового боя
  5415. */
  5416. if (attempts > 0) {
  5417. attempts--;
  5418. calcBattleResult(battlesInfo)
  5419. .then(resultCalcBattle);
  5420. return;
  5421. }
  5422. /**
  5423. * Otherwise, go to the next opponent
  5424. * Иначе переходим к следующему сопернику
  5425. */
  5426. roundRivals();
  5427. }
  5428. /**
  5429. * Processing the results of the battle calculation
  5430. *
  5431. * Обработка результатов расчета битвы
  5432. */
  5433. function resultCalcBattle(resultBattle) {
  5434. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  5435. /**
  5436. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  5437. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  5438. */
  5439. if (resultBattle.result.win || !attempts) {
  5440. titanArenaEndBattle({
  5441. progress: resultBattle.progress,
  5442. result: resultBattle.result,
  5443. rivalId: resultBattle.battleData.typeId
  5444. });
  5445. return;
  5446. }
  5447. /**
  5448. * If not victory and there are attempts we start a new battle
  5449. * Если не победа и есть попытки начинаем новый бой
  5450. */
  5451. titanArenaStartBattle(resultBattle.battleData.typeId);
  5452. }
  5453. /**
  5454. * Returns the promise of calculating the results of the battle
  5455. *
  5456. * Возращает промис расчета результатов битвы
  5457. */
  5458. function getBattleInfo(battle, isRandSeed) {
  5459. return new Promise(function (resolve) {
  5460. if (isRandSeed) {
  5461. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5462. }
  5463. // console.log(battle.seed);
  5464. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  5465. });
  5466. }
  5467. /**
  5468. * Recalculate battles
  5469. *
  5470. * Прерасчтет битвы
  5471. */
  5472. function preCalcBattle(battle) {
  5473. let actions = [getBattleInfo(battle, false)];
  5474. const countTestBattle = getInput('countTestBattle');
  5475. for (let i = 0; i < countTestBattle; i++) {
  5476. actions.push(getBattleInfo(battle, true));
  5477. }
  5478. Promise.all(actions)
  5479. .then(resultPreCalcBattle);
  5480. }
  5481. /**
  5482. * Processing the results of the battle recalculation
  5483. *
  5484. * Обработка результатов прерасчета битвы
  5485. */
  5486. function resultPreCalcBattle(e) {
  5487. let wins = e.map(n => n.result.win);
  5488. let firstBattle = e.shift();
  5489. let countWin = wins.reduce((w, s) => w + s);
  5490. const countTestBattle = getInput('countTestBattle');
  5491. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  5492. if (countWin > 0) {
  5493. attempts = getInput('countAutoBattle');
  5494. } else {
  5495. attempts = 0;
  5496. }
  5497. resultCalcBattle(firstBattle);
  5498. }
  5499.  
  5500. /**
  5501. * Complete an arena battle
  5502. *
  5503. * Завершить битву на арене
  5504. */
  5505. function titanArenaEndBattle(args) {
  5506. let calls = [{
  5507. name: "titanArenaEndBattle",
  5508. args,
  5509. ident: "body"
  5510. }];
  5511. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  5512. }
  5513.  
  5514. function resultTitanArenaEndBattle(e) {
  5515. let attackScore = e.results[0].result.response.attackScore;
  5516. let numReval = countRivalsTier - finishListBattle.length;
  5517. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  5518. /**
  5519. * TODO: Might need to improve the results.
  5520. * TODO: Возможно стоит сделать улучшение результатов
  5521. */
  5522. // console.log('resultTitanArenaEndBattle', e)
  5523. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  5524. roundRivals();
  5525. }
  5526. /**
  5527. * Arena State
  5528. *
  5529. * Состояние арены
  5530. */
  5531. function titanArenaGetStatus() {
  5532. let calls = [{
  5533. name: "titanArenaGetStatus",
  5534. args: {},
  5535. ident: "body"
  5536. }];
  5537. send(JSON.stringify({calls}), checkResultInfo);
  5538. }
  5539. /**
  5540. * Arena Raid Request
  5541. *
  5542. * Запрос рейда арены
  5543. */
  5544. function titanArenaStartRaid() {
  5545. let calls = [{
  5546. name: "titanArenaStartRaid",
  5547. args: {
  5548. titans: titan_arena
  5549. },
  5550. ident: "body"
  5551. }];
  5552. send(JSON.stringify({calls}), calcResults);
  5553. }
  5554.  
  5555. function calcResults(data) {
  5556. let battlesInfo = data.results[0].result.response;
  5557. let {attackers, rivals} = battlesInfo;
  5558.  
  5559. let promises = [];
  5560. for (let n in rivals) {
  5561. rival = rivals[n];
  5562. promises.push(calcBattleResult({
  5563. attackers: attackers,
  5564. defenders: [rival.team],
  5565. seed: rival.seed,
  5566. typeId: n,
  5567. }));
  5568. }
  5569.  
  5570. Promise.all(promises)
  5571. .then(results => {
  5572. const endResults = {};
  5573. for (let info of results) {
  5574. let id = info.battleData.typeId;
  5575. endResults[id] = {
  5576. progress: info.progress,
  5577. result: info.result,
  5578. }
  5579. }
  5580. titanArenaEndRaid(endResults);
  5581. });
  5582. }
  5583.  
  5584. function calcBattleResult(battleData) {
  5585. return new Promise(function (resolve, reject) {
  5586. BattleCalc(battleData, "get_titanClanPvp", resolve);
  5587. });
  5588. }
  5589.  
  5590. /**
  5591. * Sending Raid Results
  5592. *
  5593. * Отправка результатов рейда
  5594. */
  5595. function titanArenaEndRaid(results) {
  5596. titanArenaEndRaidCall = {
  5597. calls: [{
  5598. name: "titanArenaEndRaid",
  5599. args: {
  5600. results
  5601. },
  5602. ident: "body"
  5603. }]
  5604. }
  5605. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  5606. }
  5607.  
  5608. function checkRaidResults(data) {
  5609. results = data.results[0].result.response.results;
  5610. isSucsesRaid = true;
  5611. for (let i in results) {
  5612. isSucsesRaid &&= (results[i].attackScore >= 250);
  5613. }
  5614.  
  5615. if (isSucsesRaid) {
  5616. titanArenaCompleteTier();
  5617. } else {
  5618. titanArenaGetStatus();
  5619. }
  5620. }
  5621.  
  5622. function titanArenaFarmDailyReward() {
  5623. titanArenaFarmDailyRewardCall = {
  5624. calls: [{
  5625. name: "titanArenaFarmDailyReward",
  5626. args: {},
  5627. ident: "body"
  5628. }]
  5629. }
  5630. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  5631. }
  5632.  
  5633. function endTitanArena(reason, info) {
  5634. if (!['Peace_time', 'disabled'].includes(reason)) {
  5635. titanArenaFarmDailyReward();
  5636. }
  5637. console.log(reason, info);
  5638. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  5639. resolve();
  5640. }
  5641. }
  5642.  
  5643. function hackGame() {
  5644. self = this;
  5645. selfGame = null;
  5646. bindId = 1e9;
  5647. this.libGame = null;
  5648.  
  5649. /**
  5650. * List of correspondence of used classes to their names
  5651. *
  5652. * Список соответствия используемых классов их названиям
  5653. */
  5654. ObjectsList = [
  5655. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  5656. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  5657. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  5658. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  5659. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  5660.  
  5661. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  5662. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  5663. {name:"GameModel", prop:"game.model.GameModel"},
  5664. {name:"CommandManager", prop:"game.command.CommandManager"},
  5665. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  5666. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  5667. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  5668. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  5669. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  5670. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  5671. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  5672. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  5673. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  5674. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  5675. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  5676. {name:"ClipLabelBase", prop:"game.view.gui.components.ClipLabelBase"},
  5677. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  5678. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  5679. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  5680. {name:"SettingToggleButton", prop:"game.mechanics.settings.popup.view.SettingToggleButton"},
  5681. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  5682. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  5683. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  5684. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  5685. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  5686. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  5687. {name:"BattleConfig", prop:"battle.BattleConfig"},
  5688. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  5689. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  5690. { name: "BattleLogEncoder", prop: "battle.log.BattleLogEncoder" },
  5691. { name: "BattleLogReader", prop: "battle.log.BattleLogReader" },
  5692. { name: "PlayerSubscriptionInfoValueObject", prop: "game.model.user.subscription.PlayerSubscriptionInfoValueObject" },
  5693. ];
  5694.  
  5695. /**
  5696. * Contains the game classes needed to write and override game methods
  5697. *
  5698. * Содержит классы игры необходимые для написания и подмены методов игры
  5699. */
  5700. Game = {
  5701. /**
  5702. * Function 'e'
  5703. * Функция 'e'
  5704. */
  5705. bindFunc: function (a, b) {
  5706. if (null == b)
  5707. return null;
  5708. null == b.__id__ && (b.__id__ = bindId++);
  5709. var c;
  5710. null == a.hx__closures__ ? a.hx__closures__ = {} :
  5711. c = a.hx__closures__[b.__id__];
  5712. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  5713. return c
  5714. },
  5715. };
  5716.  
  5717. /**
  5718. * Connects to game objects via the object creation event
  5719. *
  5720. * Подключается к объектам игры через событие создания объекта
  5721. */
  5722. function connectGame() {
  5723. for (let obj of ObjectsList) {
  5724. /**
  5725. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  5726. */
  5727. Object.defineProperty(Object.prototype, obj.prop, {
  5728. set: function (value) {
  5729. if (!selfGame) {
  5730. selfGame = this;
  5731. }
  5732. if (!Game[obj.name]) {
  5733. Game[obj.name] = value;
  5734. }
  5735. // console.log('set ' + obj.prop, this, value);
  5736. this[obj.prop + '_'] = value;
  5737. },
  5738. get: function () {
  5739. // console.log('get ' + obj.prop, this);
  5740. return this[obj.prop + '_'];
  5741. }
  5742. });
  5743. }
  5744. }
  5745.  
  5746. /**
  5747. * Game.BattlePresets
  5748. * @param {bool} a isReplay
  5749. * @param {bool} b autoToggleable
  5750. * @param {bool} c auto On Start
  5751. * @param {object} d config
  5752. * @param {bool} f showBothTeams
  5753. */
  5754. /**
  5755. * Returns the results of the battle to the callback function
  5756. * Возвращает в функцию callback результаты боя
  5757. * @param {*} battleData battle data данные боя
  5758. * @param {*} battleConfig combat configuration type options:
  5759. *
  5760. * тип конфигурации боя варианты:
  5761. *
  5762. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  5763. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  5764. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  5765. *
  5766. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  5767. *
  5768. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  5769. * @param {*} callback функция в которую вернуться результаты боя
  5770. */
  5771. this.BattleCalc = function (battleData, battleConfig, callback) {
  5772. // battleConfig = battleConfig || getBattleType(battleData.type)
  5773. if (!Game.BattlePresets) throw Error('Use connectGame');
  5774. battlePresets = new Game.BattlePresets(!!battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  5775. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  5776. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  5777. const battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  5778. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  5779. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult[getProtoFn(Game.MultiBattleResult, 2)][0]));
  5780. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  5781. const battleTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  5782. callback({
  5783. battleTime,
  5784. battleData,
  5785. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  5786. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  5787. })
  5788. });
  5789. battleInstantPlay.start();
  5790. }
  5791.  
  5792. /**
  5793. * Returns a function with the specified name from the class
  5794. *
  5795. * Возвращает из класса функцию с указанным именем
  5796. * @param {Object} classF Class // класс
  5797. * @param {String} nameF function name // имя функции
  5798. * @param {String} pos name and alias order // порядок имени и псевдонима
  5799. * @returns
  5800. */
  5801. function getF(classF, nameF, pos) {
  5802. pos = pos || false;
  5803. let prop = Object.entries(classF.prototype.__properties__)
  5804. if (!pos) {
  5805. return prop.filter((e) => e[1] == nameF).pop()[0];
  5806. } else {
  5807. return prop.filter((e) => e[0] == nameF).pop()[1];
  5808. }
  5809. }
  5810.  
  5811. /**
  5812. * Returns a function with the specified name from the class
  5813. *
  5814. * Возвращает из класса функцию с указанным именем
  5815. * @param {Object} classF Class // класс
  5816. * @param {String} nameF function name // имя функции
  5817. * @returns
  5818. */
  5819. function getFnP(classF, nameF) {
  5820. let prop = Object.entries(classF.__properties__)
  5821. return prop.filter((e) => e[1] == nameF).pop()[0];
  5822. }
  5823.  
  5824. /**
  5825. * Returns the function name with the specified ordinal from the class
  5826. *
  5827. * Возвращает имя функции с указаным порядковым номером из класса
  5828. * @param {Object} classF Class // класс
  5829. * @param {Number} nF Order number of function // порядковый номер функции
  5830. * @returns
  5831. */
  5832. function getFn(classF, nF) {
  5833. let prop = Object.keys(classF);
  5834. return prop[nF];
  5835. }
  5836.  
  5837. /**
  5838. * Returns the name of the function with the specified serial number from the prototype of the class
  5839. *
  5840. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  5841. * @param {Object} classF Class // класс
  5842. * @param {Number} nF Order number of function // порядковый номер функции
  5843. * @returns
  5844. */
  5845. function getProtoFn(classF, nF) {
  5846. let prop = Object.keys(classF.prototype);
  5847. return prop[nF];
  5848. }
  5849. /**
  5850. * Description of replaced functions
  5851. *
  5852. * Описание подменяемых функций
  5853. */
  5854. replaceFunction = {
  5855. company: function() {
  5856. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  5857. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  5858. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  5859. if (!isChecked('passBattle')) {
  5860. oldSkipMisson.call(this, a, b, c);
  5861. return;
  5862. }
  5863.  
  5864. try {
  5865. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  5866.  
  5867. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](), !1);
  5868. a = new Game.BattleInstantPlay(c, a);
  5869. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  5870. a.start()
  5871. } catch (error) {
  5872. console.error('company', error)
  5873. oldSkipMisson.call(this, a, b, c);
  5874. }
  5875. }
  5876.  
  5877. Game.PlayerMissionData.prototype.P$h = function (a) {
  5878. let GM_2 = getFn(Game.GameModel, 2);
  5879. let GM_P2 = getProtoFn(Game.GameModel, 2);
  5880. let CM_20 = getProtoFn(Game.CommandManager, 20);
  5881. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  5882. let MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5883. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  5884. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  5885. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  5886. }
  5887. },
  5888. tower: function() {
  5889. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  5890. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  5891. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  5892. if (!isChecked('passBattle')) {
  5893. oldSkipTower.call(this, a);
  5894. return;
  5895. }
  5896. try {
  5897. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage,20)](), !1);
  5898. a = new Game.BattleInstantPlay(a, p);
  5899. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  5900. a.start()
  5901. } catch (error) {
  5902. console.error('tower', error)
  5903. oldSkipMisson.call(this, a, b, c);
  5904. }
  5905. }
  5906.  
  5907. Game.PlayerTowerData.prototype.P$h = function (a) {
  5908. const GM_2 = getFnP(Game.GameModel, "get_instance");
  5909. const GM_P2 = getProtoFn(Game.GameModel, 2);
  5910. const CM_29 = getProtoFn(Game.CommandManager, 29);
  5911. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  5912. const MBR_15 = getF(Game.MultiBattleResult, "get_result");
  5913. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  5914. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  5915. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  5916. }
  5917. },
  5918. // skipSelectHero: function() {
  5919. // if (!HOST) throw Error('Use connectGame');
  5920. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  5921. // },
  5922. passBattle: function() {
  5923. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  5924. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  5925. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  5926. if (!isChecked('passBattle')) {
  5927. oldPassBattle.call(this, a);
  5928. return;
  5929. }
  5930. try {
  5931. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  5932. this[getProtoFn(Game.BattlePausePopup, 3)]();
  5933. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  5934. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  5935.  
  5936. 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)])));
  5937. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  5938. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  5939. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]() ?
  5940. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)])) :
  5941. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  5942. );
  5943.  
  5944. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabelBase, 24)]();
  5945. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  5946. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]());
  5947. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]());
  5948. } catch(error) {
  5949. console.error('passBattle', error)
  5950. oldPassBattle.call(this, a);
  5951. }
  5952. }
  5953.  
  5954. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  5955. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  5956. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  5957. if (isChecked('passBattle')) {
  5958. return I18N('BTN_PASS');
  5959. } else {
  5960. return oldFunc.call(this);
  5961. }
  5962. }
  5963. },
  5964. endlessCards: function() {
  5965. let PDD_20 = getProtoFn(Game.PlayerDungeonData, 20);
  5966. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_20];
  5967. Game.PlayerDungeonData.prototype[PDD_20] = function () {
  5968. if (countPredictionCard <= 0) {
  5969. return true;
  5970. } else {
  5971. return oldEndlessCards.call(this);
  5972. }
  5973. }
  5974. },
  5975. speedBattle: function () {
  5976. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  5977. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  5978. Game.BattleController.prototype[get_timeScale] = function () {
  5979. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  5980. if (!speedBattle) {
  5981. return oldSpeedBattle.call(this);
  5982. }
  5983. try {
  5984. const BC_12 = getProtoFn(Game.BattleController, 12);
  5985. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  5986. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  5987. if (this[BC_12][BSM_12][BP_get_value]()) {
  5988. return 0;
  5989. }
  5990. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  5991. const BC_49 = getProtoFn(Game.BattleController, 49);
  5992. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  5993. const BC_14 = getProtoFn(Game.BattleController, 14);
  5994. const BC_3 = getFn(Game.BattleController, 3);
  5995. if (this[BC_12][BSM_2][BP_get_value]()) {
  5996. var a = speedBattle * this[BC_49]();
  5997. } else {
  5998. a = this[BC_12][BSM_1][BP_get_value]();
  5999. const maxSpeed = Math.max(...this[BC_14]);
  6000. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  6001. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  6002. }
  6003. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  6004. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  6005. const DS_23 = getFn(Game.DataStorage, 23);
  6006. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  6007. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  6008. const R_1 = getFn(selfGame.Reflect, 1);
  6009. const BC_1 = getFn(Game.BattleController, 1);
  6010. const get_config = getF(Game.BattlePresets, "get_config");
  6011. 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"));
  6012. return a
  6013. } catch(error) {
  6014. console.error('passBatspeedBattletle', error)
  6015. return oldSpeedBattle.call(this);
  6016. }
  6017. }
  6018. },
  6019.  
  6020. /**
  6021. * Acceleration button without Valkyries favor
  6022. *
  6023. * Кнопка ускорения без Покровительства Валькирий
  6024. */
  6025. battleFastKey: function () {
  6026. const BGM_43 = getProtoFn(Game.BattleGuiMediator, 43);
  6027. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_43];
  6028. Game.BattleGuiMediator.prototype[BGM_43] = function () {
  6029. let flag = true;
  6030. //console.log(flag)
  6031. if (!flag) {
  6032. return oldBattleFastKey.call(this);
  6033. }
  6034. try {
  6035. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  6036. const BGM_10 = getProtoFn(Game.BattleGuiMediator, 10);
  6037. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  6038. this[BGM_9][BPW_0](true);
  6039. this[BGM_10][BPW_0](true);
  6040. } catch (error) {
  6041. console.error(error);
  6042. return oldBattleFastKey.call(this);
  6043. }
  6044. }
  6045. },
  6046. fastSeason: function () {
  6047. const GameNavigator = selfGame["game.screen.navigator.GameNavigator"];
  6048. const oldFuncName = getProtoFn(GameNavigator, 16);
  6049. const newFuncName = getProtoFn(GameNavigator, 14);
  6050. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6051. const newFastSeason = GameNavigator.prototype[newFuncName];
  6052. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6053. if (isChecked('fastSeason')) {
  6054. return newFastSeason.apply(this, [a]);
  6055. } else {
  6056. return oldFastSeason.apply(this, [a, b]);
  6057. }
  6058. }
  6059. },
  6060. ShowChestReward: function () {
  6061. const TitanArtifactChest = selfGame["game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator"];
  6062. const getOpenAmountTitan = getF(TitanArtifactChest, "get_openAmount");
  6063. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6064. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6065. if (correctShowOpenArtifact) {
  6066. correctShowOpenArtifact--;
  6067. return 100;
  6068. }
  6069. return oldGetOpenAmountTitan.call(this);
  6070. }
  6071.  
  6072. const ArtifactChest = selfGame["game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator"];
  6073. const getOpenAmount = getF(ArtifactChest, "get_openAmount");
  6074. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6075. ArtifactChest.prototype[getOpenAmount] = function () {
  6076. if (correctShowOpenArtifact) {
  6077. correctShowOpenArtifact--;
  6078. return 100;
  6079. }
  6080. return oldGetOpenAmount.call(this);
  6081. }
  6082.  
  6083. },
  6084. fixCompany: function () {
  6085. const GameBattleView = selfGame["game.mediator.gui.popup.battle.GameBattleView"];
  6086. const BattleThread = selfGame["game.battle.controller.thread.BattleThread"];
  6087. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6088. const getThread = getF(GameBattleView, 'get_thread');
  6089. const oldFunc = GameBattleView.prototype[getThread];
  6090. GameBattleView.prototype[getThread] = function () {
  6091. return oldFunc.call(this) || {
  6092. [getOnViewDisposed]: async () => { }
  6093. }
  6094. }
  6095. }
  6096. }
  6097.  
  6098. /**
  6099. * Starts replacing recorded functions
  6100. *
  6101. * Запускает замену записанных функций
  6102. */
  6103. this.activateHacks = function () {
  6104. if (!selfGame) throw Error('Use connectGame');
  6105. for (let func in replaceFunction) {
  6106. replaceFunction[func]();
  6107. }
  6108. }
  6109.  
  6110. /**
  6111. * Returns the game object
  6112. *
  6113. * Возвращает объект игры
  6114. */
  6115. this.getSelfGame = function () {
  6116. return selfGame;
  6117. }
  6118.  
  6119. /**
  6120. * Updates game data
  6121. *
  6122. * Обновляет данные игры
  6123. */
  6124. this.refreshGame = function () {
  6125. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6126. try {
  6127. cheats.refreshInventory();
  6128. } catch (e) { }
  6129. }
  6130.  
  6131. /**
  6132. * Update inventory
  6133. *
  6134. * Обновляет инвентарь
  6135. */
  6136. this.refreshInventory = async function () {
  6137. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6138. const GM_0 = getProtoFn(Game.GameModel, 0);
  6139. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  6140. const Player = Game.GameModel[GM_INST]()[GM_0];
  6141. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  6142. Player[P_24].init(await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}').then(e => e.results[0].result.response))
  6143. }
  6144.  
  6145. /**
  6146. * Change the play screen on windowName
  6147. *
  6148. * Сменить экран игры на windowName
  6149. *
  6150. * Possible options:
  6151. *
  6152. * Возможные варианты:
  6153. *
  6154. * 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
  6155. */
  6156. this.goNavigtor = function (windowName) {
  6157. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  6158. let window = mechanicStorage[windowName];
  6159. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  6160. let Game = selfGame['Game'];
  6161. let navigator = getF(Game, "get_navigator")
  6162. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 18)
  6163. let instance = getFnP(Game, 'get_instance');
  6164. Game[instance]()[navigator]()[navigate](window, event);
  6165. }
  6166.  
  6167. /**
  6168. * Move to the sanctuary cheats.goSanctuary()
  6169. *
  6170. * Переместиться в святилище cheats.goSanctuary()
  6171. */
  6172. this.goSanctuary = () => {
  6173. this.goNavigtor("SANCTUARY");
  6174. }
  6175.  
  6176. /**
  6177. * Go to Guild War
  6178. *
  6179. * Перейти к Войне Гильдий
  6180. */
  6181. this.goClanWar = function() {
  6182. let instance = getFnP(Game.GameModel, 'get_instance')
  6183. let player = Game.GameModel[instance]().A;
  6184. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  6185. new clanWarSelect(player).open();
  6186. }
  6187.  
  6188. /**
  6189. * Go to BrawlShop
  6190. *
  6191. * Переместиться в BrawlShop
  6192. */
  6193. this.goBrawlShop = () => {
  6194. const instance = getFnP(Game.GameModel, 'get_instance')
  6195. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6196. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6197. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6198. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6199.  
  6200. const player = Game.GameModel[instance]().A;
  6201. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  6202. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  6203. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  6204. }
  6205.  
  6206. /**
  6207. * Returns all stores from game data
  6208. *
  6209. * Возвращает все магазины из данных игры
  6210. */
  6211. this.getShops = () => {
  6212. const instance = getFnP(Game.GameModel, 'get_instance')
  6213. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  6214. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  6215. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  6216.  
  6217. const player = Game.GameModel[instance]().A;
  6218. return player[P_36][PSD_0][IM_0];
  6219. }
  6220.  
  6221. /**
  6222. * Returns the store from the game data by ID
  6223. *
  6224. * Возвращает магазин из данных игры по идетификатору
  6225. */
  6226. this.getShop = (id) => {
  6227. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  6228. const shops = this.getShops();
  6229. const shop = shops[id]?.[PSDE_4];
  6230. return shop;
  6231. }
  6232.  
  6233. /**
  6234. * Change island map
  6235. *
  6236. * Сменить карту острова
  6237. */
  6238. this.changeIslandMap = (mapId = 2) => {
  6239. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  6240. const GM_0 = getProtoFn(Game.GameModel, 0);
  6241. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 59);
  6242. const Player = Game.GameModel[GameInst]()[GM_0];
  6243. Player[P_59].$({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  6244.  
  6245. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  6246. const navigator = getF(selfGame['Game'], "get_navigator");
  6247. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  6248. }
  6249.  
  6250. /**
  6251. * Game library availability tracker
  6252. *
  6253. * Отслеживание доступности игровой библиотеки
  6254. */
  6255. function checkLibLoad() {
  6256. timeout = setTimeout(() => {
  6257. if (Game.GameModel) {
  6258. changeLib();
  6259. } else {
  6260. checkLibLoad();
  6261. }
  6262. }, 100)
  6263. }
  6264.  
  6265. /**
  6266. * Game library data spoofing
  6267. *
  6268. * Подмена данных игровой библиотеки
  6269. */
  6270. function changeLib() {
  6271. console.log('lib connect');
  6272. const originalStartFunc = Game.GameModel.prototype.start;
  6273. Game.GameModel.prototype.start = function (a, b, c) {
  6274. self.libGame = b.raw;
  6275. try {
  6276. const levels = b.raw.seasonAdventure.level;
  6277. for (const id in levels) {
  6278. const level = levels[id];
  6279. level.clientData.graphics.fogged = level.clientData.graphics.visible
  6280. }
  6281. } catch (e) {
  6282. console.warn(e);
  6283. }
  6284. originalStartFunc.call(this, a, b, c);
  6285. }
  6286. }
  6287.  
  6288. /**
  6289. * Returns the value of a language constant
  6290. *
  6291. * Возвращает значение языковой константы
  6292. * @param {*} langConst language constant // языковая константа
  6293. * @returns
  6294. */
  6295. this.translate = function (langConst) {
  6296. return Game.Translate.translate(langConst);
  6297. }
  6298.  
  6299. connectGame();
  6300. checkLibLoad();
  6301. }
  6302.  
  6303. /**
  6304. * Auto collection of gifts
  6305. *
  6306. * Автосбор подарков
  6307. */
  6308. function getAutoGifts() {
  6309. let valName = 'giftSendIds_' + userInfo.id;
  6310.  
  6311. if (!localStorage['clearGift' + userInfo.id]) {
  6312. localStorage[valName] = '';
  6313. localStorage['clearGift' + userInfo.id] = '+';
  6314. }
  6315.  
  6316. if (!localStorage[valName]) {
  6317. localStorage[valName] = '';
  6318. }
  6319.  
  6320. const now = Date.now();
  6321. const body = JSON.stringify({ now });
  6322. const signature = window['\x73\x69\x67\x6e'](now);
  6323. /**
  6324. * Submit a request to receive gift codes
  6325. *
  6326. * Отправка запроса для получения кодов подарков
  6327. */
  6328. fetch('https://zingery.ru/heroes/getGifts.php', {
  6329. method: 'POST',
  6330. headers: {
  6331. 'X-Request-Signature': signature,
  6332. 'X-Script-Name': GM_info.script.name,
  6333. 'X-Script-Version': GM_info.script.version,
  6334. 'X-Script-Author': GM_info.script.author,
  6335. },
  6336. body
  6337. }).then(
  6338. response => response.json()
  6339. ).then(
  6340. data => {
  6341. let freebieCheckCalls = {
  6342. calls: []
  6343. }
  6344. data.forEach((giftId, n) => {
  6345. if (localStorage[valName].includes(giftId)) return;
  6346. freebieCheckCalls.calls.push({
  6347. name: "registration",
  6348. args: {
  6349. user: { referrer: {} },
  6350. giftId
  6351. },
  6352. context: {
  6353. actionTs: Math.floor(performance.now()),
  6354. cookie: window?.NXAppInfo?.session_id || null
  6355. },
  6356. ident: giftId
  6357. });
  6358. });
  6359.  
  6360. if (!freebieCheckCalls.calls.length) {
  6361. return;
  6362. }
  6363.  
  6364. send(JSON.stringify(freebieCheckCalls), e => {
  6365. let countGetGifts = 0;
  6366. const gifts = [];
  6367. for (check of e.results) {
  6368. gifts.push(check.ident);
  6369. if (check.result.response != null) {
  6370. countGetGifts++;
  6371. }
  6372. }
  6373. const saveGifts = localStorage[valName].split(';');
  6374. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  6375. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  6376. });
  6377. }
  6378. )
  6379. }
  6380.  
  6381. /**
  6382. * To fill the kills in the Forge of Souls
  6383. *
  6384. * Набить килов в горниле душ
  6385. */
  6386. async function bossRatingEvent() {
  6387. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  6388. if (!topGet || !topGet.results[0].result.response[0]) {
  6389. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6390. return;
  6391. }
  6392. const replayId = topGet.results[0].result.response[0].userData.replayId;
  6393. const result = await Send(JSON.stringify({
  6394. calls: [
  6395. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  6396. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  6397. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  6398. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  6399. ]
  6400. }));
  6401. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  6402. if (!bossEventInfo) {
  6403. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6404. return;
  6405. }
  6406. const usedHeroes = bossEventInfo.progress.usedHeroes;
  6407. const party = Object.values(result.results[0].result.response.replay.attackers);
  6408. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  6409. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  6410. const calls = [];
  6411. /**
  6412. * First pack
  6413. *
  6414. * Первая пачка
  6415. */
  6416. const args = {
  6417. heroes: [],
  6418. favor: {}
  6419. }
  6420. for (let hero of party) {
  6421. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  6422. args.pet = hero.id;
  6423. continue;
  6424. }
  6425. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  6426. continue;
  6427. }
  6428. args.heroes.push(hero.id);
  6429. if (hero.favorPetId) {
  6430. args.favor[hero.id] = hero.favorPetId;
  6431. }
  6432. }
  6433. if (args.heroes.length) {
  6434. calls.push({
  6435. name: "bossRatingEvent_startBattle",
  6436. args,
  6437. ident: "body_0"
  6438. });
  6439. }
  6440. /**
  6441. * Other packs
  6442. *
  6443. * Другие пачки
  6444. */
  6445. let heroes = [];
  6446. let count = 1;
  6447. while (heroId = availableHeroes.pop()) {
  6448. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  6449. continue;
  6450. }
  6451. heroes.push(heroId);
  6452. if (heroes.length == 5) {
  6453. calls.push({
  6454. name: "bossRatingEvent_startBattle",
  6455. args: {
  6456. heroes: [...heroes],
  6457. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  6458. },
  6459. ident: "body_" + count
  6460. });
  6461. heroes = [];
  6462. count++;
  6463. }
  6464. }
  6465.  
  6466. if (!calls.length) {
  6467. setProgress(`${I18N('NO_HEROES')}`, true);
  6468. return;
  6469. }
  6470.  
  6471. const resultBattles = await Send(JSON.stringify({ calls }));
  6472. console.log(resultBattles);
  6473. rewardBossRatingEvent();
  6474. }
  6475.  
  6476. /**
  6477. * Collecting Rewards from the Forge of Souls
  6478. *
  6479. * Сбор награды из Горнила Душ
  6480. */
  6481. function rewardBossRatingEvent() {
  6482. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6483. send(rewardBossRatingCall, function (data) {
  6484. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  6485. if (!bossEventInfo) {
  6486. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  6487. return;
  6488. }
  6489.  
  6490. let farmedChests = bossEventInfo.progress.farmedChests;
  6491. let score = bossEventInfo.progress.score;
  6492. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  6493. let revard = bossEventInfo.reward;
  6494.  
  6495. let getRewardCall = {
  6496. calls: []
  6497. }
  6498.  
  6499. let count = 0;
  6500. for (let i = 1; i < 10; i++) {
  6501. if (farmedChests.includes(i)) {
  6502. continue;
  6503. }
  6504. if (score < revard[i].score) {
  6505. break;
  6506. }
  6507. getRewardCall.calls.push({
  6508. name: "bossRatingEvent_getReward",
  6509. args: {
  6510. rewardId: i
  6511. },
  6512. ident: "body_" + i
  6513. });
  6514. count++;
  6515. }
  6516. if (!count) {
  6517. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6518. return;
  6519. }
  6520.  
  6521. send(JSON.stringify(getRewardCall), e => {
  6522. console.log(e);
  6523. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6524. });
  6525. });
  6526. }
  6527.  
  6528. /**
  6529. * Collect Easter eggs and event rewards
  6530. *
  6531. * Собрать пасхалки и награды событий
  6532. */
  6533. function offerFarmAllReward() {
  6534. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  6535. return Send(offerGetAllCall).then((data) => {
  6536. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  6537. if (!offerGetAll.length) {
  6538. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  6539. return;
  6540. }
  6541.  
  6542. const calls = [];
  6543. for (let reward of offerGetAll) {
  6544. calls.push({
  6545. name: "offerFarmReward",
  6546. args: {
  6547. offerId: reward.id
  6548. },
  6549. ident: "offerFarmReward_" + reward.id
  6550. });
  6551. }
  6552.  
  6553. return Send(JSON.stringify({ calls })).then(e => {
  6554. console.log(e);
  6555. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  6556. });
  6557. });
  6558. }
  6559.  
  6560. /**
  6561. * Assemble Outland
  6562. *
  6563. * Собрать запределье
  6564. */
  6565. function getOutland() {
  6566. return new Promise(function (resolve, reject) {
  6567. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  6568. let bosses = e.results[0].result.response;
  6569.  
  6570. let bossRaidOpenChestCall = {
  6571. calls: []
  6572. };
  6573.  
  6574. for (let boss of bosses) {
  6575. if (boss.mayRaid) {
  6576. bossRaidOpenChestCall.calls.push({
  6577. name: "bossRaid",
  6578. args: {
  6579. bossId: boss.id
  6580. },
  6581. ident: "bossRaid_" + boss.id
  6582. });
  6583. bossRaidOpenChestCall.calls.push({
  6584. name: "bossOpenChest",
  6585. args: {
  6586. bossId: boss.id,
  6587. amount: 1,
  6588. starmoney: 0
  6589. },
  6590. ident: "bossOpenChest_" + boss.id
  6591. });
  6592. } else if (boss.chestId == 1) {
  6593. bossRaidOpenChestCall.calls.push({
  6594. name: "bossOpenChest",
  6595. args: {
  6596. bossId: boss.id,
  6597. amount: 1,
  6598. starmoney: 0
  6599. },
  6600. ident: "bossOpenChest_" + boss.id
  6601. });
  6602. }
  6603. }
  6604.  
  6605. if (!bossRaidOpenChestCall.calls.length) {
  6606. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  6607. resolve();
  6608. return;
  6609. }
  6610.  
  6611. send(JSON.stringify(bossRaidOpenChestCall), e => {
  6612. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  6613. resolve();
  6614. });
  6615. });
  6616. });
  6617. }
  6618.  
  6619. /**
  6620. * Collect all rewards
  6621. *
  6622. * Собрать все награды
  6623. */
  6624. function questAllFarm() {
  6625. return new Promise(function (resolve, reject) {
  6626. let questGetAllCall = {
  6627. calls: [{
  6628. name: "questGetAll",
  6629. args: {},
  6630. ident: "body"
  6631. }]
  6632. }
  6633. send(JSON.stringify(questGetAllCall), function (data) {
  6634. let questGetAll = data.results[0].result.response;
  6635. const questAllFarmCall = {
  6636. calls: []
  6637. }
  6638. let number = 0;
  6639. for (let quest of questGetAll) {
  6640. if (quest.id < 1e6 && quest.state == 2) {
  6641. questAllFarmCall.calls.push({
  6642. name: "questFarm",
  6643. args: {
  6644. questId: quest.id
  6645. },
  6646. ident: `group_${number}_body`
  6647. });
  6648. number++;
  6649. }
  6650. }
  6651.  
  6652. if (!questAllFarmCall.calls.length) {
  6653. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6654. resolve();
  6655. return;
  6656. }
  6657.  
  6658. send(JSON.stringify(questAllFarmCall), function (res) {
  6659. console.log(res);
  6660. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  6661. resolve();
  6662. });
  6663. });
  6664. })
  6665. }
  6666.  
  6667. /**
  6668. * Mission auto repeat
  6669. *
  6670. * Автоповтор миссии
  6671. * isStopSendMission = false;
  6672. * isSendsMission = true;
  6673. **/
  6674. this.sendsMission = async function (param) {
  6675. if (isStopSendMission) {
  6676. isSendsMission = false;
  6677. console.log(I18N('STOPPED'));
  6678. setProgress('');
  6679. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  6680. msg: 'Ok',
  6681. result: true
  6682. }, ])
  6683. return;
  6684. }
  6685. lastMissionBattleStart = Date.now();
  6686. let missionStartCall = {
  6687. "calls": [{
  6688. "name": "missionStart",
  6689. "args": lastMissionStart,
  6690. "ident": "body"
  6691. }]
  6692. }
  6693. /**
  6694. * Mission Request
  6695. *
  6696. * Запрос на выполнение мисии
  6697. */
  6698. SendRequest(JSON.stringify(missionStartCall), async e => {
  6699. if (e['error']) {
  6700. isSendsMission = false;
  6701. console.log(e['error']);
  6702. setProgress('');
  6703. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6704. await popup.confirm(msg, [
  6705. {msg: 'Ok', result: true},
  6706. ])
  6707. return;
  6708. }
  6709. /**
  6710. * Mission data calculation
  6711. *
  6712. * Расчет данных мисии
  6713. */
  6714. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  6715. /** missionTimer */
  6716. let timer = getTimer(r.battleTime) + 5;
  6717. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  6718. if (period < timer) {
  6719. timer = timer - period;
  6720. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  6721. }
  6722.  
  6723. let missionEndCall = {
  6724. "calls": [{
  6725. "name": "missionEnd",
  6726. "args": {
  6727. "id": param.id,
  6728. "result": r.result,
  6729. "progress": r.progress
  6730. },
  6731. "ident": "body"
  6732. }]
  6733. }
  6734. /**
  6735. * Mission Completion Request
  6736. *
  6737. * Запрос на завершение миссии
  6738. */
  6739. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  6740. if (e['error']) {
  6741. isSendsMission = false;
  6742. console.log(e['error']);
  6743. setProgress('');
  6744. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  6745. await popup.confirm(msg, [
  6746. {msg: 'Ok', result: true},
  6747. ])
  6748. return;
  6749. }
  6750. r = e.results[0].result.response;
  6751. if (r['error']) {
  6752. isSendsMission = false;
  6753. console.log(r['error']);
  6754. setProgress('');
  6755. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  6756. {msg: 'Ok', result: true},
  6757. ])
  6758. return;
  6759. }
  6760.  
  6761. param.count++;
  6762. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  6763. isStopSendMission = true;
  6764. });
  6765. setTimeout(sendsMission, 1, param);
  6766. });
  6767. })
  6768. });
  6769. }
  6770.  
  6771. /**
  6772. * Opening of russian dolls
  6773. *
  6774. * Открытие матрешек
  6775. */
  6776. async function openRussianDolls(libId, amount) {
  6777. let sum = 0;
  6778. let sumResult = [];
  6779.  
  6780. while (amount) {
  6781. sum += amount;
  6782. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  6783. const calls = [{
  6784. name: "consumableUseLootBox",
  6785. args: { libId, amount },
  6786. ident: "body"
  6787. }];
  6788. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  6789. let newCount = 0;
  6790. for (let n of result) {
  6791. if (n?.consumable && n.consumable[libId]) {
  6792. newCount += n.consumable[libId]
  6793. }
  6794. }
  6795. sumResult = [...sumResult, ...result];
  6796. amount = newCount;
  6797. }
  6798.  
  6799. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  6800. return sumResult;
  6801. }
  6802.  
  6803. /**
  6804. * Collect all mail, except letters with energy and charges of the portal
  6805. *
  6806. * Собрать всю почту, кроме писем с энергией и зарядами портала
  6807. */
  6808. function mailGetAll() {
  6809. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  6810.  
  6811. return Send(getMailInfo).then(dataMail => {
  6812. const letters = dataMail.results[0].result.response.letters;
  6813. const letterIds = lettersFilter(letters);
  6814. if (!letterIds.length) {
  6815. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  6816. return;
  6817. }
  6818.  
  6819. const calls = [
  6820. { name: "mailFarm", args: { letterIds }, ident: "body" }
  6821. ];
  6822.  
  6823. return Send(JSON.stringify({ calls })).then(res => {
  6824. const lettersIds = res.results[0].result.response;
  6825. if (lettersIds) {
  6826. const countLetters = Object.keys(lettersIds).length;
  6827. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  6828. }
  6829. });
  6830. });
  6831. }
  6832.  
  6833. /**
  6834. * Filters received emails
  6835. *
  6836. * Фильтрует получаемые письма
  6837. */
  6838. function lettersFilter(letters) {
  6839. const lettersIds = [];
  6840. for (let l in letters) {
  6841. letter = letters[l];
  6842. const reward = letter.reward;
  6843. if (!reward) {
  6844. continue;
  6845. }
  6846. /**
  6847. * Mail Collection Exceptions
  6848. *
  6849. * Исключения на сбор писем
  6850. */
  6851. const isFarmLetter = !(
  6852. /** Portals // сферы портала */
  6853. (reward?.refillable ? reward.refillable[45] : false) ||
  6854. /** Energy // энергия */
  6855. (reward?.stamina ? reward.stamina : false) ||
  6856. /** accelerating energy gain // ускорение набора энергии */
  6857. (reward?.buff ? true : false) ||
  6858. /** VIP Points // вип очки */
  6859. (reward?.vipPoints ? reward.vipPoints : false) ||
  6860. /** souls of heroes // душы героев */
  6861. (reward?.fragmentHero ? true : false) ||
  6862. /** heroes // герои */
  6863. (reward?.bundleHeroReward ? true : false)
  6864. );
  6865. if (isFarmLetter) {
  6866. lettersIds.push(~~letter.id);
  6867. continue;
  6868. }
  6869. /**
  6870. * Если до окончания годности письма менее 24 часов,
  6871. * то оно собирается не смотря на исключения
  6872. */
  6873. const availableUntil = +letter?.availableUntil;
  6874. if (availableUntil) {
  6875. const maxTimeLeft = 24 * 60 * 60 * 1000;
  6876. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  6877. console.log('Time left:', timeLeft)
  6878. if (timeLeft < maxTimeLeft) {
  6879. lettersIds.push(~~letter.id);
  6880. continue;
  6881. }
  6882. }
  6883. }
  6884. return lettersIds;
  6885. }
  6886.  
  6887. /**
  6888. * Displaying information about the areas of the portal and attempts on the VG
  6889. *
  6890. * Отображение информации о сферах портала и попытках на ВГ
  6891. */
  6892. async function justInfo() {
  6893. return new Promise(async (resolve, reject) => {
  6894. const calls = [{
  6895. name: "userGetInfo",
  6896. args: {},
  6897. ident: "userGetInfo"
  6898. },
  6899. {
  6900. name: "clanWarGetInfo",
  6901. args: {},
  6902. ident: "clanWarGetInfo"
  6903. },
  6904. {
  6905. name: "titanArenaGetStatus",
  6906. args: {},
  6907. ident: "titanArenaGetStatus"
  6908. }];
  6909. const result = await Send(JSON.stringify({ calls }));
  6910. const infos = result.results;
  6911. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  6912. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  6913. const arePointsMax = infos[1].result.response?.arePointsMax;
  6914. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  6915. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  6916.  
  6917. const sanctuaryButton = buttons['goToSanctuary'].button;
  6918. const clanWarButton = buttons['goToClanWar'].button;
  6919. const titansArenaButton = buttons['testTitanArena'].button;
  6920.  
  6921. if (portalSphere.amount) {
  6922. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  6923. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  6924. } else {
  6925. sanctuaryButton.style.color = '';
  6926. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  6927. }
  6928. if (clanWarMyTries && !arePointsMax) {
  6929. clanWarButton.style.color = 'red';
  6930. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  6931. } else {
  6932. clanWarButton.style.color = '';
  6933. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  6934. }
  6935.  
  6936. if (titansLevel < 7 && titansStatus == 'battle') {
  6937. const partColor = Math.floor(125 * titansLevel / 7);
  6938. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  6939. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  6940. } else {
  6941. titansArenaButton.style.color = '';
  6942. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  6943. }
  6944.  
  6945. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  6946. resolve();
  6947. });
  6948. }
  6949.  
  6950. async function getDailyBonus() {
  6951. const dailyBonusInfo = await Send(JSON.stringify({
  6952. calls: [{
  6953. name: "dailyBonusGetInfo",
  6954. args: {},
  6955. ident: "body"
  6956. }]
  6957. })).then(e => e.results[0].result.response);
  6958. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  6959.  
  6960. if (!availableToday) {
  6961. console.log('Уже собрано');
  6962. return;
  6963. }
  6964.  
  6965. const currentVipPoints = +userInfo.vipPoints;
  6966. const dailyBonusStat = lib.getData('dailyBonusStatic');
  6967. const vipInfo = lib.getData('level').vip;
  6968. let currentVipLevel = 0;
  6969. for (let i in vipInfo) {
  6970. vipLvl = vipInfo[i];
  6971. if (currentVipPoints >= vipLvl.vipPoints) {
  6972. currentVipLevel = vipLvl.level;
  6973. }
  6974. }
  6975. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  6976.  
  6977. const calls = [{
  6978. name: "dailyBonusFarm",
  6979. args: {
  6980. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  6981. },
  6982. ident: "body"
  6983. }];
  6984.  
  6985. const result = await Send(JSON.stringify({ calls }));
  6986. if (result.error) {
  6987. console.error(result.error);
  6988. return;
  6989. }
  6990.  
  6991. const reward = result.results[0].result.response;
  6992. const type = Object.keys(reward).pop();
  6993. const itemId = Object.keys(reward[type]).pop();
  6994. const count = reward[type][itemId];
  6995. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  6996.  
  6997. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  6998. }
  6999.  
  7000. async function farmStamina(lootBoxId = 148) {
  7001. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  7002. .then(e => e.results[0].result.response.consumable[148]);
  7003.  
  7004. /** Добавить другие ящики */
  7005. /**
  7006. * 144 - медная шкатулка
  7007. * 145 - бронзовая шкатулка
  7008. * 148 - платиновая шкатулка
  7009. */
  7010. if (!lootBox) {
  7011. setProgress(I18N('NO_BOXES'), true);
  7012. return;
  7013. }
  7014.  
  7015. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  7016. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  7017. { result: false, isClose: true },
  7018. { msg: I18N('BTN_YES'), result: true },
  7019. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  7020. ]);
  7021. if (!+result) {
  7022. return;
  7023. }
  7024.  
  7025. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  7026. maxFarmEnergy = +result;
  7027. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  7028. } else {
  7029. maxFarmEnergy = 0;
  7030. }
  7031.  
  7032. let collectEnergy = 0;
  7033. for (let count = lootBox; count > 0; count--) {
  7034. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  7035. .then(e => e.results[0].result.response[0]);
  7036. if ('stamina' in result) {
  7037. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7038. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  7039. if (!maxFarmEnergy) {
  7040. return;
  7041. }
  7042. collectEnergy += +result.stamina;
  7043. if (collectEnergy >= maxFarmEnergy) {
  7044. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  7045. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  7046. return;
  7047. }
  7048. } else {
  7049. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  7050. console.log(result);
  7051. }
  7052. }
  7053.  
  7054. setProgress(I18N('BOXES_OVER'), true);
  7055. }
  7056.  
  7057. async function fillActive() {
  7058. const data = await Send(JSON.stringify({
  7059. calls: [{
  7060. name: "questGetAll",
  7061. args: {},
  7062. ident: "questGetAll"
  7063. }, {
  7064. name: "inventoryGet",
  7065. args: {},
  7066. ident: "inventoryGet"
  7067. }, {
  7068. name: "clanGetInfo",
  7069. args: {},
  7070. ident: "clanGetInfo"
  7071. }
  7072. ]
  7073. })).then(e => e.results.map(n => n.result.response));
  7074.  
  7075. const quests = data[0];
  7076. const inv = data[1];
  7077. const stat = data[2].stat;
  7078. const maxActive = 2000 - stat.todayItemsActivity;
  7079. if (maxActive <= 0) {
  7080. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  7081. return;
  7082. }
  7083. let countGetActive = 0;
  7084. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  7085. if (quest) {
  7086. countGetActive = 1750 - quest.progress;
  7087. }
  7088. if (countGetActive <= 0) {
  7089. countGetActive = maxActive;
  7090. }
  7091. console.log(countGetActive);
  7092.  
  7093. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  7094. { result: false, isClose: true },
  7095. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  7096. ]));
  7097.  
  7098. if (!countGetActive) {
  7099. return;
  7100. }
  7101.  
  7102. if (countGetActive > maxActive) {
  7103. countGetActive = maxActive;
  7104. }
  7105.  
  7106. const items = lib.getData('inventoryItem');
  7107.  
  7108. let itemsInfo = [];
  7109. for (let type of ['gear', 'scroll']) {
  7110. for (let i in inv[type]) {
  7111. const v = items[type][i]?.enchantValue || 0;
  7112. itemsInfo.push({
  7113. id: i,
  7114. count: inv[type][i],
  7115. v,
  7116. type
  7117. })
  7118. }
  7119. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  7120. for (let i in inv[invType]) {
  7121. const v = items[type][i]?.fragmentEnchantValue || 0;
  7122. itemsInfo.push({
  7123. id: i,
  7124. count: inv[invType][i],
  7125. v,
  7126. type: invType
  7127. })
  7128. }
  7129. }
  7130. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  7131. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  7132. console.log(itemsInfo);
  7133. const activeItem = itemsInfo.shift();
  7134. console.log(activeItem);
  7135. const countItem = Math.ceil(countGetActive / activeItem.v);
  7136. if (countItem > activeItem.count) {
  7137. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  7138. console.log(activeItem);
  7139. return;
  7140. }
  7141.  
  7142. await Send(JSON.stringify({
  7143. calls: [{
  7144. name: "clanItemsForActivity",
  7145. args: {
  7146. items: {
  7147. [activeItem.type]: {
  7148. [activeItem.id]: countItem
  7149. }
  7150. }
  7151. },
  7152. ident: "body"
  7153. }]
  7154. })).then(e => {
  7155. /** TODO: Вывести потраченые предметы */
  7156. console.log(e);
  7157. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  7158. });
  7159. }
  7160.  
  7161. async function buyHeroFragments() {
  7162. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  7163. .then(e => e.results.map(n => n.result.response));
  7164. const inv = result[0];
  7165. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  7166. const calls = [];
  7167.  
  7168. for (let shop of shops) {
  7169. const slots = Object.values(shop.slots);
  7170. for (const slot of slots) {
  7171. /* Уже куплено */
  7172. if (slot.bought) {
  7173. continue;
  7174. }
  7175. /* Не душа героя */
  7176. if (!('fragmentHero' in slot.reward)) {
  7177. continue;
  7178. }
  7179. const coin = Object.keys(slot.cost).pop();
  7180. const coinId = Object.keys(slot.cost[coin]).pop();
  7181. const stock = inv[coin][coinId] || 0;
  7182. /* Не хватает на покупку */
  7183. if (slot.cost[coin][coinId] > stock) {
  7184. continue;
  7185. }
  7186. inv[coin][coinId] -= slot.cost[coin][coinId];
  7187. calls.push({
  7188. name: "shopBuy",
  7189. args: {
  7190. shopId: shop.id,
  7191. slot: slot.id,
  7192. cost: slot.cost,
  7193. reward: slot.reward,
  7194. },
  7195. ident: `shopBuy_${shop.id}_${slot.id}`,
  7196. })
  7197. }
  7198. }
  7199.  
  7200. if (!calls.length) {
  7201. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  7202. return;
  7203. }
  7204.  
  7205. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7206. if (!bought) {
  7207. console.log('что-то пошло не так')
  7208. return;
  7209. }
  7210.  
  7211. let countHeroSouls = 0;
  7212. for (const buy of bought) {
  7213. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  7214. }
  7215. console.log(countHeroSouls, bought, calls);
  7216. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  7217. }
  7218.  
  7219. /** Открыть платные сундуки в Запределье за 90 */
  7220. async function bossOpenChestPay() {
  7221. const info = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"userGetInfo"},{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}')
  7222. .then(e => e.results.map(n => n.result.response));
  7223.  
  7224. const user = info[0];
  7225. const boses = info[1];
  7226.  
  7227. const currentStarMoney = user.starMoney;
  7228. if (currentStarMoney < 540) {
  7229. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney }), true);
  7230. return;
  7231. }
  7232.  
  7233. const calls = [];
  7234.  
  7235. let n = 0;
  7236. const amount = 1;
  7237. for (let boss of boses) {
  7238. const bossId = boss.id;
  7239. if (boss.chestNum != 2) {
  7240. continue;
  7241. }
  7242. for (const starmoney of [90, 90, 0]) {
  7243. calls.push({
  7244. name: "bossOpenChest",
  7245. args: {
  7246. bossId,
  7247. amount,
  7248. starmoney
  7249. },
  7250. ident: "bossOpenChest_" + (++n)
  7251. });
  7252. }
  7253. }
  7254.  
  7255. if (!calls.length) {
  7256. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7257. return;
  7258. }
  7259.  
  7260. const result = await Send(JSON.stringify({ calls }));
  7261. console.log(result);
  7262. if (result?.results) {
  7263. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ` + result.results.length, true);
  7264. } else {
  7265. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  7266. }
  7267. }
  7268.  
  7269. async function autoRaidAdventure() {
  7270. const calls = [
  7271. {
  7272. name: "userGetInfo",
  7273. args: {},
  7274. ident: "userGetInfo"
  7275. },
  7276. {
  7277. name: "adventure_raidGetInfo",
  7278. args: {},
  7279. ident: "adventure_raidGetInfo"
  7280. }
  7281. ];
  7282. const result = await Send(JSON.stringify({ calls }))
  7283. .then(e => e.results.map(n => n.result.response));
  7284.  
  7285. const portalSphere = result[0].refillable.find(n => n.id == 45);
  7286. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  7287. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  7288.  
  7289. if (!portalSphere.amount || !adventureId) {
  7290. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  7291. return;
  7292. }
  7293.  
  7294. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  7295. { result: false, isClose: true },
  7296. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  7297. ]));
  7298.  
  7299. if (!countRaid) {
  7300. return;
  7301. }
  7302.  
  7303. if (countRaid > portalSphere.amount) {
  7304. countRaid = portalSphere.amount;
  7305. }
  7306.  
  7307. const resultRaid = await Send(JSON.stringify({
  7308. calls: [...Array(countRaid)].map((e, i) => ({
  7309. name: "adventure_raid",
  7310. args: {
  7311. adventureId
  7312. },
  7313. ident: `body_${i}`
  7314. }))
  7315. })).then(e => e.results.map(n => n.result.response));
  7316.  
  7317. if (!resultRaid.length) {
  7318. console.log(resultRaid);
  7319. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  7320. return;
  7321. }
  7322.  
  7323. console.log(resultRaid, adventureId, portalSphere.amount);
  7324. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  7325. }
  7326.  
  7327. /** Вывести всю клановую статистику в консоль браузера */
  7328. async function clanStatistic() {
  7329. const copy = function (text) {
  7330. const copyTextarea = document.createElement("textarea");
  7331. copyTextarea.style.opacity = "0";
  7332. copyTextarea.textContent = text;
  7333. document.body.appendChild(copyTextarea);
  7334. copyTextarea.select();
  7335. document.execCommand("copy");
  7336. document.body.removeChild(copyTextarea);
  7337. delete copyTextarea;
  7338. }
  7339. const calls = [
  7340. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  7341. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  7342. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  7343. ];
  7344.  
  7345. const result = await Send(JSON.stringify({ calls }));
  7346.  
  7347. const dataClanInfo = result.results[0].result.response;
  7348. const dataClanStat = result.results[1].result.response;
  7349. const dataClanLog = result.results[2].result.response;
  7350.  
  7351. const membersStat = {};
  7352. for (let i = 0; i < dataClanStat.stat.length; i++) {
  7353. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  7354. }
  7355.  
  7356. const joinStat = {};
  7357. historyLog = dataClanLog.history;
  7358. for (let j in historyLog) {
  7359. his = historyLog[j];
  7360. if (his.event == 'join') {
  7361. joinStat[his.userId] = his.ctime;
  7362. }
  7363. }
  7364.  
  7365. const infoArr = [];
  7366. const members = dataClanInfo.clan.members;
  7367. for (let n in members) {
  7368. var member = [
  7369. n,
  7370. members[n].name,
  7371. members[n].level,
  7372. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  7373. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  7374. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  7375. membersStat[n].activity.reverse().join('\t'),
  7376. membersStat[n].adventureStat.reverse().join('\t'),
  7377. membersStat[n].clanGifts.reverse().join('\t'),
  7378. membersStat[n].clanWarStat.reverse().join('\t'),
  7379. membersStat[n].dungeonActivity.reverse().join('\t'),
  7380. ];
  7381. infoArr.push(member);
  7382. }
  7383. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  7384. console.log(info);
  7385. copy(info);
  7386. setProgress(I18N('CLAN_STAT_COPY'), true);
  7387. }
  7388.  
  7389. async function buyInStoreForGold() {
  7390. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  7391. const shops = result[0];
  7392. const user = result[1];
  7393. let gold = user.gold;
  7394. const calls = [];
  7395. if (shops[17]) {
  7396. const slots = shops[17].slots;
  7397. for (let i = 1; i <= 2; i++) {
  7398. if (!slots[i].bought) {
  7399. const costGold = slots[i].cost.gold;
  7400. if ((gold - costGold) < 0) {
  7401. continue;
  7402. }
  7403. gold -= costGold;
  7404. calls.push({
  7405. name: "shopBuy",
  7406. args: {
  7407. shopId: 17,
  7408. slot: i,
  7409. cost: slots[i].cost,
  7410. reward: slots[i].reward,
  7411. },
  7412. ident: 'body_' + i,
  7413. })
  7414. }
  7415. }
  7416. }
  7417. const slots = shops[1].slots;
  7418. for (let i = 4; i <= 6; i++) {
  7419. if (!slots[i].bought && slots[i]?.cost?.gold) {
  7420. const costGold = slots[i].cost.gold;
  7421. if ((gold - costGold) < 0) {
  7422. continue;
  7423. }
  7424. gold -= costGold;
  7425. calls.push({
  7426. name: "shopBuy",
  7427. args: {
  7428. shopId: 1,
  7429. slot: i,
  7430. cost: slots[i].cost,
  7431. reward: slots[i].reward,
  7432. },
  7433. ident: 'body_' + i,
  7434. })
  7435. }
  7436. }
  7437.  
  7438. if (!calls.length) {
  7439. setProgress(I18N('NOTHING_BUY'), true);
  7440. return;
  7441. }
  7442.  
  7443. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  7444. console.log(resultBuy);
  7445. const countBuy = resultBuy.length;
  7446. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  7447. }
  7448.  
  7449. function rewardsAndMailFarm() {
  7450. return new Promise(function (resolve, reject) {
  7451. let questGetAllCall = {
  7452. calls: [{
  7453. name: "questGetAll",
  7454. args: {},
  7455. ident: "questGetAll"
  7456. }, {
  7457. name: "mailGetAll",
  7458. args: {},
  7459. ident: "mailGetAll"
  7460. }]
  7461. }
  7462. send(JSON.stringify(questGetAllCall), function (data) {
  7463. if (!data) return;
  7464. let questGetAll = data.results[0].result.response.filter(e => e.state == 2);
  7465. const questBattlePass = lib.getData('quest').battlePass;
  7466. const questChainBPass = lib.getData('battlePass').questChain;
  7467.  
  7468. const questAllFarmCall = {
  7469. calls: []
  7470. }
  7471. let number = 0;
  7472. for (let quest of questGetAll) {
  7473. if (quest.id > 2e7) {
  7474. continue;
  7475. }
  7476. if (quest.id > 1e6) {
  7477. const questInfo = questBattlePass[quest.id];
  7478. const chain = questChainBPass[questInfo.chain];
  7479. if (chain.requirement?.battlePassTicket) {
  7480. continue;
  7481. }
  7482. }
  7483. questAllFarmCall.calls.push({
  7484. name: "questFarm",
  7485. args: {
  7486. questId: quest.id
  7487. },
  7488. ident: `questFarm_${number}`
  7489. });
  7490. number++;
  7491. }
  7492.  
  7493. let letters = data?.results[1]?.result?.response?.letters;
  7494. letterIds = lettersFilter(letters);
  7495.  
  7496. if (letterIds.length) {
  7497. questAllFarmCall.calls.push({
  7498. name: "mailFarm",
  7499. args: { letterIds },
  7500. ident: "mailFarm"
  7501. })
  7502. }
  7503.  
  7504. if (!questAllFarmCall.calls.length) {
  7505. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7506. resolve();
  7507. return;
  7508. }
  7509.  
  7510. send(JSON.stringify(questAllFarmCall), function (res) {
  7511. let reSend = false;
  7512. let countQuests = 0;
  7513. let countMail = 0;
  7514. for (let call of res.results) {
  7515. if (call.ident.includes('questFarm')) {
  7516. countQuests++;
  7517. } else {
  7518. countMail = Object.keys(call.result.response).length;
  7519. }
  7520.  
  7521. /** TODO: Переписать чтоб не вызывать функцию дважды */
  7522. const newQuests = call.result.newQuests;
  7523. if (newQuests) {
  7524. for (let quest of newQuests) {
  7525. if (quest.id < 1e6 && quest.state == 2) {
  7526. reSend = true;
  7527. }
  7528. }
  7529. }
  7530. }
  7531. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  7532. if (reSend) {
  7533. rewardsAndMailFarm()
  7534. }
  7535. resolve();
  7536. });
  7537. });
  7538. })
  7539. }
  7540.  
  7541. class epicBrawl {
  7542. timeout = null;
  7543. time = null;
  7544.  
  7545. constructor() {
  7546. if (epicBrawl.inst) {
  7547. return epicBrawl.inst;
  7548. }
  7549. epicBrawl.inst = this;
  7550. return this;
  7551. }
  7552.  
  7553. runTimeout(func, timeDiff) {
  7554. const worker = new Worker(URL.createObjectURL(new Blob([`
  7555. self.onmessage = function(e) {
  7556. const timeDiff = e.data;
  7557.  
  7558. if (timeDiff > 0) {
  7559. setTimeout(() => {
  7560. self.postMessage(1);
  7561. self.close();
  7562. }, timeDiff);
  7563. }
  7564. };
  7565. `])));
  7566. worker.postMessage(timeDiff);
  7567. worker.onmessage = () => {
  7568. func();
  7569. };
  7570. return true;
  7571. }
  7572.  
  7573. timeDiff(date1, date2) {
  7574. const date1Obj = new Date(date1);
  7575. const date2Obj = new Date(date2);
  7576.  
  7577. const timeDiff = Math.abs(date2Obj - date1Obj);
  7578.  
  7579. const totalSeconds = timeDiff / 1000;
  7580. const minutes = Math.floor(totalSeconds / 60);
  7581. const seconds = Math.floor(totalSeconds % 60);
  7582.  
  7583. const formattedMinutes = String(minutes).padStart(2, '0');
  7584. const formattedSeconds = String(seconds).padStart(2, '0');
  7585.  
  7586. return `${formattedMinutes}:${formattedSeconds}`;
  7587. }
  7588.  
  7589. check() {
  7590. console.log(new Date(this.time))
  7591. if (Date.now() > this.time) {
  7592. this.timeout = null;
  7593. this.start()
  7594. return;
  7595. }
  7596. this.timeout = this.runTimeout(() => this.check(), 6e4);
  7597. return this.timeDiff(this.time, Date.now())
  7598. }
  7599.  
  7600. async start() {
  7601. if (this.timeout) {
  7602. const time = this.timeDiff(this.time, Date.now());
  7603. console.log(new Date(this.time))
  7604. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  7605. return;
  7606. }
  7607. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  7608. 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));
  7609. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  7610. this.time = (refill.lastRefill + 3600) * 1000
  7611. const attempts = refill.amount;
  7612. if (!attempts) {
  7613. console.log(new Date(this.time));
  7614. const time = this.check();
  7615. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  7616. return;
  7617. }
  7618.  
  7619. if (!teamInfo[0].epic_brawl) {
  7620. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  7621. return;
  7622. }
  7623.  
  7624. const args = {
  7625. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  7626. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  7627. favor: teamInfo[1].epic_brawl,
  7628. }
  7629.  
  7630. let wins = 0;
  7631. let coins = 0;
  7632. let streak = { progress: 0, nextStage: 0 };
  7633. for (let i = attempts; i > 0; i--) {
  7634. const info = await Send(JSON.stringify({
  7635. calls: [
  7636. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  7637. ]
  7638. })).then(e => e.results.map(n => n.result.response));
  7639.  
  7640. const { progress, result } = await Calc(info[1].battle);
  7641. 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));
  7642.  
  7643. const resultInfo = endResult[0].result;
  7644. streak = endResult[1];
  7645.  
  7646. wins += resultInfo.win;
  7647. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  7648.  
  7649. console.log(endResult[0].result)
  7650. if (endResult[1].progress == endResult[1].nextStage) {
  7651. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  7652. coins += farm.coin[39];
  7653. }
  7654.  
  7655. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7656. i, wins, attempts, coins,
  7657. progress: streak.progress,
  7658. nextStage: streak.nextStage,
  7659. end: '',
  7660. }), false, hideProgress);
  7661. }
  7662.  
  7663. console.log(new Date(this.time));
  7664. const time = this.check();
  7665. setProgress(I18N('EPIC_BRAWL_RESULT', {
  7666. wins, attempts, coins,
  7667. i: '',
  7668. progress: streak.progress,
  7669. nextStage: streak.nextStage,
  7670. end: I18N('ATTEMPT_ENDED', { time }),
  7671. }), false, hideProgress);
  7672. }
  7673. }
  7674.  
  7675. function countdownTimer(seconds, message) {
  7676. message = message || I18N('TIMER');
  7677. const stopTimer = Date.now() + seconds * 1e3
  7678. return new Promise(resolve => {
  7679. const interval = setInterval(async () => {
  7680. const now = Date.now();
  7681. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  7682. if (now > stopTimer) {
  7683. clearInterval(interval);
  7684. setProgress('', 1);
  7685. resolve();
  7686. }
  7687. }, 100);
  7688. });
  7689. }
  7690.  
  7691. /** Набить килов в горниле душк */
  7692. async function bossRatingEventSouls() {
  7693. const data = await Send({
  7694. calls: [
  7695. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  7696. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  7697. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7698. ]
  7699. });
  7700. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  7701. if (!bossEventInfo) {
  7702. setProgress('Эвент завершен', true);
  7703. return;
  7704. }
  7705.  
  7706. if (bossEventInfo.progress.score > 250) {
  7707. setProgress('Уже убито больше 250 врагов');
  7708. rewardBossRatingEventSouls();
  7709. return;
  7710. }
  7711. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  7712. const heroGetAllList = data.results[0].result.response;
  7713. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7714. const heroList = [];
  7715.  
  7716. for (let heroId in heroGetAllList) {
  7717. let hero = heroGetAllList[heroId];
  7718. if (usedHeroes.includes(hero.id)) {
  7719. continue;
  7720. }
  7721. heroList.push(hero.id);
  7722. }
  7723.  
  7724. if (!heroList.length) {
  7725. setProgress('Нет героев', true);
  7726. return;
  7727. }
  7728.  
  7729. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  7730. const petLib = lib.getData('pet');
  7731. let count = 1;
  7732.  
  7733. for (const heroId of heroList) {
  7734. const args = {
  7735. heroes: [heroId],
  7736. pet
  7737. }
  7738. /** Поиск питомца для героя */
  7739. for (const petId of availablePets) {
  7740. if (petLib[petId].favorHeroes.includes(heroId)) {
  7741. args.favor = {
  7742. [heroId]: petId
  7743. }
  7744. break;
  7745. }
  7746. }
  7747.  
  7748. const calls = [{
  7749. name: "bossRatingEvent_startBattle",
  7750. args,
  7751. ident: "body"
  7752. }, {
  7753. name: "offerGetAll",
  7754. args: {},
  7755. ident: "offerGetAll"
  7756. }];
  7757.  
  7758. const res = await Send({ calls });
  7759. count++;
  7760.  
  7761. if ('error' in res) {
  7762. console.error(res.error);
  7763. setProgress('Перезагрузите игру и попробуйте позже', true);
  7764. return;
  7765. }
  7766.  
  7767. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  7768. if (eventInfo.progress.score > 250) {
  7769. break;
  7770. }
  7771. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  7772. }
  7773.  
  7774. rewardBossRatingEventSouls();
  7775. }
  7776. /** Сбор награды из Горнила Душ */
  7777. async function rewardBossRatingEventSouls() {
  7778. const data = await Send({
  7779. calls: [
  7780. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7781. ]
  7782. });
  7783.  
  7784. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7785. if (!bossEventInfo) {
  7786. setProgress('Эвент завершен', true);
  7787. return;
  7788. }
  7789.  
  7790. const farmedChests = bossEventInfo.progress.farmedChests;
  7791. const score = bossEventInfo.progress.score;
  7792. // setProgress('Количество убитых врагов: ' + score);
  7793. const revard = bossEventInfo.reward;
  7794. const calls = [];
  7795.  
  7796. let count = 0;
  7797. for (let i = 1; i < 10; i++) {
  7798. if (farmedChests.includes(i)) {
  7799. continue;
  7800. }
  7801. if (score < revard[i].score) {
  7802. break;
  7803. }
  7804. calls.push({
  7805. name: "bossRatingEvent_getReward",
  7806. args: {
  7807. rewardId: i
  7808. },
  7809. ident: "body_" + i
  7810. });
  7811. count++;
  7812. }
  7813. if (!count) {
  7814. setProgress('Нечего собирать', true);
  7815. return;
  7816. }
  7817.  
  7818. Send({ calls }).then(e => {
  7819. console.log(e);
  7820. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  7821. })
  7822. }
  7823. /**
  7824. * Spin the Seer
  7825. *
  7826. * Покрутить провидца
  7827. */
  7828. async function rollAscension() {
  7829. const refillable = await Send({calls:[
  7830. {
  7831. name:"userGetInfo",
  7832. args:{},
  7833. ident:"userGetInfo"
  7834. }
  7835. ]}).then(e => e.results[0].result.response.refillable);
  7836. const i47 = refillable.find(i => i.id == 47);
  7837. if (i47?.amount) {
  7838. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  7839. setProgress(I18N('DONE'), true);
  7840. } else {
  7841. setProgress(I18N('NOT_ENOUGH_AP'), true);
  7842. }
  7843. }
  7844.  
  7845. /**
  7846. * Collect gifts for the New Year
  7847. *
  7848. * Собрать подарки на новый год
  7849. */
  7850. function getGiftNewYear() {
  7851. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  7852. const gifts = e.results[0].result.response.gifts;
  7853. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  7854. name: "newYearGiftOpen",
  7855. args: {
  7856. giftId: e.id
  7857. },
  7858. ident: `body_${e.id}`
  7859. }));
  7860. if (!calls.length) {
  7861. setProgress(I18N('NY_NO_GIFTS'), 5000);
  7862. return;
  7863. }
  7864. Send({ calls }).then(e => {
  7865. console.log(e.results)
  7866. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  7867. console.log(msg);
  7868. setProgress(msg, 5000);
  7869. });
  7870. })
  7871. }
  7872.  
  7873. async function updateArtifacts() {
  7874. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  7875. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  7876. { result: false, isClose: true }
  7877. ]);
  7878. if (!count) {
  7879. return;
  7880. }
  7881. const quest = new questRun;
  7882. await quest.autoInit();
  7883. const heroes = Object.values(quest.questInfo['heroGetAll']);
  7884. const inventory = quest.questInfo['inventoryGet'];
  7885. const calls = [];
  7886. for (let i = count; i > 0; i--) {
  7887. const upArtifact = quest.getUpgradeArtifact();
  7888. if (!upArtifact.heroId) {
  7889. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  7890. { msg: I18N('YES'), result: true },
  7891. { result: false, isClose: true }
  7892. ])) {
  7893. break;
  7894. } else {
  7895. return;
  7896. }
  7897. }
  7898. const hero = heroes.find(e => e.id == upArtifact.heroId);
  7899. hero.artifacts[upArtifact.slotId].level++;
  7900. inventory[upArtifact.costСurrency][upArtifact.costId] -= upArtifact.costValue;
  7901. calls.push({
  7902. name: "heroArtifactLevelUp",
  7903. args: {
  7904. heroId: upArtifact.heroId,
  7905. slotId: upArtifact.slotId
  7906. },
  7907. ident: `heroArtifactLevelUp_${i}`
  7908. });
  7909. }
  7910.  
  7911. if (!calls.length) {
  7912. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7913. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7914. return;
  7915. }
  7916.  
  7917. await Send(JSON.stringify({ calls })).then(e => {
  7918. if ('error' in e) {
  7919. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7920. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7921. } else {
  7922. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  7923. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  7924. }
  7925. });
  7926. }
  7927.  
  7928. window.sign = a => {
  7929. const i = this['\x78\x79\x7a'];
  7930. 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'))
  7931. }
  7932.  
  7933. async function updateSkins() {
  7934. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  7935. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  7936. { result: false, isClose: true }
  7937. ]);
  7938. if (!count) {
  7939. return;
  7940. }
  7941.  
  7942. const quest = new questRun;
  7943. await quest.autoInit();
  7944. const heroes = Object.values(quest.questInfo['heroGetAll']);
  7945. const inventory = quest.questInfo['inventoryGet'];
  7946. const calls = [];
  7947. for (let i = count; i > 0; i--) {
  7948. const upSkin = quest.getUpgradeSkin();
  7949. if (!upSkin.heroId) {
  7950. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  7951. { msg: I18N('YES'), result: true },
  7952. { result: false, isClose: true }
  7953. ])) {
  7954. break;
  7955. } else {
  7956. return;
  7957. }
  7958. }
  7959. const hero = heroes.find(e => e.id == upSkin.heroId);
  7960. hero.skins[upSkin.skinId]++;
  7961. inventory[upSkin.costСurrency][upSkin.costСurrencyId] -= upSkin.cost;
  7962. calls.push({
  7963. name: "heroSkinUpgrade",
  7964. args: {
  7965. heroId: upSkin.heroId,
  7966. skinId: upSkin.skinId
  7967. },
  7968. ident: `heroSkinUpgrade_${i}`
  7969. })
  7970. }
  7971.  
  7972. if (!calls.length) {
  7973. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7974. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7975. return;
  7976. }
  7977.  
  7978. await Send(JSON.stringify({ calls })).then(e => {
  7979. if ('error' in e) {
  7980. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  7981. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  7982. } else {
  7983. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  7984. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  7985. }
  7986. });
  7987. }
  7988.  
  7989. function getQuestionInfo(img, nameOnly = false) {
  7990. const libHeroes = Object.values(lib.data.hero);
  7991. const parts = img.split(':');
  7992. const id = parts[1];
  7993. switch (parts[0]) {
  7994. case 'titanArtifact_id':
  7995. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  7996. case 'titan':
  7997. return cheats.translate("LIB_HERO_NAME_" + id);
  7998. case 'skill':
  7999. return cheats.translate("LIB_SKILL_" + id);
  8000. case 'inventoryItem_gear':
  8001. return cheats.translate("LIB_GEAR_NAME_" + id);
  8002. case 'inventoryItem_coin':
  8003. return cheats.translate("LIB_COIN_NAME_" + id);
  8004. case 'artifact':
  8005. if (nameOnly) {
  8006. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  8007. }
  8008. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  8009. return {
  8010. /** Как называется этот артефакт? */
  8011. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  8012. /** Какому герою принадлежит этот артефакт? */
  8013. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  8014. };
  8015. case 'hero':
  8016. if (nameOnly) {
  8017. return cheats.translate("LIB_HERO_NAME_" + id);
  8018. }
  8019. artifacts = lib.data.hero[id].artifacts;
  8020. return {
  8021. /** Как зовут этого героя? */
  8022. name: cheats.translate("LIB_HERO_NAME_" + id),
  8023. /** Какой артефакт принадлежит этому герою? */
  8024. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  8025. };
  8026. }
  8027. }
  8028.  
  8029. function hintQuest(quest) {
  8030. const result = {};
  8031. if (quest?.questionIcon) {
  8032. const info = getQuestionInfo(quest.questionIcon);
  8033. if (info?.heroes) {
  8034. /** Какому герою принадлежит этот артефакт? */
  8035. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  8036. }
  8037. if (info?.artifact) {
  8038. /** Какой артефакт принадлежит этому герою? */
  8039. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  8040. }
  8041. if (typeof info == 'string') {
  8042. result.info = { name: info };
  8043. } else {
  8044. result.info = info;
  8045. }
  8046. }
  8047.  
  8048. if (quest.answers[0]?.answerIcon) {
  8049. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  8050. }
  8051.  
  8052. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  8053. return false;
  8054. }
  8055.  
  8056. let resultText = '';
  8057. if (result?.info) {
  8058. resultText += I18N('PICTURE') + result.info.name;
  8059. }
  8060. console.log(result);
  8061. if (result?.answer && result.answer.length) {
  8062. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  8063. }
  8064.  
  8065. return resultText;
  8066. }
  8067.  
  8068. /**
  8069. * Attack of the minions of Asgard
  8070. *
  8071. * Атака прислужников Асгарда
  8072. */
  8073. function testRaidNodes() {
  8074. return new Promise((resolve, reject) => {
  8075. const tower = new executeRaidNodes(resolve, reject);
  8076. tower.start();
  8077. });
  8078. }
  8079.  
  8080. /**
  8081. * Attack of the minions of Asgard
  8082. *
  8083. * Атака прислужников Асгарда
  8084. */
  8085. function executeRaidNodes(resolve, reject) {
  8086. let raidData = {
  8087. teams: [],
  8088. favor: {},
  8089. nodes: [],
  8090. attempts: 0,
  8091. countExecuteBattles: 0,
  8092. cancelBattle: 0,
  8093. }
  8094.  
  8095. callsExecuteRaidNodes = {
  8096. calls: [{
  8097. name: "clanRaid_getInfo",
  8098. args: {},
  8099. ident: "clanRaid_getInfo"
  8100. }, {
  8101. name: "teamGetAll",
  8102. args: {},
  8103. ident: "teamGetAll"
  8104. }, {
  8105. name: "teamGetFavor",
  8106. args: {},
  8107. ident: "teamGetFavor"
  8108. }]
  8109. }
  8110.  
  8111. this.start = function () {
  8112. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  8113. }
  8114.  
  8115. async function startRaidNodes(data) {
  8116. res = data.results;
  8117. clanRaidInfo = res[0].result.response;
  8118. teamGetAll = res[1].result.response;
  8119. teamGetFavor = res[2].result.response;
  8120.  
  8121. let index = 0;
  8122. let isNotFullPack = false;
  8123. for (let team of teamGetAll.clanRaid_nodes) {
  8124. if (team.length < 6) {
  8125. isNotFullPack = true;
  8126. }
  8127. raidData.teams.push({
  8128. data: {},
  8129. heroes: team.filter(id => id < 6000),
  8130. pet: team.filter(id => id >= 6000).pop(),
  8131. battleIndex: index++
  8132. });
  8133. }
  8134. raidData.favor = teamGetFavor.clanRaid_nodes;
  8135.  
  8136. if (isNotFullPack) {
  8137. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  8138. { msg: I18N('BTN_NO'), result: true },
  8139. { msg: I18N('BTN_YES'), result: false },
  8140. ])) {
  8141. endRaidNodes('isNotFullPack');
  8142. return;
  8143. }
  8144. }
  8145.  
  8146. raidData.nodes = clanRaidInfo.nodes;
  8147. raidData.attempts = clanRaidInfo.attempts;
  8148. isCancalBattle = false;
  8149.  
  8150. checkNodes();
  8151. }
  8152.  
  8153. function getAttackNode() {
  8154. for (let nodeId in raidData.nodes) {
  8155. let node = raidData.nodes[nodeId];
  8156. let points = 0
  8157. for (team of node.teams) {
  8158. points += team.points;
  8159. }
  8160. let now = Date.now() / 1000;
  8161. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  8162. let countTeam = node.teams.length;
  8163. delete raidData.nodes[nodeId];
  8164. return {
  8165. nodeId,
  8166. countTeam
  8167. };
  8168. }
  8169. }
  8170. return null;
  8171. }
  8172.  
  8173. function checkNodes() {
  8174. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  8175. let nodeInfo = getAttackNode();
  8176. if (nodeInfo && raidData.attempts) {
  8177. startNodeBattles(nodeInfo);
  8178. return;
  8179. }
  8180.  
  8181. endRaidNodes('EndRaidNodes');
  8182. }
  8183.  
  8184. function startNodeBattles(nodeInfo) {
  8185. let {nodeId, countTeam} = nodeInfo;
  8186. let teams = raidData.teams.slice(0, countTeam);
  8187. let heroes = raidData.teams.map(e => e.heroes).flat();
  8188. let favor = {...raidData.favor};
  8189. for (let heroId in favor) {
  8190. if (!heroes.includes(+heroId)) {
  8191. delete favor[heroId];
  8192. }
  8193. }
  8194.  
  8195. let calls = [{
  8196. name: "clanRaid_startNodeBattles",
  8197. args: {
  8198. nodeId,
  8199. teams,
  8200. favor
  8201. },
  8202. ident: "body"
  8203. }];
  8204.  
  8205. send(JSON.stringify({calls}), resultNodeBattles);
  8206. }
  8207.  
  8208. function resultNodeBattles(e) {
  8209. if (e['error']) {
  8210. endRaidNodes('nodeBattlesError', e['error']);
  8211. return;
  8212. }
  8213.  
  8214. console.log(e);
  8215. let battles = e.results[0].result.response.battles;
  8216. let promises = [];
  8217. let battleIndex = 0;
  8218. for (let battle of battles) {
  8219. battle.battleIndex = battleIndex++;
  8220. promises.push(calcBattleResult(battle));
  8221. }
  8222.  
  8223. Promise.all(promises)
  8224. .then(results => {
  8225. const endResults = {};
  8226. let isAllWin = true;
  8227. for (let r of results) {
  8228. isAllWin &&= r.result.win;
  8229. }
  8230. if (!isAllWin) {
  8231. cancelEndNodeBattle(results[0]);
  8232. return;
  8233. }
  8234. raidData.countExecuteBattles = results.length;
  8235. let timeout = 500;
  8236. for (let r of results) {
  8237. setTimeout(endNodeBattle, timeout, r);
  8238. timeout += 500;
  8239. }
  8240. });
  8241. }
  8242. /**
  8243. * Returns the battle calculation promise
  8244. *
  8245. * Возвращает промис расчета боя
  8246. */
  8247. function calcBattleResult(battleData) {
  8248. return new Promise(function (resolve, reject) {
  8249. BattleCalc(battleData, "get_clanPvp", resolve);
  8250. });
  8251. }
  8252. /**
  8253. * Cancels the fight
  8254. *
  8255. * Отменяет бой
  8256. */
  8257. function cancelEndNodeBattle(r) {
  8258. const fixBattle = function (heroes) {
  8259. for (const ids in heroes) {
  8260. hero = heroes[ids];
  8261. hero.energy = random(1, 999);
  8262. if (hero.hp > 0) {
  8263. hero.hp = random(1, hero.hp);
  8264. }
  8265. }
  8266. }
  8267. fixBattle(r.progress[0].attackers.heroes);
  8268. fixBattle(r.progress[0].defenders.heroes);
  8269. endNodeBattle(r);
  8270. }
  8271. /**
  8272. * Ends the fight
  8273. *
  8274. * Завершает бой
  8275. */
  8276. function endNodeBattle(r) {
  8277. let nodeId = r.battleData.result.nodeId;
  8278. let battleIndex = r.battleData.battleIndex;
  8279. let calls = [{
  8280. name: "clanRaid_endNodeBattle",
  8281. args: {
  8282. nodeId,
  8283. battleIndex,
  8284. result: r.result,
  8285. progress: r.progress
  8286. },
  8287. ident: "body"
  8288. }]
  8289.  
  8290. SendRequest(JSON.stringify({calls}), battleResult);
  8291. }
  8292. /**
  8293. * Processing the results of the battle
  8294. *
  8295. * Обработка результатов боя
  8296. */
  8297. function battleResult(e) {
  8298. if (e['error']) {
  8299. endRaidNodes('missionEndError', e['error']);
  8300. return;
  8301. }
  8302. r = e.results[0].result.response;
  8303. if (r['error']) {
  8304. if (r.reason == "invalidBattle") {
  8305. raidData.cancelBattle++;
  8306. checkNodes();
  8307. } else {
  8308. endRaidNodes('missionEndError', e['error']);
  8309. }
  8310. return;
  8311. }
  8312.  
  8313. if (!(--raidData.countExecuteBattles)) {
  8314. raidData.attempts--;
  8315. checkNodes();
  8316. }
  8317. }
  8318. /**
  8319. * Completing a task
  8320. *
  8321. * Завершение задачи
  8322. */
  8323. function endRaidNodes(reason, info) {
  8324. isCancalBattle = true;
  8325. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  8326. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  8327. console.log(reason, info);
  8328. resolve();
  8329. }
  8330. }
  8331.  
  8332. /**
  8333. * Asgard Boss Attack Replay
  8334. *
  8335. * Повтор атаки босса Асгарда
  8336. */
  8337. function testBossBattle() {
  8338. return new Promise((resolve, reject) => {
  8339. const bossBattle = new executeBossBattle(resolve, reject);
  8340. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  8341. });
  8342. }
  8343.  
  8344. /**
  8345. * Asgard Boss Attack Replay
  8346. *
  8347. * Повтор атаки босса Асгарда
  8348. */
  8349. function executeBossBattle(resolve, reject) {
  8350. let lastBossBattleArgs = {};
  8351. let reachDamage = 0;
  8352. let countBattle = 0;
  8353. let countMaxBattle = 10;
  8354. let lastDamage = 0;
  8355.  
  8356. this.start = function (battleArg, battleInfo) {
  8357. lastBossBattleArgs = battleArg;
  8358. preCalcBattle(battleInfo);
  8359. }
  8360.  
  8361. function getBattleInfo(battle) {
  8362. return new Promise(function (resolve) {
  8363. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8364. BattleCalc(battle, getBattleType(battle.type), e => {
  8365. let extra = e.progress[0].defenders.heroes[1].extra;
  8366. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  8367. });
  8368. });
  8369. }
  8370.  
  8371. function preCalcBattle(battle) {
  8372. let actions = [];
  8373. const countTestBattle = getInput('countTestBattle');
  8374. for (let i = 0; i < countTestBattle; i++) {
  8375. actions.push(getBattleInfo(battle, true));
  8376. }
  8377. Promise.all(actions)
  8378. .then(resultPreCalcBattle);
  8379. }
  8380.  
  8381. function fixDamage(damage) {
  8382. for (let i = 1e6; i > 1; i /= 10) {
  8383. if (damage > i) {
  8384. let n = i / 10;
  8385. damage = Math.ceil(damage / n) * n;
  8386. break;
  8387. }
  8388. }
  8389. return damage;
  8390. }
  8391.  
  8392. async function resultPreCalcBattle(damages) {
  8393. let maxDamage = 0;
  8394. let minDamage = 1e10;
  8395. let avgDamage = 0;
  8396. for (let damage of damages) {
  8397. avgDamage += damage
  8398. if (damage > maxDamage) {
  8399. maxDamage = damage;
  8400. }
  8401. if (damage < minDamage) {
  8402. minDamage = damage;
  8403. }
  8404. }
  8405. avgDamage /= damages.length;
  8406. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  8407.  
  8408. reachDamage = fixDamage(avgDamage);
  8409. const result = await popup.confirm(
  8410. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  8411. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  8412. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  8413. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  8414. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  8415. , [
  8416. { msg: I18N('BTN_OK'), result: 0},
  8417. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  8418. ])
  8419. if (result) {
  8420. reachDamage = result;
  8421. isCancalBossBattle = false;
  8422. startBossBattle();
  8423. return;
  8424. }
  8425. endBossBattle(I18N('BTN_CANCEL'));
  8426. }
  8427.  
  8428. function startBossBattle() {
  8429. countBattle++;
  8430. countMaxBattle = getInput('countAutoBattle');
  8431. if (countBattle > countMaxBattle) {
  8432. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  8433. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  8434. return;
  8435. }
  8436. let calls = [{
  8437. name: "clanRaid_startBossBattle",
  8438. args: lastBossBattleArgs,
  8439. ident: "body"
  8440. }];
  8441. send(JSON.stringify({calls}), calcResultBattle);
  8442. }
  8443.  
  8444. function calcResultBattle(e) {
  8445. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  8446. }
  8447.  
  8448. async function resultBattle(e) {
  8449. let extra = e.progress[0].defenders.heroes[1].extra
  8450. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  8451. console.log(resultDamage);
  8452. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  8453. lastDamage = resultDamage;
  8454. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  8455. {msg: 'Ок', result: true},
  8456. {msg: 'Не пойдет', result: false},
  8457. ])) {
  8458. endBattle(e, false);
  8459. return;
  8460. }
  8461. cancelEndBattle(e);
  8462. }
  8463.  
  8464. function cancelEndBattle (r) {
  8465. const fixBattle = function (heroes) {
  8466. for (const ids in heroes) {
  8467. hero = heroes[ids];
  8468. hero.energy = random(1, 999);
  8469. if (hero.hp > 0) {
  8470. hero.hp = random(1, hero.hp);
  8471. }
  8472. }
  8473. }
  8474. fixBattle(r.progress[0].attackers.heroes);
  8475. fixBattle(r.progress[0].defenders.heroes);
  8476. endBattle(r, true);
  8477. }
  8478.  
  8479. function endBattle(battleResult, isCancal) {
  8480. let calls = [{
  8481. name: "clanRaid_endBossBattle",
  8482. args: {
  8483. result: battleResult.result,
  8484. progress: battleResult.progress
  8485. },
  8486. ident: "body"
  8487. }];
  8488.  
  8489. send(JSON.stringify({calls}), e => {
  8490. console.log(e);
  8491. if (isCancal) {
  8492. startBossBattle();
  8493. return;
  8494. }
  8495. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  8496. setTimeout(() => {
  8497. scriptMenu.setStatus('');
  8498. }, 5000);
  8499. endBossBattle('Узпех!');
  8500. });
  8501. }
  8502.  
  8503. /**
  8504. * Completing a task
  8505. *
  8506. * Завершение задачи
  8507. */
  8508. function endBossBattle(reason, info) {
  8509. isCancalBossBattle = true;
  8510. console.log(reason, info);
  8511. resolve();
  8512. }
  8513. }
  8514.  
  8515. /**
  8516. * Auto-repeat attack
  8517. *
  8518. * Автоповтор атаки
  8519. */
  8520. function testAutoBattle() {
  8521. return new Promise((resolve, reject) => {
  8522. const bossBattle = new executeAutoBattle(resolve, reject);
  8523. bossBattle.start(lastBattleArg, lastBattleInfo);
  8524. });
  8525. }
  8526.  
  8527. /**
  8528. * Auto-repeat attack
  8529. *
  8530. * Автоповтор атаки
  8531. */
  8532. function executeAutoBattle(resolve, reject) {
  8533. let battleArg = {};
  8534. let countBattle = 0;
  8535. let countError = 0;
  8536. let findCoeff = 0;
  8537. let dataNotEeceived = 0;
  8538. const svgJustice = '<svg width="20" height="20" viewBox="0 0 124 125" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m54 0h-1c-7.25 6.05-17.17 6.97-25.78 10.22-8.6 3.25-23.68 1.07-23.22 12.78s-0.47 24.08 1 35 2.36 18.36 7 28c4.43-8.31-3.26-18.88-3-30 0.26-11.11-2.26-25.29-1-37 11.88-4.16 26.27-0.42 36.77-9.23s20.53 6.05 29.23-0.77c-6.65-2.98-14.08-4.96-20-9z"/></g><g><path d="m108 5c-11.05 2.96-27.82 2.2-35.08 11.92s-14.91 14.71-22.67 23.33c-7.77 8.62-14.61 15.22-22.25 23.75 7.05 11.93 14.33 2.58 20.75-4.25 6.42-6.82 12.98-13.03 19.5-19.5s12.34-13.58 19.75-18.25c2.92 7.29-8.32 12.65-13.25 18.75-4.93 6.11-12.19 11.48-17.5 17.5s-12.31 11.38-17.25 17.75c10.34 14.49 17.06-3.04 26.77-10.23s15.98-16.89 26.48-24.52c10.5-7.64 12.09-24.46 14.75-36.25z"/></g><g><path d="m60 25c-11.52-6.74-24.53 8.28-38 6 0.84 9.61-1.96 20.2 2 29 5.53-4.04-4.15-23.2 4.33-26.67 8.48-3.48 18.14-1.1 24.67-8.33 2.73 0.3 4.81 2.98 7 0z"/></g><g><path d="m100 75c3.84-11.28 5.62-25.85 3-38-4.2 5.12-3.5 13.58-4 20s-3.52 13.18 1 18z"/></g><g><path d="m55 94c15.66-5.61 33.71-20.85 29-39-3.07 8.05-4.3 16.83-10.75 23.25s-14.76 8.35-18.25 15.75z"/></g><g><path d="m0 94v7c6.05 3.66 9.48 13.3 18 11-3.54-11.78 8.07-17.05 14-25 6.66 1.52 13.43 16.26 19 5-11.12-9.62-20.84-21.33-32-31-9.35 6.63 4.76 11.99 6 19-7.88 5.84-13.24 17.59-25 14z"/></g><g><path d="m82 125h26v-19h16v-1c-11.21-8.32-18.38-21.74-30-29-8.59 10.26-19.05 19.27-27 30h15v19z"/></g><g><path d="m68 110c-7.68-1.45-15.22 4.83-21.92-1.08s-11.94-5.72-18.08-11.92c-3.03 8.84 10.66 9.88 16.92 16.08s17.09 3.47 23.08-3.08z"/></g></svg>';
  8539. const svgBoss = '<svg width="20" height="20" viewBox="0 0 40 41" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m21 12c-2.19-3.23 5.54-10.95-0.97-10.97-6.52-0.02 1.07 7.75-1.03 10.97-2.81 0.28-5.49-0.2-8-1-0.68 3.53 0.55 6.06 4 4 0.65 7.03 1.11 10.95 1.67 18.33 0.57 7.38 6.13 7.2 6.55-0.11 0.42-7.3 1.35-11.22 1.78-18.22 3.53 1.9 4.73-0.42 4-4-2.61 0.73-5.14 1.35-8 1m-1 17c-1.59-3.6-1.71-10.47 0-14 1.59 3.6 1.71 10.47 0 14z"/></g><g><path d="m6 19c-1.24-4.15 2.69-8.87 1-12-3.67 4.93-6.52 10.57-6 17 5.64-0.15 8.82 4.98 13 8 1.3-6.54-0.67-12.84-8-13z"/></g><g><path d="m33 7c0.38 5.57 2.86 14.79-7 15v10c4.13-2.88 7.55-7.97 13-8 0.48-6.46-2.29-12.06-6-17z"/></g></svg>';
  8540. const svgAttempt = '<svg width="20" height="20" viewBox="0 0 645 645" xmlns="http://www.w3.org/2000/svg" style="fill: #fff;"><g><path d="m442 26c-8.8 5.43-6.6 21.6-12.01 30.99-2.5 11.49-5.75 22.74-8.99 34.01-40.61-17.87-92.26-15.55-133.32-0.32-72.48 27.31-121.88 100.19-142.68 171.32 10.95-4.49 19.28-14.97 29.3-21.7 50.76-37.03 121.21-79.04 183.47-44.07 16.68 5.8 2.57 21.22-0.84 31.7-4.14 12.19-11.44 23.41-13.93 36.07 56.01-17.98 110.53-41.23 166-61-20.49-59.54-46.13-117.58-67-177z"/></g><g><path d="m563 547c23.89-16.34 36.1-45.65 47.68-71.32 23.57-62.18 7.55-133.48-28.38-186.98-15.1-22.67-31.75-47.63-54.3-63.7 1.15 14.03 6.71 26.8 8.22 40.78 12.08 61.99 15.82 148.76-48.15 183.29-10.46-0.54-15.99-16.1-24.32-22.82-8.2-7.58-14.24-19.47-23.75-24.25-4.88 59.04-11.18 117.71-15 177 62.9 5.42 126.11 9.6 189 15-4.84-9.83-17.31-15.4-24.77-24.23-9.02-7.06-17.8-15.13-26.23-22.77z"/></g><g><path d="m276 412c-10.69-15.84-30.13-25.9-43.77-40.23-15.39-12.46-30.17-25.94-45.48-38.52-15.82-11.86-29.44-28.88-46.75-37.25-19.07 24.63-39.96 48.68-60.25 72.75-18.71 24.89-42.41 47.33-58.75 73.25 22.4-2.87 44.99-13.6 66.67-13.67 0.06 22.8 10.69 42.82 20.41 62.59 49.09 93.66 166.6 114.55 261.92 96.08-6.07-9.2-22.11-9.75-31.92-16.08-59.45-26.79-138.88-75.54-127.08-151.92 21.66-2.39 43.42-4.37 65-7z"/></g></svg>';
  8541.  
  8542. this.start = function (battleArgs, battleInfo) {
  8543. battleArg = battleArgs;
  8544. preCalcBattle(battleInfo);
  8545. }
  8546. /**
  8547. * Returns a promise for combat recalculation
  8548. *
  8549. * Возвращает промис для прерасчета боя
  8550. */
  8551. function getBattleInfo(battle) {
  8552. return new Promise(function (resolve) {
  8553. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  8554. Calc(battle).then(e => {
  8555. e.coeff = calcCoeff(e, 'defenders');
  8556. resolve(e);
  8557. });
  8558. });
  8559. }
  8560. /**
  8561. * Battle recalculation
  8562. *
  8563. * Прерасчет боя
  8564. */
  8565. function preCalcBattle(battle) {
  8566. let actions = [];
  8567. const countTestBattle = getInput('countTestBattle');
  8568. for (let i = 0; i < countTestBattle; i++) {
  8569. actions.push(getBattleInfo(battle));
  8570. }
  8571. Promise.all(actions)
  8572. .then(resultPreCalcBattle);
  8573. }
  8574. /**
  8575. * Processing the results of the battle recalculation
  8576. *
  8577. * Обработка результатов прерасчета боя
  8578. */
  8579. async function resultPreCalcBattle(results) {
  8580. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  8581. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  8582. if (countWin > 0) {
  8583. isCancalBattle = false;
  8584. startBattle();
  8585. return;
  8586. }
  8587.  
  8588. let minCoeff = 100;
  8589. let maxCoeff = -100;
  8590. let avgCoeff = 0;
  8591. results.forEach(e => {
  8592. if (e.coeff < minCoeff) minCoeff = e.coeff;
  8593. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  8594. avgCoeff += e.coeff;
  8595. });
  8596. avgCoeff /= results.length;
  8597.  
  8598. if (nameFuncStartBattle == 'invasion_bossStart' ||
  8599. nameFuncStartBattle == 'bossAttack') {
  8600. const result = await popup.confirm(
  8601. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  8602. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  8603. { msg: I18N('BTN_DO_IT'), result: true },
  8604. ])
  8605. if (result) {
  8606. isCancalBattle = false;
  8607. startBattle();
  8608. return;
  8609. }
  8610. setProgress(I18N('NOT_THIS_TIME'), true);
  8611. endAutoBattle('invasion_bossStart');
  8612. return;
  8613. }
  8614.  
  8615. const result = await popup.confirm(
  8616. I18N('VICTORY_IMPOSSIBLE') +
  8617. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  8618. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  8619. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  8620. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  8621. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  8622. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  8623. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  8624. ])
  8625. if (result) {
  8626. findCoeff = result;
  8627. isCancalBattle = false;
  8628. startBattle();
  8629. return;
  8630. }
  8631. setProgress(I18N('NOT_THIS_TIME'), true);
  8632. endAutoBattle(I18N('NOT_THIS_TIME'));
  8633. }
  8634.  
  8635. /**
  8636. * Calculation of the combat result coefficient
  8637. *
  8638. * Расчет коэфициента результата боя
  8639. */
  8640. function calcCoeff(result, packType) {
  8641. let beforeSumFactor = 0;
  8642. const beforePack = result.battleData[packType][0];
  8643. for (let heroId in beforePack) {
  8644. const hero = beforePack[heroId];
  8645. const state = hero.state;
  8646. let factor = 1;
  8647. if (state) {
  8648. const hp = state.hp / state.maxHp;
  8649. const energy = state.energy / 1e3;
  8650. factor = hp + energy / 20;
  8651. }
  8652. beforeSumFactor += factor;
  8653. }
  8654.  
  8655. let afterSumFactor = 0;
  8656. const afterPack = result.progress[0][packType].heroes;
  8657. for (let heroId in afterPack) {
  8658. const hero = afterPack[heroId];
  8659. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  8660. const hp = hero.hp / stateHp;
  8661. const energy = hero.energy / 1e3;
  8662. const factor = hp + energy / 20;
  8663. afterSumFactor += factor;
  8664. }
  8665. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  8666. return Math.round(resultCoeff * 1000) / 1000;
  8667. }
  8668. /**
  8669. * Start battle
  8670. *
  8671. * Начало боя
  8672. */
  8673. function startBattle() {
  8674. countBattle++;
  8675. const countMaxBattle = getInput('countAutoBattle');
  8676. // setProgress(countBattle + '/' + countMaxBattle);
  8677. if (countBattle > countMaxBattle) {
  8678. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  8679. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  8680. return;
  8681. }
  8682. send({calls: [{
  8683. name: nameFuncStartBattle,
  8684. args: battleArg,
  8685. ident: "body"
  8686. }]}, calcResultBattle);
  8687. }
  8688. /**
  8689. * Battle calculation
  8690. *
  8691. * Расчет боя
  8692. */
  8693. async function calcResultBattle(e) {
  8694. if (!e) {
  8695. console.log('данные не были получены');
  8696. if (dataNotEeceived < 10) {
  8697. dataNotEeceived++;
  8698. startBattle();
  8699. return;
  8700. }
  8701. endAutoBattle('Error', 'данные не были получены ' + dataNotEeceived + ' раз');
  8702. return;
  8703. }
  8704. if ('error' in e) {
  8705. if (e.error.description === 'too many tries') {
  8706. invasionTimer += 100;
  8707. countBattle--;
  8708. countError++;
  8709. console.log(`Errors: ${countError}`, e.error);
  8710. startBattle();
  8711. return;
  8712. }
  8713. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  8714. { msg: I18N('BTN_OK'), result: false },
  8715. { msg: I18N('RELOAD_GAME'), result: true },
  8716. ]);
  8717. endAutoBattle('Error', e.error);
  8718. if (result) {
  8719. location.reload();
  8720. }
  8721. return;
  8722. }
  8723. let battle = e.results[0].result.response.battle
  8724. if (nameFuncStartBattle == 'towerStartBattle' ||
  8725. nameFuncStartBattle == 'bossAttack' ||
  8726. nameFuncStartBattle == 'invasion_bossStart') {
  8727. battle = e.results[0].result.response;
  8728. }
  8729. lastBattleInfo = battle;
  8730. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  8731. }
  8732. /**
  8733. * Processing the results of the battle
  8734. *
  8735. * Обработка результатов боя
  8736. */
  8737. function resultBattle(e) {
  8738. const isWin = e.result.win;
  8739. if (isWin) {
  8740. endBattle(e, false);
  8741. return;
  8742. }
  8743. const countMaxBattle = getInput('countAutoBattle');
  8744. if (findCoeff) {
  8745. const coeff = calcCoeff(e, 'defenders');
  8746. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  8747. if (coeff > findCoeff) {
  8748. endBattle(e, false);
  8749. return;
  8750. }
  8751. } else {
  8752. if (nameFuncStartBattle == 'invasion_bossStart') {
  8753. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  8754. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  8755. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`);
  8756. } else {
  8757. setProgress(`${countBattle}/${countMaxBattle}`);
  8758. }
  8759. }
  8760. if (nameFuncStartBattle == 'towerStartBattle' ||
  8761. nameFuncStartBattle == 'bossAttack' ||
  8762. nameFuncStartBattle == 'invasion_bossStart') {
  8763. startBattle();
  8764. return;
  8765. }
  8766. cancelEndBattle(e);
  8767. }
  8768. /**
  8769. * Cancel fight
  8770. *
  8771. * Отмена боя
  8772. */
  8773. function cancelEndBattle(r) {
  8774. const fixBattle = function (heroes) {
  8775. for (const ids in heroes) {
  8776. hero = heroes[ids];
  8777. hero.energy = random(1, 999);
  8778. if (hero.hp > 0) {
  8779. hero.hp = random(1, hero.hp);
  8780. }
  8781. }
  8782. }
  8783. fixBattle(r.progress[0].attackers.heroes);
  8784. fixBattle(r.progress[0].defenders.heroes);
  8785. endBattle(r, true);
  8786. }
  8787. /**
  8788. * End of the fight
  8789. *
  8790. * Завершение боя */
  8791. function endBattle(battleResult, isCancal) {
  8792. let calls = [{
  8793. name: nameFuncEndBattle,
  8794. args: {
  8795. result: battleResult.result,
  8796. progress: battleResult.progress
  8797. },
  8798. ident: "body"
  8799. }];
  8800.  
  8801. if (nameFuncStartBattle == 'invasion_bossStart') {
  8802. calls[0].args.id = lastBattleArg.id;
  8803. }
  8804.  
  8805. send(JSON.stringify({
  8806. calls
  8807. }), async e => {
  8808. console.log(e);
  8809. if (isCancal) {
  8810. startBattle();
  8811. return;
  8812. }
  8813.  
  8814. setProgress(`${I18N('SUCCESS')}!`, 5000)
  8815. if (nameFuncStartBattle == 'invasion_bossStart' ||
  8816. nameFuncStartBattle == 'bossAttack') {
  8817. const countMaxBattle = getInput('countAutoBattle');
  8818. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  8819. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  8820. const result = await popup.confirm(
  8821. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  8822. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  8823. countBattle: svgAttempt + ' ' + countBattle,
  8824. countMaxBattle,
  8825. }),
  8826. [
  8827. { msg: I18N('BTN_OK'), result: 0 },
  8828. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  8829. { msg: I18N('RELOAD_GAME'), result: 2 },
  8830. ]
  8831. );
  8832. if (result) {
  8833. if (result == 1) {
  8834. cheats.refreshGame();
  8835. }
  8836. if (result == 2) {
  8837. location.reload();
  8838. }
  8839. }
  8840.  
  8841. }
  8842. endAutoBattle(`${I18N('SUCCESS')}!`)
  8843. });
  8844. }
  8845. /**
  8846. * Completing a task
  8847. *
  8848. * Завершение задачи
  8849. */
  8850. function endAutoBattle(reason, info) {
  8851. isCancalBattle = true;
  8852. console.log(reason, info);
  8853. resolve();
  8854. }
  8855. }
  8856.  
  8857. function testDailyQuests() {
  8858. return new Promise((resolve, reject) => {
  8859. const quests = new dailyQuests(resolve, reject);
  8860. quests.init(questsInfo);
  8861. quests.start();
  8862. });
  8863. }
  8864.  
  8865. /**
  8866. * Automatic completion of daily quests
  8867. *
  8868. * Автоматическое выполнение ежедневных квестов
  8869. */
  8870. class dailyQuests {
  8871. /**
  8872. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  8873. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8874. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8875. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  8876. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8877. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  8878. */
  8879. callsList = [
  8880. "userGetInfo",
  8881. "heroGetAll",
  8882. "titanGetAll",
  8883. "inventoryGet",
  8884. "questGetAll",
  8885. "bossGetAll",
  8886. ]
  8887.  
  8888. dataQuests = {
  8889. 10001: {
  8890. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  8891. doItCall: () => {
  8892. const upgradeSkills = this.getUpgradeSkills();
  8893. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  8894. },
  8895. isWeCanDo: () => {
  8896. const upgradeSkills = this.getUpgradeSkills();
  8897. let sumGold = 0;
  8898. for (const skill of upgradeSkills) {
  8899. sumGold += this.skillCost(skill.value);
  8900. if (!skill.heroId) {
  8901. return false;
  8902. }
  8903. }
  8904. return this.questInfo['userGetInfo'].gold > sumGold;
  8905. },
  8906. },
  8907. 10002: {
  8908. description: 'Пройди 10 миссий', // --------------
  8909. isWeCanDo: () => false,
  8910. },
  8911. 10003: {
  8912. description: 'Пройди 3 героические миссии', // --------------
  8913. isWeCanDo: () => false,
  8914. },
  8915. 10004: {
  8916. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  8917. isWeCanDo: () => false,
  8918. },
  8919. 10006: {
  8920. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  8921. doItCall: () => [{
  8922. name: "refillableAlchemyUse",
  8923. args: { multi: false },
  8924. ident: "refillableAlchemyUse"
  8925. }],
  8926. isWeCanDo: () => {
  8927. const starMoney = this.questInfo['userGetInfo'].starMoney;
  8928. return starMoney >= 20;
  8929. },
  8930. },
  8931. 10007: {
  8932. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  8933. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  8934. isWeCanDo: () => {
  8935. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  8936. return soulCrystal > 0;
  8937. },
  8938. },
  8939. 10016: {
  8940. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  8941. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  8942. isWeCanDo: () => true,
  8943. },
  8944. 10018: {
  8945. description: 'Используй зелье опыта', // ++++++++++++++++
  8946. doItCall: () => {
  8947. const expHero = this.getExpHero();
  8948. return [{
  8949. name: "consumableUseHeroXp",
  8950. args: {
  8951. heroId: expHero.heroId,
  8952. libId: expHero.libId,
  8953. amount: 1
  8954. },
  8955. ident: "consumableUseHeroXp"
  8956. }];
  8957. },
  8958. isWeCanDo: () => {
  8959. const expHero = this.getExpHero();
  8960. return expHero.heroId && expHero.libId;
  8961. },
  8962. },
  8963. 10019: {
  8964. description: 'Открой 1 сундук в Башне',
  8965. doItFunc: testTower,
  8966. isWeCanDo: () => false,
  8967. },
  8968. 10020: {
  8969. description: 'Открой 3 сундука в Запределье', // Готово
  8970. doItCall: () => {
  8971. return this.getOutlandChest();
  8972. },
  8973. isWeCanDo: () => {
  8974. const outlandChest = this.getOutlandChest();
  8975. return outlandChest.length > 0;
  8976. },
  8977. },
  8978. 10021: {
  8979. description: 'Собери 75 Титанита в Подземелье Гильдии',
  8980. isWeCanDo: () => false,
  8981. },
  8982. 10022: {
  8983. description: 'Собери 150 Титанита в Подземелье Гильдии',
  8984. doItFunc: testDungeon,
  8985. isWeCanDo: () => false,
  8986. },
  8987. 10023: {
  8988. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  8989. doItCall: () => {
  8990. const heroId = this.getHeroIdTitanGift();
  8991. return [
  8992. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  8993. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  8994. ]
  8995. },
  8996. isWeCanDo: () => {
  8997. const heroId = this.getHeroIdTitanGift();
  8998. return heroId;
  8999. },
  9000. },
  9001. 10024: {
  9002. description: 'Повысь уровень любого артефакта один раз', // Готово
  9003. doItCall: () => {
  9004. const upArtifact = this.getUpgradeArtifact();
  9005. return [
  9006. {
  9007. name: "heroArtifactLevelUp",
  9008. args: {
  9009. heroId: upArtifact.heroId,
  9010. slotId: upArtifact.slotId
  9011. },
  9012. ident: `heroArtifactLevelUp`
  9013. }
  9014. ];
  9015. },
  9016. isWeCanDo: () => {
  9017. const upgradeArtifact = this.getUpgradeArtifact();
  9018. return upgradeArtifact.heroId;
  9019. },
  9020. },
  9021. 10025: {
  9022. description: 'Начни 1 Экспедицию',
  9023. doItFunc: checkExpedition,
  9024. isWeCanDo: () => false,
  9025. },
  9026. 10026: {
  9027. description: 'Начни 4 Экспедиции', // --------------
  9028. doItFunc: checkExpedition,
  9029. isWeCanDo: () => false,
  9030. },
  9031. 10027: {
  9032. description: 'Победи в 1 бою Турнира Стихий',
  9033. doItFunc: testTitanArena,
  9034. isWeCanDo: () => false,
  9035. },
  9036. 10028: {
  9037. description: 'Повысь уровень любого артефакта титанов', // Готово
  9038. doItCall: () => {
  9039. const upTitanArtifact = this.getUpgradeTitanArtifact();
  9040. return [
  9041. {
  9042. name: "titanArtifactLevelUp",
  9043. args: {
  9044. titanId: upTitanArtifact.titanId,
  9045. slotId: upTitanArtifact.slotId
  9046. },
  9047. ident: `titanArtifactLevelUp`
  9048. }
  9049. ];
  9050. },
  9051. isWeCanDo: () => {
  9052. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  9053. return upgradeTitanArtifact.titanId;
  9054. },
  9055. },
  9056. 10029: {
  9057. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  9058. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  9059. isWeCanDo: () => {
  9060. return this.questInfo['inventoryGet']?.consumable[55] > 0
  9061. },
  9062. },
  9063. 10030: {
  9064. description: 'Улучши облик любого героя 1 раз', // Готово
  9065. doItCall: () => {
  9066. const upSkin = this.getUpgradeSkin();
  9067. return [
  9068. {
  9069. name: "heroSkinUpgrade",
  9070. args: {
  9071. heroId: upSkin.heroId,
  9072. skinId: upSkin.skinId
  9073. },
  9074. ident: `heroSkinUpgrade`
  9075. }
  9076. ];
  9077. },
  9078. isWeCanDo: () => {
  9079. const upgradeSkin = this.getUpgradeSkin();
  9080. return upgradeSkin.heroId;
  9081. },
  9082. },
  9083. 10031: {
  9084. description: 'Победи в 6 боях Турнира Стихий', // --------------
  9085. doItFunc: testTitanArena,
  9086. isWeCanDo: () => false,
  9087. },
  9088. 10043: {
  9089. description: 'Начни или присоеденись к Приключению', // --------------
  9090. isWeCanDo: () => false,
  9091. },
  9092. 10044: {
  9093. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  9094. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  9095. isWeCanDo: () => {
  9096. return this.questInfo['inventoryGet']?.consumable[90] > 0
  9097. },
  9098. },
  9099. 10046: {
  9100. /**
  9101. * TODO: Watch Adventure
  9102. * TODO: Смотреть приключение
  9103. */
  9104. description: 'Открой 3 сундука в Приключениях',
  9105. isWeCanDo: () => false,
  9106. },
  9107. 10047: {
  9108. description: 'Набери 150 очков активности в Гильдии', // Готово
  9109. doItCall: () => {
  9110. const enchantRune = this.getEnchantRune();
  9111. return [
  9112. {
  9113. name: "heroEnchantRune",
  9114. args: {
  9115. heroId: enchantRune.heroId,
  9116. tier: enchantRune.tier,
  9117. items: {
  9118. consumable: { [enchantRune.itemId]: 1 }
  9119. }
  9120. },
  9121. ident: `heroEnchantRune`
  9122. }
  9123. ];
  9124. },
  9125. isWeCanDo: () => {
  9126. const userInfo = this.questInfo['userGetInfo'];
  9127. const enchantRune = this.getEnchantRune();
  9128. return enchantRune.heroId && userInfo.gold > 1e3;
  9129. },
  9130. },
  9131. };
  9132.  
  9133. constructor(resolve, reject, questInfo) {
  9134. this.resolve = resolve;
  9135. this.reject = reject;
  9136. }
  9137.  
  9138. init(questInfo) {
  9139. this.questInfo = questInfo;
  9140. this.isAuto = false;
  9141. }
  9142.  
  9143. async autoInit(isAuto) {
  9144. this.isAuto = isAuto || false;
  9145. const quests = {};
  9146. const calls = this.callsList.map(name => ({
  9147. name, args: {}, ident: name
  9148. }))
  9149. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  9150. for (const call of result) {
  9151. quests[call.ident] = call.result.response;
  9152. }
  9153. this.questInfo = quests;
  9154. }
  9155.  
  9156. async start() {
  9157. const weCanDo = [];
  9158. const selectedActions = getSaveVal('selectedActions', {});
  9159. for (let quest of this.questInfo['questGetAll']) {
  9160. if (quest.id in this.dataQuests && quest.state == 1) {
  9161. if (!selectedActions[quest.id]) {
  9162. selectedActions[quest.id] = {
  9163. checked: false
  9164. }
  9165. }
  9166.  
  9167. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  9168. if (!isWeCanDo.call(this)) {
  9169. continue;
  9170. }
  9171.  
  9172. weCanDo.push({
  9173. name: quest.id,
  9174. label: I18N(`QUEST_${quest.id}`),
  9175. checked: selectedActions[quest.id].checked
  9176. });
  9177. }
  9178. }
  9179.  
  9180. if (!weCanDo.length) {
  9181. this.end(I18N('NOTHING_TO_DO'));
  9182. return;
  9183. }
  9184.  
  9185. console.log(weCanDo);
  9186. let taskList = [];
  9187. if (this.isAuto) {
  9188. taskList = weCanDo;
  9189. } else {
  9190. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  9191. { msg: I18N('BTN_DO_IT'), result: true },
  9192. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9193. ], weCanDo);
  9194. if (!answer) {
  9195. this.end('');
  9196. return;
  9197. }
  9198. taskList = popup.getCheckBoxes();
  9199. taskList.forEach(e => {
  9200. selectedActions[e.name].checked = e.checked;
  9201. });
  9202. setSaveVal('selectedActions', selectedActions);
  9203. }
  9204.  
  9205. const calls = [];
  9206. let countChecked = 0;
  9207. for (const task of taskList) {
  9208. if (task.checked) {
  9209. countChecked++;
  9210. const quest = this.dataQuests[task.name]
  9211. console.log(quest.description);
  9212.  
  9213. if (quest.doItCall) {
  9214. const doItCall = quest.doItCall.call(this);
  9215. calls.push(...doItCall);
  9216. }
  9217. }
  9218. }
  9219.  
  9220. if (!countChecked) {
  9221. this.end(I18N('NOT_QUEST_COMPLETED'));
  9222. return;
  9223. }
  9224.  
  9225. const result = await Send(JSON.stringify({ calls }));
  9226. if (result.error) {
  9227. console.error(result.error, result.error.call)
  9228. }
  9229. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  9230. }
  9231.  
  9232. errorHandling(error) {
  9233. //console.error(error);
  9234. let errorInfo = error.toString() + '\n';
  9235. try {
  9236. const errorStack = error.stack.split('\n');
  9237. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9238. errorInfo += errorStack.slice(0, endStack).join('\n');
  9239. } catch (e) {
  9240. errorInfo += error.stack;
  9241. }
  9242. copyText(errorInfo);
  9243. }
  9244.  
  9245. skillCost(lvl) {
  9246. return 573 * lvl ** 0.9 + lvl ** 2.379;
  9247. }
  9248.  
  9249. getUpgradeSkills() {
  9250. const heroes = Object.values(this.questInfo['heroGetAll']);
  9251. const upgradeSkills = [
  9252. { heroId: 0, slotId: 0, value: 130 },
  9253. { heroId: 0, slotId: 0, value: 130 },
  9254. { heroId: 0, slotId: 0, value: 130 },
  9255. ];
  9256. const skillLib = lib.getData('skill');
  9257. /**
  9258. * color - 1 (белый) открывает 1 навык
  9259. * color - 2 (зеленый) открывает 2 навык
  9260. * color - 4 (синий) открывает 3 навык
  9261. * color - 7 (фиолетовый) открывает 4 навык
  9262. */
  9263. const colors = [1, 2, 4, 7];
  9264. for (const hero of heroes) {
  9265. const level = hero.level;
  9266. const color = hero.color;
  9267. for (let skillId in hero.skills) {
  9268. const tier = skillLib[skillId].tier;
  9269. const sVal = hero.skills[skillId];
  9270. if (color < colors[tier] || tier < 1 || tier > 4) {
  9271. continue;
  9272. }
  9273. for (let upSkill of upgradeSkills) {
  9274. if (sVal < upSkill.value && sVal < level) {
  9275. upSkill.value = sVal;
  9276. upSkill.heroId = hero.id;
  9277. upSkill.skill = tier;
  9278. break;
  9279. }
  9280. }
  9281. }
  9282. }
  9283. return upgradeSkills;
  9284. }
  9285.  
  9286. getUpgradeArtifact() {
  9287. const heroes = Object.values(this.questInfo['heroGetAll']);
  9288. const inventory = this.questInfo['inventoryGet'];
  9289. const upArt = { heroId: 0, slotId: 0, level: 100 };
  9290.  
  9291. const heroLib = lib.getData('hero');
  9292. const artifactLib = lib.getData('artifact');
  9293.  
  9294. for (const hero of heroes) {
  9295. const heroInfo = heroLib[hero.id];
  9296. const level = hero.level
  9297. if (level < 20) {
  9298. continue;
  9299. }
  9300.  
  9301. for (let slotId in hero.artifacts) {
  9302. const art = hero.artifacts[slotId];
  9303. /* Текущая звезданость арта */
  9304. const star = art.star;
  9305. if (!star) {
  9306. continue;
  9307. }
  9308. /* Текущий уровень арта */
  9309. const level = art.level;
  9310. if (level >= 100) {
  9311. continue;
  9312. }
  9313. /* Идентификатор арта в библиотеке */
  9314. const artifactId = heroInfo.artifacts[slotId];
  9315. const artInfo = artifactLib.id[artifactId];
  9316. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  9317.  
  9318. const costСurrency = Object.keys(costNextLevel).pop();
  9319. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9320. const costId = costValues[0];
  9321. const costValue = +costValues[1];
  9322.  
  9323. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9324. if (level < upArt.level && inventory[costСurrency][costId] >= costValue) {
  9325. upArt.level = level;
  9326. upArt.heroId = hero.id;
  9327. upArt.slotId = slotId;
  9328. upArt.costСurrency = costСurrency;
  9329. upArt.costId = costId;
  9330. upArt.costValue = costValue;
  9331. }
  9332. }
  9333. }
  9334. return upArt;
  9335. }
  9336.  
  9337. getUpgradeSkin() {
  9338. const heroes = Object.values(this.questInfo['heroGetAll']);
  9339. const inventory = this.questInfo['inventoryGet'];
  9340. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  9341.  
  9342. const skinLib = lib.getData('skin');
  9343.  
  9344. for (const hero of heroes) {
  9345. const level = hero.level
  9346. if (level < 20) {
  9347. continue;
  9348. }
  9349.  
  9350. for (let skinId in hero.skins) {
  9351. /* Текущий уровень скина */
  9352. const level = hero.skins[skinId];
  9353. if (level >= 60) {
  9354. continue;
  9355. }
  9356. /* Идентификатор скина в библиотеке */
  9357. const skinInfo = skinLib[skinId];
  9358. if (!skinInfo.statData.levels?.[level + 1]) {
  9359. continue;
  9360. }
  9361. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  9362.  
  9363. const costСurrency = Object.keys(costNextLevel).pop();
  9364. const costСurrencyId = Object.keys(costNextLevel[costСurrency]).pop();
  9365. const costValue = +costNextLevel[costСurrency][costСurrencyId];
  9366.  
  9367. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9368. if (level < upSkin.level &&
  9369. costValue < upSkin.cost &&
  9370. inventory[costСurrency][costСurrencyId] >= costValue) {
  9371. upSkin.cost = costValue;
  9372. upSkin.level = level;
  9373. upSkin.heroId = hero.id;
  9374. upSkin.skinId = skinId;
  9375. upSkin.costСurrency = costСurrency;
  9376. upSkin.costСurrencyId = costСurrencyId;
  9377. }
  9378. }
  9379. }
  9380. return upSkin;
  9381. }
  9382.  
  9383. getUpgradeTitanArtifact() {
  9384. const titans = Object.values(this.questInfo['titanGetAll']);
  9385. const inventory = this.questInfo['inventoryGet'];
  9386. const userInfo = this.questInfo['userGetInfo'];
  9387. const upArt = { titanId: 0, slotId: 0, level: 120 };
  9388.  
  9389. const titanLib = lib.getData('titan');
  9390. const artTitanLib = lib.getData('titanArtifact');
  9391.  
  9392. for (const titan of titans) {
  9393. const titanInfo = titanLib[titan.id];
  9394. // const level = titan.level
  9395. // if (level < 20) {
  9396. // continue;
  9397. // }
  9398.  
  9399. for (let slotId in titan.artifacts) {
  9400. const art = titan.artifacts[slotId];
  9401. /* Текущая звезданость арта */
  9402. const star = art.star;
  9403. if (!star) {
  9404. continue;
  9405. }
  9406. /* Текущий уровень арта */
  9407. const level = art.level;
  9408. if (level >= 120) {
  9409. continue;
  9410. }
  9411. /* Идентификатор арта в библиотеке */
  9412. const artifactId = titanInfo.artifacts[slotId];
  9413. const artInfo = artTitanLib.id[artifactId];
  9414. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  9415.  
  9416. const costСurrency = Object.keys(costNextLevel).pop();
  9417. let costValue = 0;
  9418. let currentValue = 0;
  9419. if (costСurrency == 'gold') {
  9420. costValue = costNextLevel[costСurrency];
  9421. currentValue = userInfo.gold;
  9422. } else {
  9423. const costValues = Object.entries(costNextLevel[costСurrency]).pop();
  9424. const costId = costValues[0];
  9425. costValue = +costValues[1];
  9426. currentValue = inventory[costСurrency][costId];
  9427. }
  9428.  
  9429. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9430. if (level < upArt.level && currentValue >= costValue) {
  9431. upArt.level = level;
  9432. upArt.titanId = titan.id;
  9433. upArt.slotId = slotId;
  9434. break;
  9435. }
  9436. }
  9437. }
  9438. return upArt;
  9439. }
  9440.  
  9441. getEnchantRune() {
  9442. const heroes = Object.values(this.questInfo['heroGetAll']);
  9443. const inventory = this.questInfo['inventoryGet'];
  9444. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  9445. for (let i = 1; i <= 4; i++) {
  9446. if (inventory.consumable[i] > 0) {
  9447. enchRune.itemId = i;
  9448. break;
  9449. }
  9450. return enchRune;
  9451. }
  9452.  
  9453. const runeLib = lib.getData('rune');
  9454. const runeLvls = Object.values(runeLib.level);
  9455. /**
  9456. * color - 4 (синий) открывает 1 и 2 символ
  9457. * color - 7 (фиолетовый) открывает 3 символ
  9458. * color - 8 (фиолетовый +1) открывает 4 символ
  9459. * color - 9 (фиолетовый +2) открывает 5 символ
  9460. */
  9461. // TODO: кажется надо учесть уровень команды
  9462. const colors = [4, 4, 7, 8, 9];
  9463. for (const hero of heroes) {
  9464. const color = hero.color;
  9465.  
  9466.  
  9467. for (let runeTier in hero.runes) {
  9468. /* Проверка на доступность руны */
  9469. if (color < colors[runeTier]) {
  9470. continue;
  9471. }
  9472. /* Текущий опыт руны */
  9473. const exp = hero.runes[runeTier];
  9474. if (exp >= 43750) {
  9475. continue;
  9476. }
  9477.  
  9478. let level = 0;
  9479. if (exp) {
  9480. for (let lvl of runeLvls) {
  9481. if (exp >= lvl.enchantValue) {
  9482. level = lvl.level;
  9483. } else {
  9484. break;
  9485. }
  9486. }
  9487. }
  9488. /** Уровень героя необходимый для уровня руны */
  9489. const heroLevel = runeLib.level[level].heroLevel;
  9490. if (hero.level < heroLevel) {
  9491. continue;
  9492. }
  9493.  
  9494. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  9495. if (exp < enchRune.exp) {
  9496. enchRune.exp = exp;
  9497. enchRune.heroId = hero.id;
  9498. enchRune.tier = runeTier;
  9499. break;
  9500. }
  9501. }
  9502. }
  9503. return enchRune;
  9504. }
  9505.  
  9506. getOutlandChest() {
  9507. const bosses = this.questInfo['bossGetAll'];
  9508.  
  9509. const calls = [];
  9510.  
  9511. for (let boss of bosses) {
  9512. if (boss.mayRaid) {
  9513. calls.push({
  9514. name: "bossRaid",
  9515. args: {
  9516. bossId: boss.id
  9517. },
  9518. ident: "bossRaid_" + boss.id
  9519. });
  9520. calls.push({
  9521. name: "bossOpenChest",
  9522. args: {
  9523. bossId: boss.id,
  9524. amount: 1,
  9525. starmoney: 0
  9526. },
  9527. ident: "bossOpenChest_" + boss.id
  9528. });
  9529. } else if (boss.chestId == 1) {
  9530. calls.push({
  9531. name: "bossOpenChest",
  9532. args: {
  9533. bossId: boss.id,
  9534. amount: 1,
  9535. starmoney: 0
  9536. },
  9537. ident: "bossOpenChest_" + boss.id
  9538. });
  9539. }
  9540. }
  9541.  
  9542. return calls;
  9543. }
  9544.  
  9545. getExpHero() {
  9546. const heroes = Object.values(this.questInfo['heroGetAll']);
  9547. const inventory = this.questInfo['inventoryGet'];
  9548. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  9549. /** зелья опыта (consumable 9, 10, 11, 12) */
  9550. for (let i = 9; i <= 12; i++) {
  9551. if (inventory.consumable[i]) {
  9552. expHero.libId = i;
  9553. break;
  9554. }
  9555. }
  9556.  
  9557. for (const hero of heroes) {
  9558. const exp = hero.xp;
  9559. if (exp < expHero.exp) {
  9560. expHero.heroId = hero.id;
  9561. }
  9562. }
  9563. return expHero;
  9564. }
  9565.  
  9566. getHeroIdTitanGift() {
  9567. const heroes = Object.values(this.questInfo['heroGetAll']);
  9568. const inventory = this.questInfo['inventoryGet'];
  9569. const user = this.questInfo['userGetInfo'];
  9570. const titanGiftLib = lib.getData('titanGift');
  9571. /** Искры */
  9572. const titanGift = inventory.consumable[24];
  9573. let heroId = 0;
  9574. let minLevel = 30;
  9575.  
  9576. if (titanGift < 250 || user.gold < 7000) {
  9577. return 0;
  9578. }
  9579.  
  9580. for (const hero of heroes) {
  9581. if (hero.titanGiftLevel >= 30) {
  9582. continue;
  9583. }
  9584.  
  9585. if (!hero.titanGiftLevel) {
  9586. return hero.id;
  9587. }
  9588.  
  9589. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  9590. if (minLevel > hero.titanGiftLevel &&
  9591. titanGift >= cost.consumable[24] &&
  9592. user.gold >= cost.gold
  9593. ) {
  9594. minLevel = hero.titanGiftLevel;
  9595. heroId = hero.id;
  9596. }
  9597. }
  9598.  
  9599. return heroId;
  9600. }
  9601.  
  9602. end(status) {
  9603. setProgress(status, true);
  9604. this.resolve();
  9605. }
  9606. }
  9607.  
  9608. this.questRun = dailyQuests;
  9609.  
  9610. function testDoYourBest() {
  9611. return new Promise((resolve, reject) => {
  9612. const doIt = new doYourBest(resolve, reject);
  9613. doIt.start();
  9614. });
  9615. }
  9616.  
  9617. /**
  9618. * Do everything button
  9619. *
  9620. * Кнопка сделать все
  9621. */
  9622. class doYourBest {
  9623.  
  9624. funcList = [
  9625. {
  9626. name: 'getOutland',
  9627. label: I18N('ASSEMBLE_OUTLAND'),
  9628. checked: false
  9629. },
  9630. {
  9631. name: 'testTower',
  9632. label: I18N('PASS_THE_TOWER'),
  9633. checked: false
  9634. },
  9635. {
  9636. name: 'checkExpedition',
  9637. label: I18N('CHECK_EXPEDITIONS'),
  9638. checked: false
  9639. },
  9640. {
  9641. name: 'testTitanArena',
  9642. label: I18N('COMPLETE_TOE'),
  9643. checked: false
  9644. },
  9645. {
  9646. name: 'mailGetAll',
  9647. label: I18N('COLLECT_MAIL'),
  9648. checked: false
  9649. },
  9650. {
  9651. name: 'collectAllStuff',
  9652. label: I18N('COLLECT_MISC'),
  9653. title: I18N('COLLECT_MISC_TITLE'),
  9654. checked: false
  9655. },
  9656. {
  9657. name: 'getDailyBonus',
  9658. label: I18N('DAILY_BONUS'),
  9659. checked: false
  9660. },
  9661. {
  9662. name: 'dailyQuests',
  9663. label: I18N('DO_DAILY_QUESTS'),
  9664. checked: false
  9665. },
  9666. {
  9667. name: 'rollAscension',
  9668. label: I18N('SEER_TITLE'),
  9669. checked: false
  9670. },
  9671. {
  9672. name: 'questAllFarm',
  9673. label: I18N('COLLECT_QUEST_REWARDS'),
  9674. checked: false
  9675. },
  9676. {
  9677. name: 'testDungeon',
  9678. label: I18N('COMPLETE_DUNGEON'),
  9679. checked: false
  9680. },
  9681. {
  9682. name: 'synchronization',
  9683. label: I18N('MAKE_A_SYNC'),
  9684. checked: false
  9685. },
  9686. {
  9687. name: 'reloadGame',
  9688. label: I18N('RELOAD_GAME'),
  9689. checked: false
  9690. },
  9691. ];
  9692.  
  9693. functions = {
  9694. getOutland,
  9695. testTower,
  9696. checkExpedition,
  9697. testTitanArena,
  9698. mailGetAll,
  9699. collectAllStuff: async () => {
  9700. await offerFarmAllReward();
  9701. 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"}]}');
  9702. },
  9703. dailyQuests: async function () {
  9704. const quests = new dailyQuests(() => { }, () => { });
  9705. await quests.autoInit(true);
  9706. await quests.start();
  9707. },
  9708. rollAscension,
  9709. getDailyBonus,
  9710. questAllFarm,
  9711. testDungeon,
  9712. synchronization: async () => {
  9713. cheats.refreshGame();
  9714. },
  9715. reloadGame: async () => {
  9716. location.reload();
  9717. },
  9718. }
  9719.  
  9720. constructor(resolve, reject, questInfo) {
  9721. this.resolve = resolve;
  9722. this.reject = reject;
  9723. this.questInfo = questInfo
  9724. }
  9725.  
  9726. async start() {
  9727. const selectedDoIt = getSaveVal('selectedDoIt', {});
  9728.  
  9729. this.funcList.forEach(task => {
  9730. if (!selectedDoIt[task.name]) {
  9731. selectedDoIt[task.name] = {
  9732. checked: task.checked
  9733. }
  9734. } else {
  9735. task.checked = selectedDoIt[task.name].checked
  9736. }
  9737. });
  9738.  
  9739. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  9740. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9741. { msg: I18N('BTN_GO'), result: true },
  9742. ], this.funcList);
  9743.  
  9744. if (!answer) {
  9745. this.end('');
  9746. return;
  9747. }
  9748.  
  9749. const taskList = popup.getCheckBoxes();
  9750. taskList.forEach(task => {
  9751. selectedDoIt[task.name].checked = task.checked;
  9752. });
  9753. setSaveVal('selectedDoIt', selectedDoIt);
  9754. for (const task of popup.getCheckBoxes()) {
  9755. if (task.checked) {
  9756. try {
  9757. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  9758. await this.functions[task.name]();
  9759. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  9760. } catch (error) {
  9761. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  9762. { msg: I18N('BTN_NO'), result: false },
  9763. { msg: I18N('BTN_YES'), result: true },
  9764. ])) {
  9765. this.errorHandling(error);
  9766. }
  9767. }
  9768. }
  9769. }
  9770. setTimeout((msg) => {
  9771. this.end(msg);
  9772. }, 2000, I18N('ALL_TASK_COMPLETED'));
  9773. return;
  9774. }
  9775.  
  9776. errorHandling(error) {
  9777. //console.error(error);
  9778. let errorInfo = error.toString() + '\n';
  9779. try {
  9780. const errorStack = error.stack.split('\n');
  9781. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  9782. errorInfo += errorStack.slice(0, endStack).join('\n');
  9783. } catch (e) {
  9784. errorInfo += error.stack;
  9785. }
  9786. copyText(errorInfo);
  9787. }
  9788.  
  9789. end(status) {
  9790. setProgress(status, true);
  9791. this.resolve();
  9792. }
  9793. }
  9794.  
  9795. /**
  9796. * Passing the adventure along the specified route
  9797. *
  9798. * Прохождение приключения по указанному маршруту
  9799. */
  9800. function testAdventure(type) {
  9801. return new Promise((resolve, reject) => {
  9802. const bossBattle = new executeAdventure(resolve, reject);
  9803. bossBattle.start(type);
  9804. });
  9805. }
  9806.  
  9807. /**
  9808. * Passing the adventure along the specified route
  9809. *
  9810. * Прохождение приключения по указанному маршруту
  9811. */
  9812. class executeAdventure {
  9813.  
  9814. type = 'default';
  9815.  
  9816. actions = {
  9817. default: {
  9818. getInfo: "adventure_getInfo",
  9819. startBattle: 'adventure_turnStartBattle',
  9820. endBattle: 'adventure_endBattle',
  9821. collectBuff: 'adventure_turnCollectBuff'
  9822. },
  9823. solo: {
  9824. getInfo: "adventureSolo_getInfo",
  9825. startBattle: 'adventureSolo_turnStartBattle',
  9826. endBattle: 'adventureSolo_endBattle',
  9827. collectBuff: 'adventureSolo_turnCollectBuff'
  9828. }
  9829. }
  9830.  
  9831. terminatеReason = I18N('UNKNOWN');
  9832. callAdventureInfo = {
  9833. name: "adventure_getInfo",
  9834. args: {},
  9835. ident: "adventure_getInfo"
  9836. }
  9837. callTeamGetAll = {
  9838. name: "teamGetAll",
  9839. args: {},
  9840. ident: "teamGetAll"
  9841. }
  9842. callTeamGetFavor = {
  9843. name: "teamGetFavor",
  9844. args: {},
  9845. ident: "teamGetFavor"
  9846. }
  9847. callStartBattle = {
  9848. name: "adventure_turnStartBattle",
  9849. args: {},
  9850. ident: "body"
  9851. }
  9852. callEndBattle = {
  9853. name: "adventure_endBattle",
  9854. args: {
  9855. result: {},
  9856. progress: {},
  9857. },
  9858. ident: "body"
  9859. }
  9860. callCollectBuff = {
  9861. name: "adventure_turnCollectBuff",
  9862. args: {},
  9863. ident: "body"
  9864. }
  9865.  
  9866. constructor(resolve, reject) {
  9867. this.resolve = resolve;
  9868. this.reject = reject;
  9869. }
  9870.  
  9871. async start(type) {
  9872. this.type = type || this.type;
  9873. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  9874. const data = await Send(JSON.stringify({
  9875. calls: [
  9876. this.callAdventureInfo,
  9877. this.callTeamGetAll,
  9878. this.callTeamGetFavor
  9879. ]
  9880. }));
  9881. return this.checkAdventureInfo(data.results);
  9882. }
  9883.  
  9884. async getPath() {
  9885. const oldVal = getSaveVal('adventurePath', '');
  9886. const keyPath = `adventurePath:${this.mapIdent}`;
  9887. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  9888. {
  9889. msg: I18N('START_ADVENTURE'),
  9890. placeholder: '1,2,3,4,5,6',
  9891. isInput: true,
  9892. default: getSaveVal(keyPath, oldVal)
  9893. },
  9894. {
  9895. msg: I18N('BTN_CANCEL'),
  9896. result: false,
  9897. isCancel: true
  9898. },
  9899. ]);
  9900. if (!answer) {
  9901. this.terminatеReason = I18N('BTN_CANCELED');
  9902. return false;
  9903. }
  9904.  
  9905. let path = answer.split(',');
  9906. if (path.length < 2) {
  9907. path = answer.split('-');
  9908. }
  9909. if (path.length < 2) {
  9910. this.terminatеReason = I18N('MUST_TWO_POINTS');
  9911. return false;
  9912. }
  9913.  
  9914. for (let p in path) {
  9915. path[p] = +path[p].trim()
  9916. if (Number.isNaN(path[p])) {
  9917. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  9918. return false;
  9919. }
  9920. }
  9921.  
  9922. if (!this.checkPath(path)) {
  9923. return false;
  9924. }
  9925. setSaveVal(keyPath, answer);
  9926. return path;
  9927. }
  9928.  
  9929. checkPath(path) {
  9930. for (let i = 0; i < path.length - 1; i++) {
  9931. const currentPoint = path[i];
  9932. const nextPoint = path[i + 1];
  9933.  
  9934. const isValidPath = this.paths.some(p =>
  9935. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  9936. (p.from_id === nextPoint && p.to_id === currentPoint)
  9937. );
  9938.  
  9939. if (!isValidPath) {
  9940. this.terminatеReason = I18N('INCORRECT_WAY', {
  9941. from: currentPoint,
  9942. to: nextPoint,
  9943. });
  9944. return false;
  9945. }
  9946. }
  9947.  
  9948. return true;
  9949. }
  9950.  
  9951. async checkAdventureInfo(data) {
  9952. this.advInfo = data[0].result.response;
  9953. if (!this.advInfo) {
  9954. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  9955. return this.end();
  9956. }
  9957. const heroesTeam = data[1].result.response.adventure_hero;
  9958. const favor = data[2]?.result.response.adventure_hero;
  9959. const heroes = heroesTeam.slice(0, 5);
  9960. const pet = heroesTeam[5];
  9961. this.args = {
  9962. pet,
  9963. heroes,
  9964. favor,
  9965. path: [],
  9966. broadcast: false
  9967. }
  9968. const advUserInfo = this.advInfo.users[userInfo.id];
  9969. this.turnsLeft = advUserInfo.turnsLeft;
  9970. this.currentNode = advUserInfo.currentNode;
  9971. this.nodes = this.advInfo.nodes;
  9972. this.paths = this.advInfo.paths;
  9973. this.mapIdent = this.advInfo.mapIdent;
  9974.  
  9975. this.path = await this.getPath();
  9976. if (!this.path) {
  9977. return this.end();
  9978. }
  9979.  
  9980. if (this.currentNode == 1 && this.path[0] != 1) {
  9981. this.path.unshift(1);
  9982. }
  9983.  
  9984. return this.loop();
  9985. }
  9986.  
  9987. async loop() {
  9988. const position = this.path.indexOf(+this.currentNode);
  9989. if (!(~position)) {
  9990. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  9991. return this.end();
  9992. }
  9993. this.path = this.path.slice(position);
  9994. if ((this.path.length - 1) > this.turnsLeft &&
  9995. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  9996. { msg: I18N('YES_CONTINUE'), result: false },
  9997. { msg: I18N('BTN_NO'), result: true },
  9998. ])) {
  9999. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  10000. return this.end();
  10001. }
  10002. const toPath = [];
  10003. for (const nodeId of this.path) {
  10004. if (!this.turnsLeft) {
  10005. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  10006. return this.end();
  10007. }
  10008. toPath.push(nodeId);
  10009. console.log(toPath);
  10010. if (toPath.length > 1) {
  10011. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  10012. }
  10013. if (nodeId == this.currentNode) {
  10014. continue;
  10015. }
  10016.  
  10017. const nodeInfo = this.getNodeInfo(nodeId);
  10018. if (nodeInfo.type == 'TYPE_COMBAT') {
  10019. if (nodeInfo.state == 'empty') {
  10020. this.turnsLeft--;
  10021. continue;
  10022. }
  10023.  
  10024. /**
  10025. * Disable regular battle cancellation
  10026. *
  10027. * Отключаем штатную отменую боя
  10028. */
  10029. isCancalBattle = false;
  10030. if (await this.battle(toPath)) {
  10031. this.turnsLeft--;
  10032. toPath.splice(0, toPath.indexOf(nodeId));
  10033. nodeInfo.state = 'empty';
  10034. isCancalBattle = true;
  10035. continue;
  10036. }
  10037. isCancalBattle = true;
  10038. return this.end()
  10039. }
  10040.  
  10041. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  10042. const buff = this.checkBuff(nodeInfo);
  10043. if (buff == null) {
  10044. continue;
  10045. }
  10046.  
  10047. if (await this.collectBuff(buff, toPath)) {
  10048. this.turnsLeft--;
  10049. toPath.splice(0, toPath.indexOf(nodeId));
  10050. continue;
  10051. }
  10052. this.terminatеReason = I18N('BUFF_GET_ERROR');
  10053. return this.end();
  10054. }
  10055. }
  10056. this.terminatеReason = I18N('SUCCESS');
  10057. return this.end();
  10058. }
  10059.  
  10060. /**
  10061. * Carrying out a fight
  10062. *
  10063. * Проведение боя
  10064. */
  10065. async battle(path, preCalc = true) {
  10066. const data = await this.startBattle(path);
  10067. try {
  10068. const battle = data.results[0].result.response.battle;
  10069. const result = await Calc(battle);
  10070. if (result.result.win) {
  10071. const info = await this.endBattle(result);
  10072. if (info.results[0].result.response?.error) {
  10073. this.terminatеReason = I18N('BATTLE_END_ERROR');
  10074. return false;
  10075. }
  10076. } else {
  10077. await this.cancelBattle(result);
  10078.  
  10079. if (preCalc && await this.preCalcBattle(battle)) {
  10080. path = path.slice(-2);
  10081. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  10082. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  10083. const result = await this.battle(path, false);
  10084. if (result) {
  10085. setProgress(I18N('VICTORY'));
  10086. return true;
  10087. }
  10088. }
  10089. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  10090. return false;
  10091. }
  10092. return false;
  10093. }
  10094. } catch (error) {
  10095. console.error(error);
  10096. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  10097. { msg: I18N('BTN_NO'), result: false },
  10098. { msg: I18N('BTN_YES'), result: true },
  10099. ])) {
  10100. this.errorHandling(error, data);
  10101. }
  10102. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  10103. return false;
  10104. }
  10105. return true;
  10106. }
  10107.  
  10108. /**
  10109. * Recalculate battles
  10110. *
  10111. * Прерасчтет битвы
  10112. */
  10113. async preCalcBattle(battle) {
  10114. const countTestBattle = getInput('countTestBattle');
  10115. for (let i = 0; i < countTestBattle; i++) {
  10116. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  10117. const result = await Calc(battle);
  10118. if (result.result.win) {
  10119. console.log(i, countTestBattle);
  10120. return true;
  10121. }
  10122. }
  10123. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  10124. return false;
  10125. }
  10126.  
  10127. /**
  10128. * Starts a fight
  10129. *
  10130. * Начинает бой
  10131. */
  10132. startBattle(path) {
  10133. this.args.path = path;
  10134. this.callStartBattle.name = this.actions[this.type].startBattle;
  10135. this.callStartBattle.args = this.args
  10136. const calls = [this.callStartBattle];
  10137. return Send(JSON.stringify({ calls }));
  10138. }
  10139.  
  10140. cancelBattle(battle) {
  10141. const fixBattle = function (heroes) {
  10142. for (const ids in heroes) {
  10143. const hero = heroes[ids];
  10144. hero.energy = random(1, 999);
  10145. if (hero.hp > 0) {
  10146. hero.hp = random(1, hero.hp);
  10147. }
  10148. }
  10149. }
  10150. fixBattle(battle.progress[0].attackers.heroes);
  10151. fixBattle(battle.progress[0].defenders.heroes);
  10152. return this.endBattle(battle);
  10153. }
  10154.  
  10155. /**
  10156. * Ends the fight
  10157. *
  10158. * Заканчивает бой
  10159. */
  10160. endBattle(battle) {
  10161. this.callEndBattle.name = this.actions[this.type].endBattle;
  10162. this.callEndBattle.args.result = battle.result
  10163. this.callEndBattle.args.progress = battle.progress
  10164. const calls = [this.callEndBattle];
  10165. return Send(JSON.stringify({ calls }));
  10166. }
  10167.  
  10168. /**
  10169. * Checks if you can get a buff
  10170. *
  10171. * Проверяет можно ли получить баф
  10172. */
  10173. checkBuff(nodeInfo) {
  10174. let id = null;
  10175. let value = 0;
  10176. for (const buffId in nodeInfo.buffs) {
  10177. const buff = nodeInfo.buffs[buffId];
  10178. if (buff.owner == null && buff.value > value) {
  10179. id = buffId;
  10180. value = buff.value;
  10181. }
  10182. }
  10183. nodeInfo.buffs[id].owner = 'Я';
  10184. return id;
  10185. }
  10186.  
  10187. /**
  10188. * Collects a buff
  10189. *
  10190. * Собирает баф
  10191. */
  10192. async collectBuff(buff, path) {
  10193. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  10194. this.callCollectBuff.args = { buff, path };
  10195. const calls = [this.callCollectBuff];
  10196. return Send(JSON.stringify({ calls }));
  10197. }
  10198.  
  10199. getNodeInfo(nodeId) {
  10200. return this.nodes.find(node => node.id == nodeId);
  10201. }
  10202.  
  10203. errorHandling(error, data) {
  10204. //console.error(error);
  10205. let errorInfo = error.toString() + '\n';
  10206. try {
  10207. const errorStack = error.stack.split('\n');
  10208. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  10209. errorInfo += errorStack.slice(0, endStack).join('\n');
  10210. } catch (e) {
  10211. errorInfo += error.stack;
  10212. }
  10213. if (data) {
  10214. errorInfo += '\nData: ' + JSON.stringify(data);
  10215. }
  10216. copyText(errorInfo);
  10217. }
  10218.  
  10219. end() {
  10220. isCancalBattle = true;
  10221. setProgress(this.terminatеReason, true);
  10222. console.log(this.terminatеReason);
  10223. this.resolve();
  10224. }
  10225. }
  10226.  
  10227. /**
  10228. * Passage of brawls
  10229. *
  10230. * Прохождение потасовок
  10231. */
  10232. function testBrawls(isAuto) {
  10233. return new Promise((resolve, reject) => {
  10234. const brawls = new executeBrawls(resolve, reject);
  10235. brawls.start(brawlsPack, isAuto);
  10236. });
  10237. }
  10238. /**
  10239. * Passage of brawls
  10240. *
  10241. * Прохождение потасовок
  10242. */
  10243. class executeBrawls {
  10244. callBrawlQuestGetInfo = {
  10245. name: "brawl_questGetInfo",
  10246. args: {},
  10247. ident: "brawl_questGetInfo"
  10248. }
  10249. callBrawlFindEnemies = {
  10250. name: "brawl_findEnemies",
  10251. args: {},
  10252. ident: "brawl_findEnemies"
  10253. }
  10254. callBrawlQuestFarm = {
  10255. name: "brawl_questFarm",
  10256. args: {},
  10257. ident: "brawl_questFarm"
  10258. }
  10259. callUserGetInfo = {
  10260. name: "userGetInfo",
  10261. args: {},
  10262. ident: "userGetInfo"
  10263. }
  10264. callTeamGetMaxUpgrade = {
  10265. name: "teamGetMaxUpgrade",
  10266. args: {},
  10267. ident: "teamGetMaxUpgrade"
  10268. }
  10269. callBrawlGetInfo = {
  10270. name: "brawl_getInfo",
  10271. args: {},
  10272. ident: "brawl_getInfo"
  10273. }
  10274.  
  10275. stats = {
  10276. win: 0,
  10277. loss: 0,
  10278. count: 0,
  10279. }
  10280.  
  10281. stage = {
  10282. '3': 1,
  10283. '7': 2,
  10284. '12': 3,
  10285. }
  10286.  
  10287. attempts = 0;
  10288.  
  10289. constructor(resolve, reject) {
  10290. this.resolve = resolve;
  10291. this.reject = reject;
  10292. }
  10293.  
  10294. async start(args, isAuto) {
  10295. this.isAuto = isAuto;
  10296. this.args = args;
  10297. isCancalBattle = false;
  10298. this.brawlInfo = await this.getBrawlInfo();
  10299. this.attempts = this.brawlInfo.attempts;
  10300.  
  10301. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  10302. this.end(I18N('DONT_HAVE_LIVES'));
  10303. return;
  10304. }
  10305.  
  10306. while (1) {
  10307. if (!isBrawlsAutoStart) {
  10308. this.end(I18N('BTN_CANCELED'));
  10309. return;
  10310. }
  10311.  
  10312. const maxStage = this.brawlInfo.questInfo.stage;
  10313. const stage = this.stage[maxStage];
  10314. const progress = this.brawlInfo.questInfo.progress;
  10315.  
  10316. setProgress(
  10317. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  10318. this.stats.win
  10319. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  10320. false,
  10321. function () {
  10322. isBrawlsAutoStart = false;
  10323. }
  10324. );
  10325.  
  10326. if (this.brawlInfo.questInfo.canFarm) {
  10327. const result = await this.questFarm();
  10328. console.log(result);
  10329. }
  10330.  
  10331. if (!this.continueAttack &&
  10332. this.brawlInfo.questInfo.stage == 12 &&
  10333. this.brawlInfo.questInfo.progress == 12) {
  10334. if (
  10335. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  10336. { msg: I18N('BTN_NO'), result: true },
  10337. { msg: I18N('BTN_YES'), result: false },
  10338. ])
  10339. ) {
  10340. this.end(I18N('SUCCESS'));
  10341. return;
  10342. } else {
  10343. this.continueAttack = true;
  10344. }
  10345. }
  10346.  
  10347. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  10348. this.end(I18N('DONT_HAVE_LIVES'));
  10349. return;
  10350. }
  10351.  
  10352. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  10353.  
  10354. // Автоматический подбор пачки
  10355. if (this.isAuto) {
  10356. if (this.mandatoryId !== 11) {
  10357. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  10358. return;
  10359. }
  10360. this.args = await this.updatePack(enemie.heroes);
  10361. }
  10362.  
  10363. const result = await this.battle(enemie.userId);
  10364. this.brawlInfo = {
  10365. questInfo: result[1].result.response,
  10366. findEnemies: result[2].result.response,
  10367. };
  10368. }
  10369. }
  10370.  
  10371. async updatePack(enemieHeroes) {
  10372. const packs=[
  10373. {id:3,args:{heroes:[9,40,56,12,11],pet:6008,favor:{9:6005,11:6e3,12:6003,40:6004,56:6001}},attackers:{9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6027:130,8270:1,8271:1},power:195886,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:7020.32,strength:3068,armor:19995,dodge:14644,magicPower:64780.6,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6005,favorPower:11064},11:{id:"11",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{290:130,291:130,292:130,293:130,6002:130},power:189775,star:6,runes:[43750,43750,43750,43750,43750],skins:{11:60,36:60,86:60,170:60,247:60},currentSkin:86,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[4,8,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3032,hp:309512,intelligence:2777,physicalAttack:52570.32,strength:17624,armor:42178,armorPenetration:9957.6,magicResist:37632,skin:86,favorPetId:6e3,favorPower:11064},12:{id:12,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{346:130,347:130,348:130,349:130,6017:130},power:190108,star:6,runes:[43750,43750,43750,43750,43750],skins:{12:60,37:60,87:60,157:60,207:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[8,10,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17241,hp:359857,intelligence:3432,physicalAttack:17632,strength:2887,armor:25126,lifesteal:80,magicPenetration:19650,magicPower:60919.6,magicResist:29092.6,skin:0,favorPetId:6003,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},56:{id:56,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{376:130,377:130,378:130,379:130,6007:130},power:184420,star:6,runes:[43750,43750,43750,43750,43750],skins:{264:60,279:60,294:60,321:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[5,7,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2791,hp:334687,intelligence:18813,physicalAttack:50,strength:2656,armor:22982.6,magicPenetration:48159,magicPower:65641,magicResist:13990,skin:0,favorPetId:6001,favorPower:11064},6008:{id:6008,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6036:130,6037:130},power:181943,type:"pet",perks:[5],name:null,armorPenetration:47911,intelligence:11064,strength:12360}}},{id:4,args:{heroes:[63,48,54,1,11],pet:6006,favor:{1:6004,11:6001,48:6005,54:6e3,63:6003}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},11:{id:"11",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{290:130,291:130,292:130,293:130,6007:130},power:189526,star:6,runes:[43750,43750,43750,43750,43750],skins:{11:60,36:60,86:60,170:60,247:60},currentSkin:86,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,8,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3032,hp:409088,intelligence:2777,physicalAttack:45600,strength:17624,armor:52135.6,magicResist:37632,skin:86,favorPetId:6001,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6027:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:10180,magicPower:9957.6,magicResist:24816,skin:0,favorPetId:6005,favorPower:11064},54:{id:54,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{320:130,321:130,322:130,323:130,6002:130},power:190760,star:6,runes:[43750,43750,43750,43750,43750],skins:{224:60,225:60,263:60,282:60,319:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[10,2,16],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3179,hp:324868,intelligence:2844,physicalAttack:44980.32,strength:18258,armor:29660,armorPenetration:59258.6,magicPower:320,magicResist:7684,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6017:130,8272:1,8273:1},power:191031,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:44256,strength:2877,armor:800,armorPenetration:22520,magicPower:9957.6,magicResist:18483.6,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:2,args:{heroes:[23,56,43,12,11],pet:6006,favor:{11:6e3,12:6003,23:6005,43:6008,56:6001}},attackers:{11:{id:"11",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{290:130,291:130,292:130,293:130,6002:130},power:189775,star:6,runes:[43750,43750,43750,43750,43750],skins:{11:60,36:60,86:60,170:60,247:60},currentSkin:86,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[4,8,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3032,hp:309512,intelligence:2777,physicalAttack:52570.32,strength:17624,armor:42178,armorPenetration:9957.6,magicResist:37632,skin:86,favorPetId:6e3,favorPower:11064},12:{id:12,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{346:130,347:130,348:130,349:130,6017:130},power:190108,star:6,runes:[43750,43750,43750,43750,43750],skins:{12:60,37:60,87:60,157:60,207:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[8,10,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17241,hp:359857,intelligence:3432,physicalAttack:17632,strength:2887,armor:25126,lifesteal:80,magicPenetration:19650,magicPower:60919.6,magicResist:29092.6,skin:0,favorPetId:6003,favorPower:11064},23:{id:23,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{280:130,281:130,282:130,283:130,6027:130},power:195291,star:6,runes:[43750,43750,43750,43750,43750],skins:{23:60,59:60,152:60,190:60,228:60,336:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[8,7,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2655,hp:445846,intelligence:18302,physicalAttack:7020.32,strength:2920,armor:28620,magicPower:87413.6,magicResist:37016,skin:0,favorPetId:6005,favorPower:11064},43:{id:43,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{215:130,216:130,217:130,218:130,6038:130},power:189593,star:6,runes:[43750,43750,43750,43750,43750],skins:{98:60,130:60,169:60,201:60,304:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6008,type:"hero",perks:[7,9,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2447,hp:265217,intelligence:18758,physicalAttack:50,strength:2842,armor:18637.6,magicPenetration:52439,magicPower:75465.6,magicResist:22695,skin:0,favorPetId:6008,favorPower:11064},56:{id:56,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{376:130,377:130,378:130,379:130,6007:130},power:184420,star:6,runes:[43750,43750,43750,43750,43750],skins:{264:60,279:60,294:60,321:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[5,7,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2791,hp:334687,intelligence:18813,physicalAttack:50,strength:2656,armor:22982.6,magicPenetration:48159,magicPower:65641,magicResist:13990,skin:0,favorPetId:6001,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:5,args:{heroes:[57,63,40,16,11],pet:6003,favor:{11:6007,16:6e3,40:6004,57:6003,63:6009}},attackers:{11:{id:"11",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{290:130,291:130,292:130,293:130,6035:130},power:189526,star:6,runes:[43750,43750,43750,43750,43750],skins:{11:60,36:60,86:60,170:60,247:60},currentSkin:86,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[4,8,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3032,hp:309512,intelligence:2777,physicalAttack:45600,strength:17624,armor:52135.6,magicPower:9957.6,magicResist:37632,skin:86,favorPetId:6007,favorPower:11064},16:{id:16,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{301:130,302:130,303:130,350:130,6002:130},power:191091,star:6,runes:[43750,43750,43750,43750,43750],skins:{16:60,58:60,177:60,192:60,258:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[6,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17007,hp:286172,intelligence:3196,physicalAttack:37367.32,strength:3207,armor:16985,armorPenetration:43317.6,dodge:14027,magicResist:6866,skin:0,favorPetId:6e3,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},57:{id:57,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{386:130,387:130,388:130,389:130,6017:130},power:189978,star:6,runes:[43750,43750,43750,43750,43750],skins:{269:60,288:60,316:60,328:60,342:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[5,8,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3249,hp:263278,intelligence:2854,physicalAttack:47083,strength:18671,armor:44106,magicPower:9957.6,magicResist:41589.6,skin:0,favorPetId:6003,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6041:130,8272:1,8273:1},power:193520,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6009,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:54213.6,strength:2877,armor:800,armorPenetration:32477.6,magicResist:8526,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6009,favorPower:11064},6003:{id:6003,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6015:130,6016:130},power:181943,type:"pet",perks:[8],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}}
  10374. ];
  10375.  
  10376. const bestPack = {
  10377. pack: packs[0],
  10378. countWin: 0,
  10379. }
  10380.  
  10381. for (const pack of packs) {
  10382. const attackers = pack.attackers;
  10383. const battle = {
  10384. attackers,
  10385. defenders: [enemieHeroes],
  10386. type: 'brawl',
  10387. };
  10388.  
  10389. let countWinBattles = 0;
  10390. let countTestBattle = 10;
  10391. for (let i = 0; i < countTestBattle; i++) {
  10392. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  10393. const result = await Calc(battle);
  10394. if (result.result.win) {
  10395. countWinBattles++;
  10396. }
  10397. if (countWinBattles > 7) {
  10398. console.log(pack)
  10399. return pack.args;
  10400. }
  10401. }
  10402. if (countWinBattles > bestPack.countWin) {
  10403. bestPack.countWin = countWinBattles;
  10404. bestPack.pack = pack.args;
  10405. }
  10406. }
  10407.  
  10408. console.log(bestPack);
  10409. return bestPack.pack;
  10410. }
  10411.  
  10412. async questFarm() {
  10413. const calls = [this.callBrawlQuestFarm];
  10414. const result = await Send(JSON.stringify({ calls }));
  10415. return result.results[0].result.response;
  10416. }
  10417.  
  10418. async getBrawlInfo() {
  10419. const data = await Send(JSON.stringify({
  10420. calls: [
  10421. this.callUserGetInfo,
  10422. this.callBrawlQuestGetInfo,
  10423. this.callBrawlFindEnemies,
  10424. this.callTeamGetMaxUpgrade,
  10425. this.callBrawlGetInfo,
  10426. ]
  10427. }));
  10428.  
  10429. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  10430.  
  10431. const maxUpgrade = data.results[3].result.response;
  10432. const maxHero = Object.values(maxUpgrade.hero);
  10433. const maxTitan = Object.values(maxUpgrade.titan);
  10434. const maxPet = Object.values(maxUpgrade.pet);
  10435. this.maxUpgrade = [...maxHero, ...maxPet];
  10436.  
  10437. this.info = data.results[4].result.response;
  10438. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  10439. return {
  10440. attempts: attempts.amount,
  10441. questInfo: data.results[1].result.response,
  10442. findEnemies: data.results[2].result.response,
  10443. }
  10444. }
  10445.  
  10446. /**
  10447. * Carrying out a fight
  10448. *
  10449. * Проведение боя
  10450. */
  10451. async battle(userId) {
  10452. this.stats.count++;
  10453. const battle = await this.startBattle(userId, this.args);
  10454. const result = await Calc(battle);
  10455. console.log(result.result);
  10456. if (result.result.win) {
  10457. this.stats.win++;
  10458. } else {
  10459. this.stats.loss++;
  10460. if (!this.info.boughtEndlessLivesToday) {
  10461. this.attempts--;
  10462. }
  10463. }
  10464. return await this.endBattle(result);
  10465. // return await this.cancelBattle(result);
  10466. }
  10467.  
  10468. /**
  10469. * Starts a fight
  10470. *
  10471. * Начинает бой
  10472. */
  10473. async startBattle(userId, args) {
  10474. const call = {
  10475. name: "brawl_startBattle",
  10476. args,
  10477. ident: "brawl_startBattle"
  10478. }
  10479. call.args.userId = userId;
  10480. const calls = [call];
  10481. const result = await Send(JSON.stringify({ calls }));
  10482. return result.results[0].result.response;
  10483. }
  10484.  
  10485. cancelBattle(battle) {
  10486. const fixBattle = function (heroes) {
  10487. for (const ids in heroes) {
  10488. const hero = heroes[ids];
  10489. hero.energy = random(1, 999);
  10490. if (hero.hp > 0) {
  10491. hero.hp = random(1, hero.hp);
  10492. }
  10493. }
  10494. }
  10495. fixBattle(battle.progress[0].attackers.heroes);
  10496. fixBattle(battle.progress[0].defenders.heroes);
  10497. return this.endBattle(battle);
  10498. }
  10499.  
  10500. /**
  10501. * Ends the fight
  10502. *
  10503. * Заканчивает бой
  10504. */
  10505. async endBattle(battle) {
  10506. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  10507. const calls = [{
  10508. name: "brawl_endBattle",
  10509. args: {
  10510. result: battle.result,
  10511. progress: battle.progress
  10512. },
  10513. ident: "brawl_endBattle"
  10514. },
  10515. this.callBrawlQuestGetInfo,
  10516. this.callBrawlFindEnemies,
  10517. ];
  10518. const result = await Send(JSON.stringify({ calls }));
  10519. return result.results;
  10520. }
  10521.  
  10522. end(endReason) {
  10523. isCancalBattle = true;
  10524. isBrawlsAutoStart = false;
  10525. setProgress(endReason, true);
  10526. console.log(endReason);
  10527. this.resolve();
  10528. }
  10529. }
  10530.  
  10531. })();
  10532.  
  10533. /**
  10534. * TODO:
  10535. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  10536. * Добивание на арене титанов
  10537. * Закрытие окошек по Esc +-
  10538. * Починить работу скрипта на уровне команды ниже 10 +-
  10539. * Написать номальную синхронизацию
  10540. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  10541. */