HeroWarsDungeon

Automation of actions for the game Hero Wars

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

  1. // ==UserScript==
  2. // @name HeroWarsDungeon
  3. // @name:en HeroWarsDungeon
  4. // @name:ru HeroWarsDungeon
  5. // @namespace HeroWarsDungeon
  6. // @version 2.292.3
  7. // @description Automation of actions for the game Hero Wars
  8. // @description:en Automation of actions for the game Hero Wars
  9. // @description:ru Автоматизация действий для игры Хроники Хаоса
  10. // @author ZingerY, ApuoH, Gudwin
  11. // @license Copyright ZingerY
  12. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  13. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  14. // @match https://www.hero-wars.com/*
  15. // @match https://apps-1701433570146040.apps.fbsbx.com/*
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. // сделал ApuoH
  20. (function() {
  21. /**
  22. * Start script
  23. *
  24. * Стартуем скрипт
  25. */
  26. console.log('%cStart ' + GM_info.script.name + ', v' + GM_info.script.version + ' by ' + GM_info.script.author, 'color: red');
  27. /**
  28. * Script info
  29. *
  30. * Информация о скрипте
  31. */
  32. this.scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl) =>
  33. ({name, version, author, homepage, lastModified, updateUrl}))
  34. (GM_info.script, GM_info.scriptUpdateURL);
  35. this.GM_info = GM_info;
  36. /**
  37. * Information for completing daily quests
  38. *
  39. * Информация для выполнения ежендевных квестов
  40. */
  41. const questsInfo = {};
  42. /**
  43. * Is the game data loaded
  44. *
  45. * Загружены ли данные игры
  46. */
  47. let isLoadGame = false;
  48. /**
  49. * Headers of the last request
  50. *
  51. * Заголовки последнего запроса
  52. */
  53. let lastHeaders = {};
  54. /**
  55. * Information about sent gifts
  56. *
  57. * Информация об отправленных подарках
  58. */
  59. let freebieCheckInfo = null;
  60. /**
  61. * missionTimer
  62. *
  63. * missionTimer
  64. */
  65. let missionBattle = null;
  66. /** Пачки для тестов в чате*/ //тест сохранка
  67. let repleyBattle = {
  68. defenders: {},
  69. attackers: {},
  70. effects: {},
  71. state: {},
  72. seed: undefined
  73. }
  74. /**
  75. * User data
  76. *
  77. * Данные пользователя
  78. */
  79. let userInfo;
  80. /**
  81. * Original methods for working with AJAX
  82. *
  83. * Оригинальные методы для работы с AJAX
  84. */
  85. const original = {
  86. open: XMLHttpRequest.prototype.open,
  87. send: XMLHttpRequest.prototype.send,
  88. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  89. SendWebSocket: WebSocket.prototype.send,
  90. };
  91. /**
  92. * Decoder for converting byte data to JSON string
  93. *
  94. * Декодер для перобразования байтовых данных в JSON строку
  95. */
  96. const decoder = new TextDecoder("utf-8");
  97. /**
  98. * Stores a history of requests
  99. *
  100. * Хранит историю запросов
  101. */
  102. let requestHistory = {};
  103. /**
  104. * URL for API requests
  105. *
  106. * URL для запросов к API
  107. */
  108. let apiUrl = '';
  109.  
  110. /**
  111. * Connecting to the game code
  112. *
  113. * Подключение к коду игры
  114. */
  115. this.cheats = new hackGame();
  116. /**
  117. * The function of calculating the results of the battle
  118. *
  119. * Функция расчета результатов боя
  120. */
  121. this.BattleCalc = cheats.BattleCalc;
  122. /**
  123. * Sending a request available through the console
  124. *
  125. * Отправка запроса доступная через консоль
  126. */
  127. this.SendRequest = send;
  128. /**
  129. * Simple combat calculation available through the console
  130. *
  131. * Простой расчет боя доступный через консоль
  132. */
  133. this.Calc = function (data) {
  134. const type = getBattleType(data?.type);
  135. return new Promise((resolve, reject) => {
  136. try {
  137. BattleCalc(data, type, resolve);
  138. } catch (e) {
  139. reject(e);
  140. }
  141. })
  142. }
  143. //тест остановка подземки
  144. let stopDung = false;
  145. /**
  146. * Short asynchronous request
  147. * Usage example (returns information about a character):
  148. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  149. *
  150. * Короткий асинхронный запрос
  151. * Пример использования (возвращает информацию о персонаже):
  152. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  153. */
  154. this.Send = function (json, pr) {
  155. return new Promise((resolve, reject) => {
  156. try {
  157. send(json, resolve, pr);
  158. } catch (e) {
  159. reject(e);
  160. }
  161. })
  162. }
  163.  
  164. this.xyz = (({ name, version, author }) => ({ name, version, author }))(GM_info.script);
  165. const i18nLangData = {
  166. /* English translation by BaBa */
  167. en: {
  168. /* Checkboxes */
  169. SKIP_FIGHTS: 'Skip battle',
  170. SKIP_FIGHTS_TITLE: 'Skip battle in Outland and the arena of the titans, auto-pass in the tower and campaign',
  171. ENDLESS_CARDS: 'Infinite cards',
  172. ENDLESS_CARDS_TITLE: 'Disable Divination Cards wasting',
  173. AUTO_EXPEDITION: 'Auto Expedition',
  174. AUTO_EXPEDITION_TITLE: 'Auto-sending expeditions',
  175. CANCEL_FIGHT: 'Cancel battle',
  176. CANCEL_FIGHT_TITLE: 'Ability to cancel manual combat on GW, CoW and Asgard',
  177. GIFTS: 'Gifts',
  178. GIFTS_TITLE: 'Collect gifts automatically',
  179. BATTLE_RECALCULATION: 'Battle recalculation',
  180. BATTLE_RECALCULATION_TITLE: 'Preliminary calculation of the battle',
  181. BATTLE_FISHING: 'Finishing',
  182. BATTLE_FISHING_TITLE: 'Finishing off the team from the last replay in the chat',
  183. BATTLE_TRENING: 'Workout',
  184. BATTLE_TRENING_TITLE: 'A training battle in the chat against the team from the last replay',
  185. QUANTITY_CONTROL: 'Quantity control',
  186. QUANTITY_CONTROL_TITLE: 'Ability to specify the number of opened "lootboxes"',
  187. REPEAT_CAMPAIGN: 'Repeat missions',
  188. REPEAT_CAMPAIGN_TITLE: 'Auto-repeat battles in the campaign',
  189. DISABLE_DONAT: 'Disable donation',
  190. DISABLE_DONAT_TITLE: 'Removes all donation offers',
  191. DAILY_QUESTS: 'Quests',
  192. DAILY_QUESTS_TITLE: 'Complete daily quests',
  193. AUTO_QUIZ: 'AutoQuiz',
  194. AUTO_QUIZ_TITLE: 'Automatically receive correct answers to quiz questions',
  195. SECRET_WEALTH_CHECKBOX: 'Automatic purchase in the store "Secret Wealth" when entering the game',
  196. HIDE_SERVERS: 'Collapse servers',
  197. HIDE_SERVERS_TITLE: 'Hide unused servers',
  198. /* Input fields */
  199. HOW_MUCH_TITANITE: 'How much titanite to farm',
  200. COMBAT_SPEED: 'Combat Speed Multiplier',
  201. HOW_REPEAT_CAMPAIGN: 'how many mission replays', //тест добавил
  202. NUMBER_OF_TEST: 'Number of test fights',
  203. NUMBER_OF_AUTO_BATTLE: 'Number of auto-battle attempts',
  204. USER_ID_TITLE: 'Enter the player ID',
  205. AMOUNT: 'Gift number, 1 - hero development, 2 - pets, 3 - light, 4 - darkness, 5 - ascension, 6 - appearance',
  206. GIFT_NUM: 'Number of gifts to be sent',
  207. /* Buttons */
  208. RUN_SCRIPT: 'Run the',
  209. STOP_SCRIPT: 'Stop the',
  210. TO_DO_EVERYTHING: 'Do All',
  211. TO_DO_EVERYTHING_TITLE: 'Perform multiple actions of your choice',
  212. OUTLAND: 'Outland',
  213. OUTLAND_TITLE: 'Collect Outland',
  214. TITAN_ARENA: 'ToE',
  215. TITAN_ARENA_TITLE: 'Complete the titan arena',
  216. DUNGEON: 'Dungeon',
  217. DUNGEON_TITLE: 'Go through the dungeon',
  218. DUNGEON2: 'Dungeon full',
  219. DUNGEON_FULL_TITLE: 'Dungeon for Full Titans',
  220. STOP_DUNGEON: 'Stop Dungeon',
  221. STOP_DUNGEON_TITLE: 'Stop digging the dungeon',
  222. SEER: 'Seer',
  223. SEER_TITLE: 'Roll the Seer',
  224. TOWER: 'Tower',
  225. TOWER_TITLE: 'Pass the tower',
  226. EXPEDITIONS: 'Expeditions',
  227. EXPEDITIONS_TITLE: 'Sending and collecting expeditions',
  228. SYNC: 'Sync',
  229. SYNC_TITLE: 'Partial synchronization of game data without reloading the page',
  230. ARCHDEMON: 'Archdemon',
  231. ARCHDEMON_TITLE: 'Hitting kills and collecting rewards',
  232. CRUCIBLE_SOULS: 'Crucible',
  233. CRUCIBLE_SOULS_TITLE: 'Fill the kilos in the crucible of souls',
  234. ESTER_EGGS: 'Easter eggs',
  235. ESTER_EGGS_TITLE: 'Collect all Easter eggs or rewards',
  236. REWARDS: 'Rewards',
  237. REWARDS_TITLE: 'Collect all quest rewards',
  238. MAIL: 'Mail',
  239. MAIL_TITLE: 'Collect all mail, except letters with energy and charges of the portal',
  240. MINIONS: 'Minions',
  241. MINIONS_TITLE: 'Attack minions with saved packs',
  242. ADVENTURE: 'Adventure',
  243. ADVENTURE_TITLE: 'Passes the adventure along the specified route',
  244. STORM: 'Storm',
  245. STORM_TITLE: 'Passes the Storm along the specified route',
  246. SANCTUARY: 'Sanctuary',
  247. SANCTUARY_TITLE: 'Fast travel to Sanctuary',
  248. GUILD_WAR: 'Guild War',
  249. GUILD_WAR_TITLE: 'Fast travel to Guild War',
  250. SECRET_WEALTH: 'Secret Wealth',
  251. SECRET_WEALTH_TITLE: 'Buy something in the store "Secret Wealth"',
  252. /* Misc */
  253. BOTTOM_URLS: '<a href="https://t.me/+0oMwICyV1aQ1MDAy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://www.patreon.com/HeroWarsUserScripts" target="_blank" title="Patreon"><svg width="20" height="20" viewBox="0 0 1080 1080" xmlns="http://www.w3.org/2000/svg"><g fill="#FFF" stroke="None"><path d="m1033 324.45c-0.19-137.9-107.59-250.92-233.6-291.7-156.48-50.64-362.86-43.3-512.28 27.2-181.1 85.46-237.99 272.66-240.11 459.36-1.74 153.5 13.58 557.79 241.62 560.67 169.44 2.15 194.67-216.18 273.07-321.33 55.78-74.81 127.6-95.94 216.01-117.82 151.95-37.61 255.51-157.53 255.29-316.38z"/></g></svg></a>',
  254. GIFTS_SENT: 'Gifts sent!',
  255. DO_YOU_WANT: 'Do you really want to do this?',
  256. BTN_RUN: 'Run',
  257. BTN_CANCEL: 'Cancel',
  258. BTN_OK: 'OK',
  259. MSG_HAVE_BEEN_DEFEATED: 'You have been defeated!',
  260. BTN_AUTO: 'Auto',
  261. MSG_YOU_APPLIED: 'You applied',
  262. MSG_DAMAGE: 'damage',
  263. MSG_CANCEL_AND_STAT: 'Auto (F5) and show statistic',
  264. MSG_REPEAT_MISSION: 'Repeat the mission?',
  265. BTN_REPEAT: 'Repeat',
  266. BTN_NO: 'No',
  267. MSG_SPECIFY_QUANT: 'Specify Quantity:',
  268. BTN_OPEN: 'Open',
  269. QUESTION_COPY: 'Question copied to clipboard',
  270. ANSWER_KNOWN: 'The answer is known',
  271. ANSWER_NOT_KNOWN: 'ATTENTION THE ANSWER IS NOT KNOWN',
  272. BEING_RECALC: 'The battle is being recalculated',
  273. THIS_TIME: 'This time',
  274. VICTORY: '<span style="color:green;">VICTORY</span>',
  275. DEFEAT: '<span style="color:red;">DEFEAT</span>',
  276. CHANCE_TO_WIN: 'Chance to win <span style="color: red;">based on pre-calculation</span>',
  277. OPEN_DOLLS: 'nesting dolls recursively',
  278. SENT_QUESTION: 'Question sent',
  279. SETTINGS: 'Settings',
  280. MSG_BAN_ATTENTION: '<p style="color:red;">Using this feature may result in a ban.</p> Continue?',
  281. BTN_YES_I_AGREE: 'Yes, I understand the risks!',
  282. BTN_NO_I_AM_AGAINST: 'No, I refuse it!',
  283. VALUES: 'Values',
  284. SAVING: 'Saving',
  285. USER_ID: 'User Id',
  286. SEND_GIFT: 'The gift has been sent',
  287. EXPEDITIONS_SENT: 'Expeditions:<br>Collected: {countGet}<br>Sent: {countSend}',
  288. EXPEDITIONS_NOTHING: 'Nothing to collect/send',
  289. TITANIT: 'Titanit',
  290. COMPLETED: 'completed',
  291. FLOOR: 'Floor',
  292. LEVEL: 'Level',
  293. BATTLES: 'battles',
  294. EVENT: 'Event',
  295. NOT_AVAILABLE: 'not available',
  296. NO_HEROES: 'No heroes',
  297. DAMAGE_AMOUNT: 'Damage amount',
  298. NOTHING_TO_COLLECT: 'Nothing to collect',
  299. COLLECTED: 'Collected',
  300. REWARD: 'rewards',
  301. REMAINING_ATTEMPTS: 'Remaining attempts',
  302. BATTLES_CANCELED: 'Battles canceled',
  303. MINION_RAID: 'Minion Raid',
  304. STOPPED: 'Stopped',
  305. REPETITIONS: 'Repetitions',
  306. MISSIONS_PASSED: 'Missions passed',
  307. STOP: 'stop',
  308. TOTAL_OPEN: 'Total open',
  309. OPEN: 'Open',
  310. ROUND_STAT: 'Damage statistics for ',
  311. BATTLE: 'battles',
  312. MINIMUM: 'Minimum',
  313. MAXIMUM: 'Maximum',
  314. AVERAGE: 'Average',
  315. NOT_THIS_TIME: 'Not this time',
  316. RETRY_LIMIT_EXCEEDED: 'Retry limit exceeded',
  317. SUCCESS: 'Success',
  318. RECEIVED: 'Received',
  319. LETTERS: 'letters',
  320. PORTALS: 'portals',
  321. ATTEMPTS: 'attempts',
  322. /* Quests */
  323. QUEST_10001: 'Upgrade the skills of heroes 3 times',
  324. QUEST_10002: 'Complete 10 missions',
  325. QUEST_10003: 'Complete 3 heroic missions',
  326. QUEST_10004: 'Fight 3 times in the Arena or Grand Arena',
  327. QUEST_10006: 'Use the exchange of emeralds 1 time',
  328. QUEST_10007: 'Perform 1 summon in the Solu Atrium',
  329. QUEST_10016: 'Send gifts to guildmates',
  330. QUEST_10018: 'Use an experience potion',
  331. QUEST_10019: 'Open 1 chest in the Tower',
  332. QUEST_10020: 'Open 3 chests in Outland',
  333. QUEST_10021: 'Collect 75 Titanite in the Guild Dungeon',
  334. QUEST_10021: 'Collect 150 Titanite in the Guild Dungeon',
  335. QUEST_10023: 'Upgrade Gift of the Elements by 1 level',
  336. QUEST_10024: 'Level up any artifact once',
  337. QUEST_10025: 'Start Expedition 1',
  338. QUEST_10026: 'Start 4 Expeditions',
  339. QUEST_10027: 'Win 1 battle of the Tournament of Elements',
  340. QUEST_10028: 'Level up any titan artifact',
  341. QUEST_10029: 'Unlock the Orb of Titan Artifacts',
  342. QUEST_10030: 'Upgrade any Skin of any hero 1 time',
  343. QUEST_10031: 'Win 6 battles of the Tournament of Elements',
  344. QUEST_10043: 'Start or Join an Adventure',
  345. QUEST_10044: 'Use Summon Pets 1 time',
  346. QUEST_10046: 'Open 3 chests in Adventure',
  347. QUEST_10047: 'Get 150 Guild Activity Points',
  348. NOTHING_TO_DO: 'Nothing to do',
  349. YOU_CAN_COMPLETE: 'You can complete quests',
  350. BTN_DO_IT: 'Do it',
  351. NOT_QUEST_COMPLETED: 'Not a single quest completed',
  352. COMPLETED_QUESTS: 'Completed quests',
  353. /* everything button */
  354. ASSEMBLE_OUTLAND: 'Assemble Outland',
  355. PASS_THE_TOWER: 'Pass the tower',
  356. CHECK_EXPEDITIONS: 'Check Expeditions',
  357. COMPLETE_TOE: 'Complete ToE',
  358. COMPLETE_DUNGEON: 'Complete the dungeon',
  359. COMPLETE_DUNGEON_FULL: 'Complete the dungeon for Full Titans',
  360. COLLECT_MAIL: 'Collect mail',
  361. COLLECT_MISC: 'Collect some bullshit',
  362. COLLECT_MISC_TITLE: 'Collect Easter Eggs, Skin Gems, Keys, Arena Coins and Soul Crystal',
  363. COLLECT_QUEST_REWARDS: 'Collect quest rewards',
  364. MAKE_A_SYNC: 'Make a sync',
  365.  
  366. RUN_FUNCTION: 'Run the following functions?',
  367. BTN_GO: 'Go!',
  368. PERFORMED: 'Performed',
  369. DONE: 'Done',
  370. ERRORS_OCCURRES: 'Errors occurred while executing',
  371. COPY_ERROR: 'Copy error information to clipboard',
  372. BTN_YES: 'Yes',
  373. ALL_TASK_COMPLETED: 'All tasks completed',
  374.  
  375. UNKNOWN: 'unknown',
  376. ENTER_THE_PATH: 'Enter the path of adventure using commas or dashes',
  377. START_ADVENTURE: 'Start your adventure along this path!',
  378. INCORRECT_WAY: 'Incorrect path in adventure: {from} -> {to}',
  379. BTN_CANCELED: 'Canceled',
  380. MUST_TWO_POINTS: 'The path must contain at least 2 points.',
  381. MUST_ONLY_NUMBERS: 'The path must contain only numbers and commas',
  382. NOT_ON_AN_ADVENTURE: 'You are not on an adventure',
  383. YOU_IN_NOT_ON_THE_WAY: 'Your location is not on the way',
  384. ATTEMPTS_NOT_ENOUGH: 'Your attempts are not enough to complete the path, continue?',
  385. YES_CONTINUE: 'Yes, continue!',
  386. NOT_ENOUGH_AP: 'Not enough action points',
  387. ATTEMPTS_ARE_OVER: 'The attempts are over',
  388. MOVES: 'Moves',
  389. BUFF_GET_ERROR: 'Buff getting error',
  390. BATTLE_END_ERROR: 'Battle end error',
  391. AUTOBOT: 'Autobot',
  392. FAILED_TO_WIN_AUTO: 'Failed to win the auto battle',
  393. ERROR_OF_THE_BATTLE_COPY: 'An error occurred during the passage of the battle<br>Copy the error to the clipboard?',
  394. ERROR_DURING_THE_BATTLE: 'Error during the battle',
  395. NO_CHANCE_WIN: 'No chance of winning this fight: 0/',
  396. LOST_HEROES: 'You have won, but you have lost one or several heroes',
  397. VICTORY_IMPOSSIBLE: 'Is victory impossible, should we focus on the result?',
  398. FIND_COEFF: 'Find the coefficient greater than',
  399. BTN_PASS: 'PASS',
  400. BRAWLS: 'Brawls',
  401. BRAWLS_TITLE: 'Activates the ability to auto-brawl',
  402. START_AUTO_BRAWLS: 'Start Auto Brawls?',
  403. LOSSES: 'Losses',
  404. WINS: 'Wins',
  405. FIGHTS: 'Fights',
  406. STAGE: 'Stage',
  407. DONT_HAVE_LIVES: "You don't have lives",
  408. LIVES: 'Lives',
  409. SECRET_WEALTH_ALREADY: 'Item for Pet Potions already purchased',
  410. SECRET_WEALTH_NOT_ENOUGH: 'Not Enough Pet Potion, You Have {available}, Need {need}',
  411. SECRET_WEALTH_UPGRADE_NEW_PET: 'After purchasing the Pet Potion, it will not be enough to upgrade a new pet',
  412. SECRET_WEALTH_PURCHASED: 'Purchased {count} {name}',
  413. SECRET_WEALTH_CANCELED: 'Secret Wealth: Purchase Canceled',
  414. SECRET_WEALTH_BUY: 'You have {available} Pet Potion.<br>Do you want to buy {countBuy} {name} for {price} Pet Potion?',
  415. DAILY_BONUS: 'Daily bonus',
  416. DO_DAILY_QUESTS: 'Do daily quests',
  417. ACTIONS: 'Actions',
  418. ACTIONS_TITLE: 'Dialog box with various actions',
  419. OTHERS: 'Others',
  420. OTHERS_TITLE: 'Others',
  421. CHOOSE_ACTION: 'Choose an action',
  422. OPEN_LOOTBOX: 'You have {lootBox} boxes, should we open them?',
  423. STAMINA: 'Energy',
  424. BOXES_OVER: 'The boxes are over',
  425. NO_BOXES: 'No boxes',
  426. NO_MORE_ACTIVITY: 'No more activity for items today',
  427. EXCHANGE_ITEMS: 'Exchange items for activity points (max {maxActive})?',
  428. GET_ACTIVITY: 'Get Activity',
  429. NOT_ENOUGH_ITEMS: 'Not enough items',
  430. ACTIVITY_RECEIVED: 'Activity received',
  431. NO_PURCHASABLE_HERO_SOULS: 'No purchasable Hero Souls',
  432. PURCHASED_HERO_SOULS: 'Purchased {countHeroSouls} Hero Souls',
  433. NOT_ENOUGH_EMERALDS_540: 'Not enough emeralds, you need {imgEmerald}540 you have {imgEmerald}{currentStarMoney}',
  434. BUY_OUTLAND_BTN: 'Buy {count} chests {imgEmerald}{countEmerald}',
  435. CHESTS_NOT_AVAILABLE: 'Chests not available',
  436. OUTLAND_CHESTS_RECEIVED: 'Outland chests received',
  437. RAID_NOT_AVAILABLE: 'The raid is not available or there are no spheres',
  438. RAID_ADVENTURE: 'Raid {adventureId} adventure!',
  439. SOMETHING_WENT_WRONG: 'Something went wrong',
  440. ADVENTURE_COMPLETED: 'Adventure {adventureId} completed {times} times',
  441. CLAN_STAT_COPY: 'Clan statistics copied to clipboard',
  442. GET_ENERGY: 'Get Energy',
  443. GET_ENERGY_TITLE: 'Opens platinum boxes one at a time until you get 250 energy',
  444. ITEM_EXCHANGE: 'Item Exchange',
  445. ITEM_EXCHANGE_TITLE: 'Exchanges items for the specified amount of activity',
  446. BUY_SOULS: 'Buy souls',
  447. BUY_SOULS_TITLE: 'Buy hero souls from all available shops',
  448. BUY_OUTLAND: 'Buy Outland',
  449. BUY_OUTLAND_TITLE: 'Buy 9 chests in Outland for 540 emeralds',
  450. RAID: 'Raid',
  451. AUTO_RAID_ADVENTURE: 'Raid adventure',
  452. AUTO_RAID_ADVENTURE_TITLE: 'Raid adventure set number of times',
  453. CLAN_STAT: 'Clan statistics',
  454. CLAN_STAT_TITLE: 'Copies clan statistics to the clipboard',
  455. BTN_AUTO_F5: 'Auto (F5)',
  456. BOSS_DAMAGE: 'Boss Damage: ',
  457. NOTHING_BUY: 'Nothing to buy',
  458. LOTS_BOUGHT: '{countBuy} lots bought for gold',
  459. BUY_FOR_GOLD: 'Buy for gold',
  460. BUY_FOR_GOLD_TITLE: 'Buy items for gold in the Town Shop and in the Pet Soul Stone Shop',
  461. REWARDS_AND_MAIL: 'Rewards and Mail',
  462. REWARDS_AND_MAIL_TITLE: 'Collects rewards and mail',
  463. New_Year_Clan: 'a gift for a friend',
  464. New_Year_Clan_TITLE: 'New Year gifts to friends',
  465. COLLECT_REWARDS_AND_MAIL: 'Collected {countQuests} rewards and {countMail} letters',
  466. TIMER_ALREADY: 'Timer already started {time}',
  467. NO_ATTEMPTS_TIMER_START: 'No attempts, timer started {time}',
  468. EPIC_BRAWL_RESULT: 'Wins: {wins}/{attempts}, Coins: {coins}, Streak: {progress}/{nextStage} [Close]{end}',
  469. ATTEMPT_ENDED: '<br>Attempts ended, timer started {time}',
  470. EPIC_BRAWL: 'Cosmic Battle',
  471. EPIC_BRAWL_TITLE: 'Spends attempts in the Cosmic Battle',
  472. RELOAD_GAME: 'Reload game',
  473. TIMER: 'Timer:',
  474. SHOW_ERRORS: 'Show errors',
  475. SHOW_ERRORS_TITLE: 'Show server request errors',
  476. ERROR_MSG: 'Error: {name}<br>{description}',
  477. EVENT_AUTO_BOSS: 'Maximum number of battles for calculation:</br>{length} ∗ {countTestBattle} = {maxCalcBattle}</br>If you have a weak computer, it may take a long time for this, click on the cross to cancel.</br>Should I search for the best pack from all or the first suitable one?',
  478. BEST_SLOW: 'Best (slower)',
  479. FIRST_FAST: 'First (faster)',
  480. FREEZE_INTERFACE: 'Calculating... <br>The interface may freeze.',
  481. ERROR_F12: 'Error, details in the console (F12)',
  482. FAILED_FIND_WIN_PACK: 'Failed to find a winning pack',
  483. BEST_PACK: 'Best pack:',
  484. BOSS_HAS_BEEN_DEF: 'Boss {bossLvl} has been defeated.',
  485. NOT_ENOUGH_ATTEMPTS_BOSS: 'Not enough attempts to defeat boss {bossLvl}, retry?',
  486. BOSS_VICTORY_IMPOSSIBLE: 'Based on the recalculation of {battles} battles, victory has not been achieved. Would you like to continue the search for a winning battle in real battles?',
  487. BOSS_HAS_BEEN_DEF_TEXT: 'Boss {bossLvl} defeated in<br>{countBattle}/{countMaxBattle} attempts<br>(Please synchronize or restart the game to update the data)',
  488. MAP: 'Map: ',
  489. PLAYER_POS: 'Player positions:',
  490. NY_GIFTS: 'Gifts',
  491. NY_GIFTS_TITLE: "Open all New Year's gifts",
  492. NY_NO_GIFTS: 'No gifts not received',
  493. NY_GIFTS_COLLECTED: '{count} gifts collected',
  494. CHANGE_MAP: 'Island map',
  495. CHANGE_MAP_TITLE: 'Change island map',
  496. SELECT_ISLAND_MAP: 'Select an island map:',
  497. MAP_NUM: 'Map {num}',
  498. SECRET_WEALTH_SHOP: 'Secret Wealth {name}: ',
  499. SHOPS: 'Shops',
  500. SHOPS_DEFAULT: 'Default',
  501. SHOPS_DEFAULT_TITLE: 'Default stores',
  502. SHOPS_LIST: 'Shops {number}',
  503. SHOPS_LIST_TITLE: 'List of shops {number}',
  504. SHOPS_WARNING: 'Stores<br><span style="color:red">If you buy brawl store coins for emeralds, you must use them immediately, otherwise they will disappear after restarting the game!</span>',
  505. MINIONS_WARNING: 'The hero packs for attacking minions are incomplete, should I continue?',
  506. FAST_SEASON: 'Fast season',
  507. FAST_SEASON_TITLE: 'Skip the map selection screen in a season',
  508. SET_NUMBER_LEVELS: 'Specify the number of levels:',
  509. POSSIBLE_IMPROVE_LEVELS: 'It is possible to improve only {count} levels.<br>Improving?',
  510. NOT_ENOUGH_RESOURECES: 'Not enough resources',
  511. IMPROVED_LEVELS: 'Improved levels: {count}',
  512. ARTIFACTS_UPGRADE: 'Artifacts Upgrade',
  513. ARTIFACTS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero artifacts',
  514. SKINS_UPGRADE: 'Skins Upgrade',
  515. SKINS_UPGRADE_TITLE: 'Upgrades the specified amount of the cheapest hero skins',
  516. HINT: '<br>Hint: ',
  517. PICTURE: '<br>Picture: ',
  518. ANSWER: '<br>Answer: ',
  519. NO_HEROES_PACK: 'Fight at least one battle to save the attacking team',
  520. BRAWL_AUTO_PACK: 'Automatic selection of packs',
  521. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Automatic pack selection is not suitable for the current hero',
  522. BRAWL_DAILY_TASK_COMPLETED: 'Daily task completed, continue attacking?',
  523. CALC_STAT: 'Calculate statistics',
  524. ELEMENT_TOURNAMENT_REWARD: 'Unclaimed bonus for Elemental Tournament',
  525. BTN_TRY_FIX_IT: 'Fix it',
  526. BTN_TRY_FIX_IT_TITLE: 'Enable auto attack combat correction',
  527. DAMAGE_FIXED: 'Damage fixed from {lastDamage} to {maxDamage}!',
  528. DAMAGE_NO_FIXED: 'Failed to fix damage: {lastDamage}',
  529. LETS_FIX: "Let's fix",
  530. COUNT_FIXED: 'For {count} attempts',
  531. DEFEAT_TURN_TIMER: 'Defeat! Turn on the timer to complete the mission?',
  532. SEASON_REWARD: 'Season Rewards',
  533. SEASON_REWARD_TITLE: 'Collects available free rewards from all current seasons',
  534. SEASON_REWARD_COLLECTED: 'Collected {count} season rewards',
  535. SELL_HERO_SOULS: 'Sell ​​souls',
  536. SELL_HERO_SOULS_TITLE: 'Exchanges all absolute star hero souls for gold',
  537. GOLD_RECEIVED: 'Gold received: {gold}',
  538. OPEN_ALL_EQUIP_BOXES: 'Open all Equipment Fragment Box?',
  539. },
  540. ru: {
  541. /* Чекбоксы */
  542. SKIP_FIGHTS: 'Пропуск боев',
  543. SKIP_FIGHTS_TITLE: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  544. ENDLESS_CARDS: 'Бесконечные карты',
  545. ENDLESS_CARDS_TITLE: 'Отключить трату карт предсказаний',
  546. AUTO_EXPEDITION: 'АвтоЭкспедиции',
  547. AUTO_EXPEDITION_TITLE: 'Автоотправка экспедиций',
  548. CANCEL_FIGHT: 'Отмена боя',
  549. CANCEL_FIGHT_TITLE: 'Возможность отмены ручного боя на ВГ, СМ и в Асгарде',
  550. GIFTS: 'Подарки',
  551. GIFTS_TITLE: 'Собирать подарки автоматически',
  552. BATTLE_RECALCULATION: 'Прерасчет боя',
  553. BATTLE_RECALCULATION_TITLE: 'Предварительный расчет боя',
  554. BATTLE_FISHING: 'Добивание',
  555. BATTLE_FISHING_TITLE: 'Добивание в чате команды из последнего реплея',
  556. BATTLE_TRENING: 'Тренировка',
  557. BATTLE_TRENING_TITLE: 'Тренировочный бой в чате против команды из последнего реплея',
  558. QUANTITY_CONTROL: 'Контроль кол-ва',
  559. QUANTITY_CONTROL_TITLE: 'Возможность указывать количество открываемых "лутбоксов"',
  560. REPEAT_CAMPAIGN: 'Повтор в компании',
  561. REPEAT_CAMPAIGN_TITLE: 'Автоповтор боев в кампании',
  562. DISABLE_DONAT: 'Отключить донат',
  563. DISABLE_DONAT_TITLE: 'Убирает все предложения доната',
  564. DAILY_QUESTS: 'Квесты',
  565. DAILY_QUESTS_TITLE: 'Выполнять ежедневные квесты',
  566. AUTO_QUIZ: 'АвтоВикторина',
  567. AUTO_QUIZ_TITLE: 'Автоматическое получение правильных ответов на вопросы викторины',
  568. SECRET_WEALTH_CHECKBOX: 'Автоматическая покупка в магазине "Тайное Богатство" при заходе в игру',
  569. HIDE_SERVERS: 'Свернуть сервера',
  570. HIDE_SERVERS_TITLE: 'Скрывать неиспользуемые сервера',
  571. /* Поля ввода */
  572. HOW_MUCH_TITANITE: 'Сколько фармим титанита',
  573. COMBAT_SPEED: 'Множитель ускорения боя',
  574. HOW_REPEAT_CAMPAIGN: 'Сколько повторов миссий', //тест добавил
  575. NUMBER_OF_TEST: 'Количество тестовых боев',
  576. NUMBER_OF_AUTO_BATTLE: 'Количество попыток автобоев',
  577. USER_ID_TITLE: 'Введите айди игрока',
  578. AMOUNT: 'Количество отправляемых подарков',
  579. GIFT_NUM: 'Номер подарка, 1 - развитие героев, 2 - питомцы, 3 - света, 4 - тьмы, 5 - вознесения, 6 - облик',
  580. /* Кнопки */
  581. RUN_SCRIPT: 'Запустить скрипт',
  582. STOP_SCRIPT: 'Остановить скрипт',
  583. TO_DO_EVERYTHING: 'Сделать все',
  584. TO_DO_EVERYTHING_TITLE: 'Выполнить несколько действий',
  585. OUTLAND: 'Запределье',
  586. OUTLAND_TITLE: 'Собрать Запределье',
  587. TITAN_ARENA: 'Турнир Стихий',
  588. TITAN_ARENA_TITLE: 'Автопрохождение Турнира Стихий',
  589. DUNGEON: 'Подземелье',
  590. DUNGEON_TITLE: 'Автопрохождение подземелья',
  591. DUNGEON2: 'Подземелье фулл',
  592. DUNGEON_FULL_TITLE: 'Подземелье для фуловых титанов',
  593. STOP_DUNGEON: 'Стоп подземка',
  594. STOP_DUNGEON_TITLE: 'Остановить копание подземелья',
  595. SEER: 'Провидец',
  596. SEER_TITLE: 'Покрутить Провидца',
  597. TOWER: 'Башня',
  598. TOWER_TITLE: 'Автопрохождение башни',
  599. EXPEDITIONS: 'Экспедиции',
  600. EXPEDITIONS_TITLE: 'Отправка и сбор экспедиций',
  601. SYNC: 'Синхронизация',
  602. SYNC_TITLE: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  603. ARCHDEMON: 'Архидемон',
  604. ARCHDEMON_TITLE: 'Набивает килы и собирает награду',
  605. CRUCIBLE_SOULS: 'Горнило душ',
  606. CRUCIBLE_SOULS_TITLE:'Набить килов в горниле душ',
  607. ESTER_EGGS: 'Пасхалки',
  608. ESTER_EGGS_TITLE: 'Собрать все пасхалки или награды',
  609. REWARDS: 'Награды',
  610. REWARDS_TITLE: 'Собрать все награды за задания',
  611. MAIL: 'Почта',
  612. MAIL_TITLE: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  613. MINIONS: 'Прислужники',
  614. MINIONS_TITLE: 'Атакует прислужников сохраннеными пачками',
  615. ADVENTURE: 'Приключение',
  616. ADVENTURE_TITLE: 'Проходит приключение по указанному маршруту',
  617. STORM: 'Буря',
  618. STORM_TITLE: 'Проходит бурю по указанному маршруту',
  619. SANCTUARY: 'Святилище',
  620. SANCTUARY_TITLE: 'Быстрый переход к Святилищу',
  621. GUILD_WAR: 'Война гильдий',
  622. GUILD_WAR_TITLE: 'Быстрый переход к Войне гильдий',
  623. SECRET_WEALTH: 'Тайное богатство',
  624. SECRET_WEALTH_TITLE: 'Купить что-то в магазине "Тайное богатство"',
  625. /* Разное */
  626. BOTTOM_URLS: '<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank" title="Telegram"><svg width="20" height="20" style="margin:2px" viewBox="0 0 1e3 1e3" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="a" x1="50%" x2="50%" y2="99.258%"><stop stop-color="#2AABEE" offset="0"/><stop stop-color="#229ED9" offset="1"/></linearGradient></defs><g fill-rule="evenodd"><circle cx="500" cy="500" r="500" fill="url(#a)"/><path d="m226.33 494.72c145.76-63.505 242.96-105.37 291.59-125.6 138.86-57.755 167.71-67.787 186.51-68.119 4.1362-0.072862 13.384 0.95221 19.375 5.8132 5.0584 4.1045 6.4501 9.6491 7.1161 13.541 0.666 3.8915 1.4953 12.756 0.83608 19.683-7.5246 79.062-40.084 270.92-56.648 359.47-7.0089 37.469-20.81 50.032-34.17 51.262-29.036 2.6719-51.085-19.189-79.207-37.624-44.007-28.847-68.867-46.804-111.58-74.953-49.366-32.531-17.364-50.411 10.769-79.631 7.3626-7.6471 135.3-124.01 137.77-134.57 0.30968-1.3202 0.59708-6.2414-2.3265-8.8399s-7.2385-1.7099-10.352-1.0032c-4.4137 1.0017-74.715 47.468-210.9 139.4-19.955 13.702-38.029 20.379-54.223 20.029-17.853-0.3857-52.194-10.094-77.723-18.393-31.313-10.178-56.199-15.56-54.032-32.846 1.1287-9.0037 13.528-18.212 37.197-27.624z" fill="#fff"/></g></svg></a><a href="https://vk.com/invite/YNPxKGX" target="_blank" title="Вконтакте"><svg width="20" height="20" style="margin:2px" viewBox="0 0 101 100" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#a)"><path d="M0.5 48C0.5 25.3726 0.5 14.0589 7.52944 7.02944C14.5589 0 25.8726 0 48.5 0H52.5C75.1274 0 86.4411 0 93.4706 7.02944C100.5 14.0589 100.5 25.3726 100.5 48V52C100.5 74.6274 100.5 85.9411 93.4706 92.9706C86.4411 100 75.1274 100 52.5 100H48.5C25.8726 100 14.5589 100 7.52944 92.9706C0.5 85.9411 0.5 74.6274 0.5 52V48Z" fill="#07f"/><path d="m53.708 72.042c-22.792 0-35.792-15.625-36.333-41.625h11.417c0.375 19.083 8.7915 27.167 15.458 28.833v-28.833h10.75v16.458c6.5833-0.7083 13.499-8.2082 15.832-16.458h10.75c-1.7917 10.167-9.2917 17.667-14.625 20.75 5.3333 2.5 13.875 9.0417 17.125 20.875h-11.834c-2.5417-7.9167-8.8745-14.042-17.25-14.875v14.875h-1.2919z" fill="#fff"/></g><defs><clipPath id="a"><rect transform="translate(.5)" width="100" height="100" fill="#fff"/></clipPath></defs></svg></a>',
  627. GIFTS_SENT: 'Подарки отправлены!',
  628. DO_YOU_WANT: 'Вы действительно хотите это сделать?',
  629. BTN_RUN: 'Запускай',
  630. BTN_CANCEL: 'Отмена',
  631. BTN_OK: 'Ок',
  632. MSG_HAVE_BEEN_DEFEATED: 'Вы потерпели поражение!',
  633. BTN_AUTO: 'Авто',
  634. MSG_YOU_APPLIED: 'Вы нанесли',
  635. MSG_DAMAGE: 'урона',
  636. MSG_CANCEL_AND_STAT: 'Авто (F5) и показать Статистику',
  637. MSG_REPEAT_MISSION: 'Повторить миссию?',
  638. BTN_REPEAT: 'Повторить',
  639. BTN_NO: 'Нет',
  640. MSG_SPECIFY_QUANT: 'Указать количество:',
  641. BTN_OPEN: 'Открыть',
  642. QUESTION_COPY: 'Вопрос скопирован в буфер обмена',
  643. ANSWER_KNOWN: 'Ответ известен',
  644. ANSWER_NOT_KNOWN: 'ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН',
  645. BEING_RECALC: 'Идет прерасчет боя',
  646. THIS_TIME: 'На этот раз',
  647. VICTORY: '<span style="color:green;">ПОБЕДА</span>',
  648. DEFEAT: '<span style="color:red;">ПОРАЖЕНИЕ</span>',
  649. CHANCE_TO_WIN: 'Шансы на победу <span style="color:red;">на основе прерасчета</span>',
  650. OPEN_DOLLS: 'матрешек рекурсивно',
  651. SENT_QUESTION: 'Вопрос отправлен',
  652. SETTINGS: 'Настройки',
  653. MSG_BAN_ATTENTION: '<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?',
  654. BTN_YES_I_AGREE: 'Да, я беру на себя все риски!',
  655. BTN_NO_I_AM_AGAINST: 'Нет, я отказываюсь от этого!',
  656. VALUES: 'Значения',
  657. SAVING: 'Сохранка',
  658. USER_ID: 'айди пользователя',
  659. SEND_GIFT: 'Подарок отправлен',
  660. EXPEDITIONS_SENT: 'Экспедиции:<br>Собрано: {countGet}<br>Отправлено: {countSend}',
  661. EXPEDITIONS_NOTHING: 'Нечего собирать/отправлять',
  662. TITANIT: 'Титанит',
  663. COMPLETED: 'завершено',
  664. FLOOR: 'Этаж',
  665. LEVEL: 'Уровень',
  666. BATTLES: 'бои',
  667. EVENT: 'Эвент',
  668. NOT_AVAILABLE: 'недоступен',
  669. NO_HEROES: 'Нет героев',
  670. DAMAGE_AMOUNT: 'Количество урона',
  671. NOTHING_TO_COLLECT: 'Нечего собирать',
  672. COLLECTED: 'Собрано',
  673. REWARD: 'наград',
  674. REMAINING_ATTEMPTS: 'Осталось попыток',
  675. BATTLES_CANCELED: 'Битв отменено',
  676. MINION_RAID: 'Рейд прислужников',
  677. STOPPED: 'Остановлено',
  678. REPETITIONS: 'Повторений',
  679. MISSIONS_PASSED: 'Миссий пройдено',
  680. STOP: 'остановить',
  681. TOTAL_OPEN: 'Всего открыто',
  682. OPEN: 'Открыто',
  683. ROUND_STAT: 'Статистика урона за',
  684. BATTLE: 'боев',
  685. MINIMUM: 'Минимальный',
  686. MAXIMUM: 'Максимальный',
  687. AVERAGE: 'Средний',
  688. NOT_THIS_TIME: 'Не в этот раз',
  689. RETRY_LIMIT_EXCEEDED: 'Превышен лимит попыток',
  690. SUCCESS: 'Успех',
  691. RECEIVED: 'Получено',
  692. LETTERS: 'писем',
  693. PORTALS: 'порталов',
  694. ATTEMPTS: 'попыток',
  695. QUEST_10001: 'Улучши умения героев 3 раза',
  696. QUEST_10002: 'Пройди 10 миссий',
  697. QUEST_10003: 'Пройди 3 героические миссии',
  698. QUEST_10004: 'Сразись 3 раза на Арене или Гранд Арене',
  699. QUEST_10006: 'Используй обмен изумрудов 1 раз',
  700. QUEST_10007: 'Соверши 1 призыв в Атриуме Душ',
  701. QUEST_10016: 'Отправь подарки согильдийцам',
  702. QUEST_10018: 'Используй зелье опыта',
  703. QUEST_10019: 'Открой 1 сундук в Башне',
  704. QUEST_10020: 'Открой 3 сундука в Запределье',
  705. QUEST_10021: 'Собери 75 Титанита в Подземелье Гильдии',
  706. QUEST_10021: 'Собери 150 Титанита в Подземелье Гильдии',
  707. QUEST_10023: 'Прокачай Дар Стихий на 1 уровень',
  708. QUEST_10024: 'Повысь уровень любого артефакта один раз',
  709. QUEST_10025: 'Начни 1 Экспедицию',
  710. QUEST_10026: 'Начни 4 Экспедиции',
  711. QUEST_10027: 'Победи в 1 бою Турнира Стихий',
  712. QUEST_10028: 'Повысь уровень любого артефакта титанов',
  713. QUEST_10029: 'Открой сферу артефактов титанов',
  714. QUEST_10030: 'Улучши облик любого героя 1 раз',
  715. QUEST_10031: 'Победи в 6 боях Турнира Стихий',
  716. QUEST_10043: 'Начни или присоеденись к Приключению',
  717. QUEST_10044: 'Воспользуйся призывом питомцев 1 раз',
  718. QUEST_10046: 'Открой 3 сундука в Приключениях',
  719. QUEST_10047: 'Набери 150 очков активности в Гильдии',
  720. NOTHING_TO_DO: 'Нечего выполнять',
  721. YOU_CAN_COMPLETE: 'Можно выполнить квесты',
  722. BTN_DO_IT: 'Выполняй',
  723. NOT_QUEST_COMPLETED: 'Ни одного квеста не выполенно',
  724. COMPLETED_QUESTS: 'Выполнено квестов',
  725. /* everything button */
  726. ASSEMBLE_OUTLAND: 'Собрать Запределье',
  727. PASS_THE_TOWER: 'Пройти башню',
  728. CHECK_EXPEDITIONS: 'Проверить экспедиции',
  729. COMPLETE_TOE: 'Пройти Турнир Стихий',
  730. COMPLETE_DUNGEON: 'Пройти подземелье',
  731. COMPLETE_DUNGEON_FULL: 'Пройти подземелье фулл',
  732. COLLECT_MAIL: 'Собрать почту',
  733. COLLECT_MISC: 'Собрать всякую херню',
  734. COLLECT_MISC_TITLE: 'Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души',
  735. COLLECT_QUEST_REWARDS: 'Собрать награды за квесты',
  736. MAKE_A_SYNC: 'Сделать синхронизацию',
  737.  
  738. RUN_FUNCTION: 'Выполнить следующие функции?',
  739. BTN_GO: 'Погнали!',
  740. PERFORMED: 'Выполняется',
  741. DONE: 'Выполнено',
  742. ERRORS_OCCURRES: 'Призошли ошибки при выполнении',
  743. COPY_ERROR: 'Скопировать в буфер информацию об ошибке',
  744. BTN_YES: 'Да',
  745. ALL_TASK_COMPLETED: 'Все задачи выполнены',
  746.  
  747. UNKNOWN: 'Неизвестно',
  748. ENTER_THE_PATH: 'Введите путь приключения через запятые или дефисы',
  749. START_ADVENTURE: 'Начать приключение по этому пути!',
  750. INCORRECT_WAY: 'Неверный путь в приключении: {from} -> {to}',
  751. BTN_CANCELED: 'Отменено',
  752. MUST_TWO_POINTS: 'Путь должен состоять минимум из 2х точек',
  753. MUST_ONLY_NUMBERS: 'Путь должен содержать только цифры и запятые',
  754. NOT_ON_AN_ADVENTURE: 'Вы не в приключении',
  755. YOU_IN_NOT_ON_THE_WAY: 'Указанный путь должен включать точку вашего положения',
  756. ATTEMPTS_NOT_ENOUGH: 'Ваших попыток не достаточно для завершения пути, продолжить?',
  757. YES_CONTINUE: 'Да, продолжай!',
  758. NOT_ENOUGH_AP: 'Попыток не достаточно',
  759. ATTEMPTS_ARE_OVER: 'Попытки закончились',
  760. MOVES: 'Ходы',
  761. BUFF_GET_ERROR: 'Ошибка при получении бафа',
  762. BATTLE_END_ERROR: 'Ошибка завершения боя',
  763. AUTOBOT: 'АвтоБой',
  764. FAILED_TO_WIN_AUTO: 'Не удалось победить в автобою',
  765. ERROR_OF_THE_BATTLE_COPY: 'Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?',
  766. ERROR_DURING_THE_BATTLE: 'Ошибка в процессе прохождения боя',
  767. NO_CHANCE_WIN: 'Нет шансов победить в этом бою: 0/',
  768. LOST_HEROES: 'Вы победили, но потеряли одного или несколько героев!',
  769. VICTORY_IMPOSSIBLE: 'Победа не возможна, бъем на результат?',
  770. FIND_COEFF: 'Поиск коэффициента больше чем',
  771. BTN_PASS: 'ПРОПУСК',
  772. BRAWLS: 'Потасовки',
  773. BRAWLS_TITLE: 'Включает возможность автопотасовок',
  774. START_AUTO_BRAWLS: 'Запустить Автопотасовки?',
  775. LOSSES: 'Поражений',
  776. WINS: 'Побед',
  777. FIGHTS: 'Боев',
  778. STAGE: 'Стадия',
  779. DONT_HAVE_LIVES: 'У Вас нет жизней',
  780. LIVES: 'Жизни',
  781. SECRET_WEALTH_ALREADY: 'товар за Зелья питомцев уже куплен',
  782. SECRET_WEALTH_NOT_ENOUGH: 'Не достаточно Зелье Питомца, у Вас {available}, нужно {need}',
  783. SECRET_WEALTH_UPGRADE_NEW_PET: 'После покупки Зелье Питомца будет не достаточно для прокачки нового питомца',
  784. SECRET_WEALTH_PURCHASED: 'Куплено {count} {name}',
  785. SECRET_WEALTH_CANCELED: 'Тайное богатство: покупка отменена',
  786. SECRET_WEALTH_BUY: 'У вас {available} Зелье Питомца.<br>Вы хотите купить {countBuy} {name} за {price} Зелье Питомца?',
  787. DAILY_BONUS: 'Ежедневная награда',
  788. DO_DAILY_QUESTS: 'Сделать ежедневные квесты',
  789. ACTIONS: 'Действия',
  790. ACTIONS_TITLE: 'Диалоговое окно с различными действиями',
  791. OTHERS: 'Разное',
  792. OTHERS_TITLE: 'Диалоговое окно с дополнительными различными действиями',
  793. CHOOSE_ACTION: 'Выберите действие',
  794. OPEN_LOOTBOX: 'У Вас {lootBox} ящиков, откываем?',
  795. STAMINA: 'Энергия',
  796. BOXES_OVER: 'Ящики закончились',
  797. NO_BOXES: 'Нет ящиков',
  798. NO_MORE_ACTIVITY: 'Больше активности за предметы сегодня не получить',
  799. EXCHANGE_ITEMS: 'Обменять предметы на очки активности (не более {maxActive})?',
  800. GET_ACTIVITY: 'Получить активность',
  801. NOT_ENOUGH_ITEMS: 'Предметов недостаточно',
  802. ACTIVITY_RECEIVED: 'Получено активности',
  803. NO_PURCHASABLE_HERO_SOULS: 'Нет доступных для покупки душ героев',
  804. PURCHASED_HERO_SOULS: 'Куплено {countHeroSouls} душ героев',
  805. NOT_ENOUGH_EMERALDS_540: 'Недостаточно изюма, нужно {imgEmerald}540 у Вас {imgEmerald}{currentStarMoney}',
  806. BUY_OUTLAND_BTN: 'Купить {count} сундуков {imgEmerald}{countEmerald}',
  807. CHESTS_NOT_AVAILABLE: 'Сундуки не доступны',
  808. OUTLAND_CHESTS_RECEIVED: 'Получено сундуков Запределья',
  809. RAID_NOT_AVAILABLE: 'Рейд не доступен или сфер нет',
  810. RAID_ADVENTURE: 'Рейд {adventureId} приключения!',
  811. SOMETHING_WENT_WRONG: 'Что-то пошло не так',
  812. ADVENTURE_COMPLETED: 'Приключение {adventureId} пройдено {times} раз',
  813. CLAN_STAT_COPY: 'Клановая статистика скопирована в буфер обмена',
  814. GET_ENERGY: 'Получить энергию',
  815. GET_ENERGY_TITLE: 'Открывает платиновые шкатулки по одной до получения 250 энергии',
  816. ITEM_EXCHANGE: 'Обмен предметов',
  817. ITEM_EXCHANGE_TITLE: 'Обменивает предметы на указанное количество активности',
  818. BUY_SOULS: 'Купить души',
  819. BUY_SOULS_TITLE: 'Купить души героев из всех доступных магазинов',
  820. BUY_OUTLAND: 'Купить Запределье',
  821. BUY_OUTLAND_TITLE: 'Купить 9 сундуков в Запределье за 540 изумрудов',
  822. RAID: 'Рейд',
  823. AUTO_RAID_ADVENTURE: 'Рейд приключения',
  824. AUTO_RAID_ADVENTURE_TITLE: 'Рейд приключения заданное количество раз',
  825. CLAN_STAT: 'Клановая статистика',
  826. CLAN_STAT_TITLE: 'Копирует клановую статистику в буфер обмена',
  827. BTN_AUTO_F5: 'Авто (F5)',
  828. BOSS_DAMAGE: 'Урон по боссу: ',
  829. NOTHING_BUY: 'Нечего покупать',
  830. LOTS_BOUGHT: 'За золото куплено {countBuy} лотов',
  831. BUY_FOR_GOLD: 'Скупить за золото',
  832. BUY_FOR_GOLD_TITLE: 'Скупить предметы за золото в Городской лавке и в магазине Камней Душ Питомцев',
  833. REWARDS_AND_MAIL: 'Награды и почта',
  834. REWARDS_AND_MAIL_TITLE: 'Собирает награды и почту',
  835. New_Year_Clan: 'подарок другу',
  836. New_Year_Clan_TITLE: 'Новогодние подарки друзьям',
  837. COLLECT_REWARDS_AND_MAIL: 'Собрано {countQuests} наград и {countMail} писем',
  838. TIMER_ALREADY: 'Таймер уже запущен {time}',
  839. NO_ATTEMPTS_TIMER_START: 'Попыток нет, запущен таймер {time}',
  840. EPIC_BRAWL_RESULT: '{i} Победы: {wins}/{attempts}, Монеты: {coins}, Серия: {progress}/{nextStage} [Закрыть]{end}',
  841. ATTEMPT_ENDED: '<br>Попытки закончились, запущен таймер {time}',
  842. EPIC_BRAWL: 'Вселенская битва',
  843. EPIC_BRAWL_TITLE: 'Тратит попытки во Вселенской битве',
  844. RELOAD_GAME: 'Перезагрузить игру',
  845. TIMER: 'Таймер:',
  846. SHOW_ERRORS: 'Отображать ошибки',
  847. SHOW_ERRORS_TITLE: 'Отображать ошибки запросов к серверу',
  848. ERROR_MSG: 'Ошибка: {name}<br>{description}',
  849. EVENT_AUTO_BOSS: 'Максимальное количество боев для расчета:</br>{length} * {countTestBattle} = {maxCalcBattle}</br>Если у Вас слабый компьютер на это может потребоваться много времени, нажмите крестик для отмены.</br>Искать лучший пак из всех или первый подходящий?',
  850. BEST_SLOW: 'Лучший (медленее)',
  851. FIRST_FAST: 'Первый (быстрее)',
  852. FREEZE_INTERFACE: 'Идет расчет... <br> Интерфейс может зависнуть.',
  853. ERROR_F12: 'Ошибка, подробности в консоли (F12)',
  854. FAILED_FIND_WIN_PACK: 'Победный пак найти не удалось',
  855. BEST_PACK: 'Наилучший пак: ',
  856. BOSS_HAS_BEEN_DEF: 'Босс {bossLvl} побежден',
  857. NOT_ENOUGH_ATTEMPTS_BOSS: 'Для победы босса ${bossLvl} не хватило попыток, повторить?',
  858. BOSS_VICTORY_IMPOSSIBLE: 'По результатам прерасчета {battles} боев победу получить не удалось. Вы хотите продолжить поиск победного боя на реальных боях?',
  859. BOSS_HAS_BEEN_DEF_TEXT: 'Босс {bossLvl} побежден за<br>{countBattle}/{countMaxBattle} попыток<br>(Сделайте синхронизацию или перезагрузите игру для обновления данных)',
  860. MAP: 'Карта: ',
  861. PLAYER_POS: 'Позиции игроков:',
  862. NY_GIFTS: 'Подарки',
  863. NY_GIFTS_TITLE: 'Открыть все новогодние подарки',
  864. NY_NO_GIFTS: 'Нет не полученных подарков',
  865. NY_GIFTS_COLLECTED: 'Собрано {count} подарков',
  866. CHANGE_MAP: 'Карта острова',
  867. CHANGE_MAP_TITLE: 'Сменить карту острова',
  868. SELECT_ISLAND_MAP: 'Выберите карту острова:',
  869. MAP_NUM: 'Карта {num}',
  870. SECRET_WEALTH_SHOP: 'Тайное богатство {name}: ',
  871. SHOPS: 'Магазины',
  872. SHOPS_DEFAULT: 'Стандартные',
  873. SHOPS_DEFAULT_TITLE: 'Стандартные магазины',
  874. SHOPS_LIST: 'Магазины {number}',
  875. SHOPS_LIST_TITLE: 'Список магазинов {number}',
  876. SHOPS_WARNING: 'Магазины<br><span style="color:red">Если Вы купите монеты магазинов потасовок за изумруды, то их надо использовать сразу, иначе после перезагрузки игры они пропадут!</span>',
  877. MINIONS_WARNING: 'Пачки героев для атаки приспешников неполные, продолжить?',
  878. FAST_SEASON: 'Быстрый сезон',
  879. FAST_SEASON_TITLE: 'Пропуск экрана с выбором карты в сезоне',
  880. SET_NUMBER_LEVELS: 'Указать колличество уровней:',
  881. POSSIBLE_IMPROVE_LEVELS: 'Возможно улучшить только {count} уровней.<br>Улучшаем?',
  882. NOT_ENOUGH_RESOURECES: 'Не хватает ресурсов',
  883. IMPROVED_LEVELS: 'Улучшено уровней: {count}',
  884. ARTIFACTS_UPGRADE: 'Улучшение артефактов',
  885. ARTIFACTS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых артефактов героев',
  886. SKINS_UPGRADE: 'Улучшение обликов',
  887. SKINS_UPGRADE_TITLE: 'Улучшает указанное количество самых дешевых обликов героев',
  888. HINT: '<br>Подсказка: ',
  889. PICTURE: '<br>На картинке: ',
  890. ANSWER: '<br>Ответ: ',
  891. NO_HEROES_PACK: 'Проведите хотя бы один бой для сохранения атакующей команды',
  892. BRAWL_AUTO_PACK: 'Автоподбор пачки',
  893. BRAWL_AUTO_PACK_NOT_CUR_HERO: 'Автоматический подбор пачки не подходит для текущего героя',
  894. BRAWL_DAILY_TASK_COMPLETED: 'Ежедневное задание выполнено, продолжить атаку?',
  895. CALC_STAT: 'Посчитать статистику',
  896. ELEMENT_TOURNAMENT_REWARD: 'Несобранная награда за Турнир Стихий',
  897. BTN_TRY_FIX_IT: 'Исправить',
  898. BTN_TRY_FIX_IT_TITLE: 'Включить исправление боев при автоатаке',
  899. DAMAGE_FIXED: 'Урон исправлен с {lastDamage} до {maxDamage}!',
  900. DAMAGE_NO_FIXED: 'Не удалось исправить урон: {lastDamage}',
  901. LETS_FIX: 'Исправляем',
  902. COUNT_FIXED: 'За {count} попыток',
  903. DEFEAT_TURN_TIMER: 'Поражение! Включить таймер для завершения миссии?',
  904. SEASON_REWARD: 'Награды сезонов',
  905. SEASON_REWARD_TITLE: 'Собирает доступные бесплатные награды со всех текущих сезонов',
  906. SEASON_REWARD_COLLECTED: 'Собрано {count} наград сезонов',
  907. SELL_HERO_SOULS: 'Продать души',
  908. SELL_HERO_SOULS_TITLE: 'Обменивает все души героев с абсолютной звездой на золото',
  909. GOLD_RECEIVED: 'Получено золота: {gold}',
  910. OPEN_ALL_EQUIP_BOXES: 'Открыть все ящики фрагментов экипировки?',
  911. },
  912. };
  913.  
  914. function getLang() {
  915. let lang = '';
  916. if (typeof NXFlashVars !== 'undefined') {
  917. lang = NXFlashVars.interface_lang
  918. }
  919. if (!lang) {
  920. lang = (navigator.language || navigator.userLanguage).substr(0, 2);
  921. }
  922. if (lang == 'ru') {
  923. return lang;
  924. }
  925. return 'en';
  926. }
  927.  
  928. this.I18N = function (constant, replace) {
  929. const selectLang = getLang();
  930. if (constant && constant in i18nLangData[selectLang]) {
  931. const result = i18nLangData[selectLang][constant];
  932. if (replace) {
  933. return result.sprintf(replace);
  934. }
  935. return result;
  936. }
  937. return `% ${constant} %`;
  938. };
  939.  
  940. String.prototype.sprintf = String.prototype.sprintf ||
  941. function () {
  942. "use strict";
  943. var str = this.toString();
  944. if (arguments.length) {
  945. var t = typeof arguments[0];
  946. var key;
  947. var args = ("string" === t || "number" === t) ?
  948. Array.prototype.slice.call(arguments)
  949. : arguments[0];
  950.  
  951. for (key in args) {
  952. str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
  953. }
  954. }
  955.  
  956. return str;
  957. };
  958.  
  959. /**
  960. * Checkboxes
  961. *
  962. * Чекбоксы
  963. */
  964. const checkboxes = {
  965. passBattle: {
  966. label: I18N('SKIP_FIGHTS'),
  967. cbox: null,
  968. title: I18N('SKIP_FIGHTS_TITLE'),
  969. default: false,
  970. },
  971. /*sendExpedition: {
  972. label: I18N('AUTO_EXPEDITION'),
  973. cbox: null,
  974. title: I18N('AUTO_EXPEDITION_TITLE'),
  975. default: false,
  976. },*/ //тест сдедал экспедиции на авто в сделать все
  977. cancelBattle: {
  978. label: I18N('CANCEL_FIGHT'),
  979. cbox: null,
  980. title: I18N('CANCEL_FIGHT_TITLE'),
  981. default: false,
  982. },
  983. preCalcBattle: {
  984. label: I18N('BATTLE_RECALCULATION'),
  985. cbox: null,
  986. title: I18N('BATTLE_RECALCULATION_TITLE'),
  987. default: false,
  988. },
  989. finishingBattle: {
  990. label: I18N('BATTLE_FISHING'),
  991. cbox: null,
  992. title: I18N('BATTLE_FISHING_TITLE'),
  993. default: false,
  994. },
  995. treningBattle: {
  996. label: I18N('BATTLE_TRENING'),
  997. cbox: null,
  998. title: I18N('BATTLE_TRENING_TITLE'),
  999. default: false,
  1000. },
  1001. countControl: {
  1002. label: I18N('QUANTITY_CONTROL'),
  1003. cbox: null,
  1004. title: I18N('QUANTITY_CONTROL_TITLE'),
  1005. default: true,
  1006. },
  1007. repeatMission: {
  1008. label: I18N('REPEAT_CAMPAIGN'),
  1009. cbox: null,
  1010. title: I18N('REPEAT_CAMPAIGN_TITLE'),
  1011. default: false,
  1012. },
  1013. noOfferDonat: {
  1014. label: I18N('DISABLE_DONAT'),
  1015. cbox: null,
  1016. title: I18N('DISABLE_DONAT_TITLE'),
  1017. /**
  1018. * A crutch to get the field before getting the character id
  1019. *
  1020. * Костыль чтоб получать поле до получения id персонажа
  1021. */
  1022. default: (() => {
  1023. $result = false;
  1024. try {
  1025. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat']);
  1026. } catch (e) {
  1027. $result = false;
  1028. }
  1029. return $result || false;
  1030. })(),
  1031. },
  1032. dailyQuests: {
  1033. label: I18N('DAILY_QUESTS'),
  1034. cbox: null,
  1035. title: I18N('DAILY_QUESTS_TITLE'),
  1036. default: false,
  1037. },
  1038. // Потасовки
  1039. /*
  1040. autoBrawls: {
  1041. label: I18N('BRAWLS'),
  1042. cbox: null,
  1043. title: I18N('BRAWLS_TITLE'),
  1044. default: (() => {
  1045. $result = false;
  1046. try {
  1047. $result = JSON.parse(localStorage[GM_info.script.name + ':autoBrawls']);
  1048. } catch (e) {
  1049. $result = false;
  1050. }
  1051. return $result || false;
  1052. })(),
  1053. hide: false,
  1054. },
  1055. getAnswer: {
  1056. label: I18N('AUTO_QUIZ'),
  1057. cbox: null,
  1058. title: I18N('AUTO_QUIZ_TITLE'),
  1059. default: false,
  1060. hide: true,
  1061. },*/
  1062. tryFixIt: {
  1063. label: I18N('BTN_TRY_FIX_IT'),
  1064. cbox: null,
  1065. title: I18N('BTN_TRY_FIX_IT_TITLE'),
  1066. default: false,
  1067. hide: false,
  1068. },
  1069. showErrors: {
  1070. label: I18N('SHOW_ERRORS'),
  1071. cbox: null,
  1072. title: I18N('SHOW_ERRORS_TITLE'),
  1073. default: true,
  1074. },
  1075. buyForGold: {
  1076. label: I18N('BUY_FOR_GOLD'),
  1077. cbox: null,
  1078. title: I18N('BUY_FOR_GOLD_TITLE'),
  1079. default: false,
  1080. },
  1081. hideServers: {
  1082. label: I18N('HIDE_SERVERS'),
  1083. cbox: null,
  1084. title: I18N('HIDE_SERVERS_TITLE'),
  1085. default: false,
  1086. },
  1087. fastSeason: {
  1088. label: I18N('FAST_SEASON'),
  1089. cbox: null,
  1090. title: I18N('FAST_SEASON_TITLE'),
  1091. default: false,
  1092. },
  1093. };
  1094. /**
  1095. * Get checkbox state
  1096. *
  1097. * Получить состояние чекбокса
  1098. */
  1099. function isChecked(checkBox) {
  1100. if (!(checkBox in checkboxes)) {
  1101. return false;
  1102. }
  1103. return checkboxes[checkBox].cbox?.checked;
  1104. }
  1105. /**
  1106. * Input fields
  1107. *
  1108. * Поля ввода
  1109. */
  1110. const inputs = {
  1111. countTitanit: {
  1112. input: null,
  1113. title: I18N('HOW_MUCH_TITANITE'),
  1114. default: 150,
  1115. },
  1116. speedBattle: {
  1117. input: null,
  1118. title: I18N('COMBAT_SPEED'),
  1119. default: 5,
  1120. },
  1121. //тест повтор компании
  1122. countRaid: {
  1123. input: null,
  1124. title: I18N('HOW_REPEAT_CAMPAIGN'),
  1125. default: 5,
  1126. },
  1127. countTestBattle: {
  1128. input: null,
  1129. title: I18N('NUMBER_OF_TEST'),
  1130. default: 10,
  1131. },
  1132. countAutoBattle: {
  1133. input: null,
  1134. title: I18N('NUMBER_OF_AUTO_BATTLE'),
  1135. default: 10,
  1136. },
  1137. /*FPS: {
  1138. input: null,
  1139. title: 'FPS',
  1140. default: 60,
  1141. }*/
  1142. }
  1143. //сохранка тест
  1144. const inputs2 = {
  1145. countBattle: {
  1146. input: null,
  1147. title: '-1 сохраняет защиту, -2 атаку противника с Replay',
  1148. default: 1,
  1149. },
  1150. needResource: {
  1151. input: null,
  1152. title: 'Мощь противника мин.(тыс.)/урона(млн.)',
  1153. default: 300,
  1154. },
  1155. needResource2: {
  1156. input: null,
  1157. title: 'Мощь противника макс./тип бафа',
  1158. default: 1500,
  1159. },
  1160. }
  1161. //новогодние подарки игрокам других гильдий
  1162. const inputs3 = {
  1163. userID: { // айди игрока посмотреть открыв его инфо
  1164. input: null,
  1165. title: I18N('USER_ID_TITLE'),
  1166. default: 111111,
  1167. },
  1168. GiftNum: { // номер подарка считаем слева направо от 1 до 6, под 1 это за 750 новогодних игрушек
  1169. input: null,
  1170. title: I18N('GIFT_NUM'),
  1171. default: 10,
  1172. },
  1173. AmontID: { // количество ресурсов от 1 до бесконечности
  1174. input: null,
  1175. title: I18N('AMOUNT'),
  1176. default: 1,
  1177. },
  1178. }
  1179. /**
  1180. * Checks the checkbox
  1181. *
  1182. * Поплучить данные поля ввода
  1183. */
  1184. /*function getInput(inputName) {
  1185. return inputs[inputName]?.input?.value;
  1186. }*/
  1187. function getInput(inputName) {
  1188. if (inputName in inputs){return inputs[inputName]?.input?.value;}
  1189. else if (inputName in inputs2){return inputs2[inputName]?.input?.value;}
  1190. //else if (inputName in inputs3){return inputs3[inputName]?.input?.value;}
  1191. else return null
  1192. }
  1193.  
  1194. //тест рейд
  1195. /** Автоповтор миссии */
  1196. let isRepeatMission = false;
  1197. /** Вкл/Выкл автоповтор миссии */
  1198. this.switchRepeatMission = function() {
  1199. isRepeatMission = !isRepeatMission;
  1200. console.log(isRepeatMission);
  1201. }
  1202.  
  1203. /**
  1204. * Control FPS
  1205. *
  1206. * Контроль FPS
  1207. */
  1208. let nextAnimationFrame = Date.now();
  1209. const oldRequestAnimationFrame = this.requestAnimationFrame;
  1210. this.requestAnimationFrame = async function (e) {
  1211. const FPS = Number(getInput('FPS')) || -1;
  1212. const now = Date.now();
  1213. const delay = nextAnimationFrame - now;
  1214. nextAnimationFrame = Math.max(now, nextAnimationFrame) + Math.min(1e3 / FPS, 1e3);
  1215. if (delay > 0) {
  1216. await new Promise((e) => setTimeout(e, delay));
  1217. }
  1218. oldRequestAnimationFrame(e);
  1219. };
  1220.  
  1221. /**
  1222. * Button List
  1223. *
  1224. * Список кнопочек
  1225. */
  1226. const buttons = {
  1227. getOutland: {
  1228. name: I18N('TO_DO_EVERYTHING'),
  1229. title: I18N('TO_DO_EVERYTHING_TITLE'),
  1230. func: testDoYourBest,
  1231. },
  1232. /*
  1233. doActions: {
  1234. name: I18N('ACTIONS'),
  1235. title: I18N('ACTIONS_TITLE'),
  1236. func: async function () {
  1237. const popupButtons = [
  1238. {
  1239. msg: I18N('OUTLAND'),
  1240. result: function () {
  1241. confShow(`${I18N('RUN_SCRIPT')} ${I18N('OUTLAND')}?`, getOutland);
  1242. },
  1243. title: I18N('OUTLAND_TITLE'),
  1244. },
  1245. {
  1246. msg: I18N('TOWER'),
  1247. result: function () {
  1248. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TOWER')}?`, testTower);
  1249. },
  1250. title: I18N('TOWER_TITLE'),
  1251. },
  1252. {
  1253. msg: I18N('EXPEDITIONS'),
  1254. result: function () {
  1255. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EXPEDITIONS')}?`, checkExpedition);
  1256. },
  1257. title: I18N('EXPEDITIONS_TITLE'),
  1258. },
  1259. {
  1260. msg: I18N('MINIONS'),
  1261. result: function () {
  1262. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1263. },
  1264. title: I18N('MINIONS_TITLE'),
  1265. },
  1266. {
  1267. msg: I18N('ESTER_EGGS'),
  1268. result: function () {
  1269. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ESTER_EGGS')}?`, offerFarmAllReward);
  1270. },
  1271. title: I18N('ESTER_EGGS_TITLE'),
  1272. },
  1273. {
  1274. msg: I18N('STORM'),
  1275. result: function () {
  1276. testAdventure('solo');
  1277. },
  1278. title: I18N('STORM_TITLE'),
  1279. },
  1280. {
  1281. msg: I18N('REWARDS'),
  1282. result: function () {
  1283. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS')}?`, questAllFarm);
  1284. },
  1285. title: I18N('REWARDS_TITLE'),
  1286. },
  1287. {
  1288. msg: I18N('MAIL'),
  1289. result: function () {
  1290. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MAIL')}?`, mailGetAll);
  1291. },
  1292. title: I18N('MAIL_TITLE'),
  1293. },
  1294. {
  1295. msg: I18N('SEER'),
  1296. result: function () {
  1297. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SEER')}?`, rollAscension);
  1298. },
  1299. title: I18N('SEER_TITLE'),
  1300. },
  1301. {
  1302. msg: I18N('NY_GIFTS'),
  1303. result: getGiftNewYear,
  1304. title: I18N('NY_GIFTS_TITLE'),
  1305. },
  1306. ];
  1307. popupButtons.push({ result: false, isClose: true })
  1308. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1309. if (typeof answer === 'function') {
  1310. answer();
  1311. }
  1312. }
  1313. },*/
  1314. doOthers: {
  1315. name: I18N('OTHERS'),
  1316. title: I18N('OTHERS_TITLE'),
  1317. func: async function () {
  1318. const popupButtons = [
  1319. /*
  1320. {
  1321. msg: I18N('GET_ENERGY'),
  1322. result: farmStamina,
  1323. title: I18N('GET_ENERGY_TITLE'),
  1324. },
  1325. {
  1326. msg: I18N('ITEM_EXCHANGE'),
  1327. result: fillActive,
  1328. title: I18N('ITEM_EXCHANGE_TITLE'),
  1329. },
  1330. {
  1331. msg: I18N('BUY_SOULS'),
  1332. result: function () {
  1333. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_SOULS')}?`, buyHeroFragments);
  1334. },
  1335. title: I18N('BUY_SOULS_TITLE'),
  1336. },
  1337. {
  1338. msg: I18N('BUY_FOR_GOLD'),
  1339. result: function () {
  1340. confShow(`${I18N('RUN_SCRIPT')} ${I18N('BUY_FOR_GOLD')}?`, buyInStoreForGold);
  1341. },
  1342. title: I18N('BUY_FOR_GOLD_TITLE'),
  1343. },
  1344. {
  1345. msg: I18N('BUY_OUTLAND'),
  1346. result: bossOpenChestPay,
  1347. title: I18N('BUY_OUTLAND_TITLE'),
  1348. },
  1349. {
  1350. msg: I18N('AUTO_RAID_ADVENTURE'),
  1351. result: autoRaidAdventure,
  1352. title: I18N('AUTO_RAID_ADVENTURE_TITLE'),
  1353. },
  1354. {
  1355. msg: I18N('CLAN_STAT'),
  1356. result: clanStatistic,
  1357. title: I18N('CLAN_STAT_TITLE'),
  1358. },
  1359. {
  1360. msg: I18N('EPIC_BRAWL'),
  1361. result: async function () {
  1362. confShow(`${I18N('RUN_SCRIPT')} ${I18N('EPIC_BRAWL')}?`, () => {
  1363. const brawl = new epicBrawl();
  1364. brawl.start();
  1365. });
  1366. },
  1367. title: I18N('EPIC_BRAWL_TITLE'),
  1368. },*/
  1369. {
  1370. msg: I18N('ARTIFACTS_UPGRADE'),
  1371. result: updateArtifacts,
  1372. title: I18N('ARTIFACTS_UPGRADE_TITLE'),
  1373. },
  1374. {
  1375. msg: I18N('SKINS_UPGRADE'),
  1376. result: updateSkins,
  1377. title: I18N('SKINS_UPGRADE_TITLE'),
  1378. },
  1379. {
  1380. msg: I18N('SEASON_REWARD'),
  1381. result: farmBattlePass,
  1382. title: I18N('SEASON_REWARD_TITLE'),
  1383. },
  1384. {
  1385. msg: I18N('SELL_HERO_SOULS'),
  1386. result: sellHeroSoulsForGold,
  1387. title: I18N('SELL_HERO_SOULS_TITLE'),
  1388. },
  1389. {
  1390. msg: I18N('CHANGE_MAP'),
  1391. result: async function () {
  1392. const maps = Object.values(lib.data.seasonAdventure.list)
  1393. .filter((e) => e.map.cells.length > 2)
  1394. .map((i) => ({
  1395. msg: I18N('MAP_NUM', { num: i.id }),
  1396. result: i.id,
  1397. }));
  1398.  
  1399. /*const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [
  1400. ...maps,
  1401. { result: false, isClose: true },
  1402. ]);*/
  1403. //тест карта острова
  1404. const result = await popup.confirm(I18N('SELECT_ISLAND_MAP'), [...maps, { result: false, isClose: true }]);
  1405. if (result) {
  1406. cheats.changeIslandMap(result);
  1407. }
  1408. },
  1409. title: I18N('CHANGE_MAP_TITLE'),
  1410. },
  1411. {
  1412. msg: I18N('SHOPS'),
  1413. result: async function () {
  1414. const shopButtons = [{
  1415. msg: I18N('SHOPS_DEFAULT'),
  1416. result: function () {
  1417. cheats.goDefaultShops();
  1418. },
  1419. title: I18N('SHOPS_DEFAULT_TITLE'),
  1420. }, {
  1421. msg: I18N('SECRET_WEALTH'),
  1422. result: function () {
  1423. cheats.goSecretWealthShops();
  1424. },
  1425. title: I18N('SECRET_WEALTH'),
  1426. }];
  1427. for (let i = 0; i < 4; i++) {
  1428. const number = i + 1;
  1429. shopButtons.push({
  1430. msg: I18N('SHOPS_LIST', { number }),
  1431. result: function () {
  1432. cheats.goCustomShops(i);
  1433. },
  1434. title: I18N('SHOPS_LIST_TITLE', { number }),
  1435. })
  1436. }
  1437. shopButtons.push({ result: false, isClose: true })
  1438. const answer = await popup.confirm(I18N('SHOPS_WARNING'), shopButtons);
  1439. if (typeof answer === 'function') {
  1440. answer();
  1441. }
  1442. },
  1443. title: I18N('SHOPS'),
  1444. },
  1445. ];
  1446.  
  1447. popupButtons.push({ result: false, isClose: true })
  1448. const answer = await popup.confirm(`${I18N('CHOOSE_ACTION')}:`, popupButtons);
  1449. if (typeof answer === 'function') {
  1450. answer();
  1451. }
  1452. }
  1453. },
  1454. testTitanArena: {
  1455. name: I18N('TITAN_ARENA'),
  1456. title: I18N('TITAN_ARENA_TITLE'),
  1457. func: function () {
  1458. confShow(`${I18N('RUN_SCRIPT')} ${I18N('TITAN_ARENA')}?`, testTitanArena);
  1459. },
  1460. },
  1461. /* тест подземка есть в сделать все
  1462. testDungeon: {
  1463. name: I18N('DUNGEON'),
  1464. title: I18N('DUNGEON_TITLE'),
  1465. func: function () {
  1466. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON')}?`, testDungeon);
  1467. },
  1468. hide: true,
  1469. },*/
  1470. //тест подземка 2
  1471. DungeonFull: {
  1472. name: I18N('DUNGEON2'),
  1473. title: I18N('DUNGEON_FULL_TITLE'),
  1474. func: function () {
  1475. confShow(`${I18N('RUN_SCRIPT')} ${I18N('DUNGEON_FULL_TITLE')}?`, DungeonFull);
  1476. },
  1477. },
  1478. //остановить подземелье
  1479. stopDungeon: {
  1480. name: I18N('STOP_DUNGEON'),
  1481. title: I18N('STOP_DUNGEON_TITLE'),
  1482. func: function () {
  1483. confShow(`${I18N('STOP_SCRIPT')} ${I18N('STOP_DUNGEON_TITLE')}?`, stopDungeon);
  1484. },
  1485. },
  1486. // Архидемон
  1487. bossRatingEvent: {
  1488. name: I18N('ARCHDEMON'),
  1489. title: I18N('ARCHDEMON_TITLE'),
  1490. func: function () {
  1491. confShow(`${I18N('RUN_SCRIPT')} ${I18N('ARCHDEMON')}?`, bossRatingEvent);
  1492. },
  1493. hide: true,
  1494. },
  1495. // Горнило душ
  1496. bossRatingEvent: {
  1497. name: I18N('CRUCIBLE_SOULS'),
  1498. title: I18N('CRUCIBLE_SOULS_TITLE'),
  1499. func: function () {
  1500. confShow(`${I18N('RUN_SCRIPT')} ${I18N('CRUCIBLE_SOULS')}?`, bossRatingEventSouls);
  1501. },
  1502. },
  1503. // Буря
  1504. /*testAdventure2: {
  1505. name: I18N('STORM'),
  1506. title: I18N('STORM_TITLE'),
  1507. func: () => {
  1508. testAdventure2('solo');
  1509. },
  1510. },*/
  1511. rewardsAndMailFarm: {
  1512. name: I18N('REWARDS_AND_MAIL'),
  1513. title: I18N('REWARDS_AND_MAIL_TITLE'),
  1514. func: function () {
  1515. confShow(`${I18N('RUN_SCRIPT')} ${I18N('REWARDS_AND_MAIL')}?`, rewardsAndMailFarm);
  1516. },
  1517. },
  1518. //тест прислужники
  1519. testRaidNodes: {
  1520. name: I18N('MINIONS'),
  1521. title: I18N('MINIONS_TITLE'),
  1522. func: function () {
  1523. confShow(`${I18N('RUN_SCRIPT')} ${I18N('MINIONS')}?`, testRaidNodes);
  1524. },
  1525. },
  1526. testAdventure: {
  1527. name: I18N('ADVENTURE'),
  1528. title: I18N('ADVENTURE_TITLE'),
  1529. func: () => {
  1530. testAdventure();
  1531. },
  1532. },
  1533. goToSanctuary: {
  1534. name: I18N('SANCTUARY'),
  1535. title: I18N('SANCTUARY_TITLE'),
  1536. func: cheats.goSanctuary,
  1537. },
  1538. goToClanWar: {
  1539. name: I18N('GUILD_WAR'),
  1540. title: I18N('GUILD_WAR_TITLE'),
  1541. func: cheats.goClanWar,
  1542. },
  1543. dailyQuests: {
  1544. name: I18N('DAILY_QUESTS'),
  1545. title: I18N('DAILY_QUESTS_TITLE'),
  1546. func: async function () {
  1547. const quests = new dailyQuests(() => { }, () => { });
  1548. await quests.autoInit();
  1549. quests.start();
  1550. },
  1551. },
  1552. //подарок др
  1553. /*NewYearGift_Clan: {
  1554. name: I18N('New_Year_Clan'),
  1555. title: I18N('New_Year_Clan_TITLE'),
  1556. func: function () {
  1557. confShow(`${I18N('RUN_SCRIPT')} ${I18N('New_Year_Clan_TITLE')}?`, NewYearGift_Clan);
  1558. },
  1559. },*/
  1560. newDay: {
  1561. name: I18N('SYNC'),
  1562. title: I18N('SYNC_TITLE'),
  1563. func: function () {
  1564. confShow(`${I18N('RUN_SCRIPT')} ${I18N('SYNC')}?`, cheats.refreshGame);
  1565. },
  1566. },
  1567. }
  1568. /**
  1569. * Display buttons
  1570. *
  1571. * Вывести кнопочки
  1572. */
  1573. function addControlButtons() {
  1574. for (let name in buttons) {
  1575. button = buttons[name];
  1576. if (button.hide) {
  1577. continue;
  1578. }
  1579. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  1580. }
  1581. }
  1582. /**
  1583. * Adds links
  1584. *
  1585. * Добавляет ссылки
  1586. */
  1587. function addBottomUrls() {
  1588. scriptMenu.addHeader(I18N('BOTTOM_URLS'));
  1589. }
  1590. /**
  1591. * Stop repetition of the mission
  1592. *
  1593. * Остановить повтор миссии
  1594. */
  1595. let isStopSendMission = false;
  1596. /**
  1597. * There is a repetition of the mission
  1598. *
  1599. * Идет повтор миссии
  1600. */
  1601. let isSendsMission = false;
  1602. /**
  1603. * Data on the past mission
  1604. *
  1605. * Данные о прошедшей мисии
  1606. */
  1607. let lastMissionStart = {}
  1608. /**
  1609. * Start time of the last battle in the company
  1610. *
  1611. * Время начала последнего боя в кампании
  1612. */
  1613. let lastMissionBattleStart = 0;
  1614. /**
  1615. * Data for calculating the last battle with the boss
  1616. *
  1617. * Данные для расчете последнего боя с боссом
  1618. */
  1619. let lastBossBattle = null;
  1620. /**
  1621. * Information about the last battle
  1622. *
  1623. * Данные о прошедшей битве
  1624. */
  1625. let lastBattleArg = {}
  1626. let lastBossBattleStart = null;
  1627. this.addBattleTimer = 4;
  1628. this.invasionTimer = 2500;
  1629. /**
  1630. * The name of the function of the beginning of the battle
  1631. *
  1632. * Имя функции начала боя
  1633. */
  1634. let nameFuncStartBattle = '';
  1635. /**
  1636. * The name of the function of the end of the battle
  1637. *
  1638. * Имя функции конца боя
  1639. */
  1640. let nameFuncEndBattle = '';
  1641. /**
  1642. * Data for calculating the last battle
  1643. *
  1644. * Данные для расчета последнего боя
  1645. */
  1646. let lastBattleInfo = null;
  1647. /**
  1648. * The ability to cancel the battle
  1649. *
  1650. * Возможность отменить бой
  1651. */
  1652. let isCancalBattle = true;
  1653.  
  1654. /**
  1655. * Certificator of the last open nesting doll
  1656. *
  1657. * Идетификатор последней открытой матрешки
  1658. */
  1659. let lastRussianDollId = null;
  1660. /**
  1661. * Cancel the training guide
  1662. *
  1663. * Отменить обучающее руководство
  1664. */
  1665. this.isCanceledTutorial = false;
  1666.  
  1667. /**
  1668. * Data from the last question of the quiz
  1669. *
  1670. * Данные последнего вопроса викторины
  1671. */
  1672. let lastQuestion = null;
  1673. /**
  1674. * Answer to the last question of the quiz
  1675. *
  1676. * Ответ на последний вопрос викторины
  1677. */
  1678. let lastAnswer = null;
  1679. /**
  1680. * Flag for opening keys or titan artifact spheres
  1681. *
  1682. * Флаг открытия ключей или сфер артефактов титанов
  1683. */
  1684. let artifactChestOpen = false;
  1685. /**
  1686. * The name of the function to open keys or orbs of titan artifacts
  1687. *
  1688. * Имя функции открытия ключей или сфер артефактов титанов
  1689. */
  1690. let artifactChestOpenCallName = '';
  1691. let correctShowOpenArtifact = 0;
  1692. /**
  1693. * Data for the last battle in the dungeon
  1694. * (Fix endless cards)
  1695. *
  1696. * Данные для последнего боя в подземке
  1697. * (Исправление бесконечных карт)
  1698. */
  1699. let lastDungeonBattleData = null;
  1700. /**
  1701. * Start time of the last battle in the dungeon
  1702. *
  1703. * Время начала последнего боя в подземелье
  1704. */
  1705. let lastDungeonBattleStart = 0;
  1706. /**
  1707. * Subscription end time
  1708. *
  1709. * Время окончания подписки
  1710. */
  1711. let subEndTime = 0;
  1712. /**
  1713. * Number of prediction cards
  1714. *
  1715. * Количество карт предсказаний
  1716. */
  1717. let countPredictionCard = 0;
  1718.  
  1719. /**
  1720. * Brawl pack
  1721. *
  1722. * Пачка для потасовок
  1723. */
  1724. let brawlsPack = null;
  1725. /**
  1726. * Autobrawl started
  1727. *
  1728. * Автопотасовка запущена
  1729. */
  1730. let isBrawlsAutoStart = false;
  1731. let clanDominationGetInfo = null;
  1732. /**
  1733. * Copies the text to the clipboard
  1734. *
  1735. * Копирует тест в буфер обмена
  1736. * @param {*} text copied text // копируемый текст
  1737. */
  1738. function copyText(text) {
  1739. let copyTextarea = document.createElement("textarea");
  1740. copyTextarea.style.opacity = "0";
  1741. copyTextarea.textContent = text;
  1742. document.body.appendChild(copyTextarea);
  1743. copyTextarea.select();
  1744. document.execCommand("copy");
  1745. document.body.removeChild(copyTextarea);
  1746. delete copyTextarea;
  1747. }
  1748. /**
  1749. * Returns the history of requests
  1750. *
  1751. * Возвращает историю запросов
  1752. */
  1753. this.getRequestHistory = function() {
  1754. return requestHistory;
  1755. }
  1756. /**
  1757. * Generates a random integer from min to max
  1758. *
  1759. * Гененирует случайное целое число от min до max
  1760. */
  1761. const random = function (min, max) {
  1762. return Math.floor(Math.random() * (max - min + 1) + min);
  1763. }
  1764. const randf = function (min, max) {
  1765. return Math.random() * (max - min + 1) + min;
  1766. };
  1767. /**
  1768. * Clearing the request history
  1769. *
  1770. * Очистка истоии запросов
  1771. */
  1772. setInterval(function () {
  1773. let now = Date.now();
  1774. for (let i in requestHistory) {
  1775. const time = +i.split('_')[0];
  1776. if (now - time > 300000) {
  1777. delete requestHistory[i];
  1778. }
  1779. }
  1780. }, 300000);
  1781. /**
  1782. * Displays the dialog box
  1783. *
  1784. * Отображает диалоговое окно
  1785. */
  1786. function confShow(message, yesCallback, noCallback) {
  1787. let buts = [];
  1788. message = message || I18N('DO_YOU_WANT');
  1789. noCallback = noCallback || (() => {});
  1790. if (yesCallback) {
  1791. buts = [
  1792. { msg: I18N('BTN_RUN'), result: true},
  1793. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true},
  1794. ]
  1795. } else {
  1796. yesCallback = () => {};
  1797. buts = [
  1798. { msg: I18N('BTN_OK'), result: true},
  1799. ];
  1800. }
  1801. popup.confirm(message, buts).then((e) => {
  1802. // dialogPromice = null;
  1803. if (e) {
  1804. yesCallback();
  1805. } else {
  1806. noCallback();
  1807. }
  1808. });
  1809. }
  1810. /**
  1811. * Override/proxy the method for creating a WS package send
  1812. *
  1813. * Переопределяем/проксируем метод создания отправки WS пакета
  1814. */
  1815. WebSocket.prototype.send = function (data) {
  1816. if (!this.isSetOnMessage) {
  1817. const oldOnmessage = this.onmessage;
  1818. this.onmessage = function (event) {
  1819. try {
  1820. const data = JSON.parse(event.data);
  1821. if (!this.isWebSocketLogin && data.result.type == "iframeEvent.login") {
  1822. this.isWebSocketLogin = true;
  1823. } else if (data.result.type == "iframeEvent.login") {
  1824. return;
  1825. }
  1826. } catch (e) { }
  1827. return oldOnmessage.apply(this, arguments);
  1828. }
  1829. this.isSetOnMessage = true;
  1830. }
  1831. original.SendWebSocket.call(this, data);
  1832. }
  1833. /**
  1834. * Overriding/Proxying the Ajax Request Creation Method
  1835. *
  1836. * Переопределяем/проксируем метод создания Ajax запроса
  1837. */
  1838. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  1839. this.uniqid = Date.now() + '_' + random(1000000, 10000000);
  1840. this.errorRequest = false;
  1841. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  1842. if (!apiUrl) {
  1843. apiUrl = url;
  1844. const socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  1845. console.log(socialInfo);
  1846. }
  1847. requestHistory[this.uniqid] = {
  1848. method,
  1849. url,
  1850. error: [],
  1851. headers: {},
  1852. request: null,
  1853. response: null,
  1854. signature: [],
  1855. calls: {},
  1856. };
  1857. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  1858. this.errorRequest = true;
  1859. }
  1860. return original.open.call(this, method, url, async, user, password);
  1861. };
  1862. /**
  1863. * Overriding/Proxying the header setting method for the AJAX request
  1864. *
  1865. * Переопределяем/проксируем метод установки заголовков для AJAX запроса
  1866. */
  1867. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  1868. if (this.uniqid in requestHistory) {
  1869. requestHistory[this.uniqid].headers[name] = value;
  1870. } else {
  1871. check = true;
  1872. }
  1873.  
  1874. if (name == 'X-Auth-Signature') {
  1875. requestHistory[this.uniqid].signature.push(value);
  1876. if (!check) {
  1877. return;
  1878. }
  1879. }
  1880.  
  1881. return original.setRequestHeader.call(this, name, value);
  1882. };
  1883. /**
  1884. * Overriding/Proxying the AJAX Request Sending Method
  1885. *
  1886. * Переопределяем/проксируем метод отправки AJAX запроса
  1887. */
  1888. XMLHttpRequest.prototype.send = async function (sourceData) {
  1889. if (this.uniqid in requestHistory) {
  1890. let tempData = null;
  1891. if (getClass(sourceData) == "ArrayBuffer") {
  1892. tempData = decoder.decode(sourceData);
  1893. } else {
  1894. tempData = sourceData;
  1895. }
  1896. requestHistory[this.uniqid].request = tempData;
  1897. let headers = requestHistory[this.uniqid].headers;
  1898. lastHeaders = Object.assign({}, headers);
  1899. /**
  1900. * Game loading event
  1901. *
  1902. * Событие загрузки игры
  1903. */
  1904. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  1905. isLoadGame = true;
  1906. await lib.load();
  1907. addControls();
  1908. addControlButtons();
  1909. addBottomUrls();
  1910.  
  1911. //if (isChecked('sendExpedition')) {
  1912. checkExpedition(); //экспедиции на авто при входе в игру
  1913. //}
  1914.  
  1915. getAutoGifts();
  1916.  
  1917. cheats.activateHacks();
  1918.  
  1919. justInfo();
  1920. if (isChecked('dailyQuests')) {
  1921. testDailyQuests();
  1922. }
  1923.  
  1924. if (isChecked('buyForGold')) {
  1925. buyInStoreForGold();
  1926. }
  1927. }
  1928. /**
  1929. * Outgoing request data processing
  1930. *
  1931. * Обработка данных исходящего запроса
  1932. */
  1933. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  1934. /**
  1935. * Handling incoming request data
  1936. *
  1937. * Обработка данных входящего запроса
  1938. */
  1939. const oldReady = this.onreadystatechange;
  1940. this.onreadystatechange = async function (e) {
  1941. if (this.errorRequest) {
  1942. return oldReady.apply(this, arguments);
  1943. }
  1944. if(this.readyState == 4 && this.status == 200) {
  1945. isTextResponse = this.responseType === "text" || this.responseType === "";
  1946. let response = isTextResponse ? this.responseText : this.response;
  1947. requestHistory[this.uniqid].response = response;
  1948. /**
  1949. * Replacing incoming request data
  1950. *
  1951. * Заменна данных входящего запроса
  1952. */
  1953. if (isTextResponse) {
  1954. await checkChangeResponse.call(this, response);
  1955. }
  1956. /**
  1957. * A function to run after the request is executed
  1958. *
  1959. * Функция запускаемая после выполения запроса
  1960. */
  1961. if (typeof this.onReadySuccess == 'function') {
  1962. setTimeout(this.onReadySuccess, 500);
  1963. }
  1964. /** Удаляем из истории запросов битвы с боссом */
  1965. if ('invasion_bossStart' in requestHistory[this.uniqid].calls) delete requestHistory[this.uniqid];
  1966. }
  1967. if (oldReady) {
  1968. return oldReady.apply(this, arguments);
  1969. }
  1970. }
  1971. }
  1972. if (this.errorRequest) {
  1973. const oldReady = this.onreadystatechange;
  1974. this.onreadystatechange = function () {
  1975. Object.defineProperty(this, 'status', {
  1976. writable: true
  1977. });
  1978. this.status = 200;
  1979. Object.defineProperty(this, 'readyState', {
  1980. writable: true
  1981. });
  1982. this.readyState = 4;
  1983. Object.defineProperty(this, 'responseText', {
  1984. writable: true
  1985. });
  1986. this.responseText = JSON.stringify({
  1987. "result": true
  1988. });
  1989. if (typeof this.onReadySuccess == 'function') {
  1990. setTimeout(this.onReadySuccess, 200);
  1991. }
  1992. return oldReady.apply(this, arguments);
  1993. }
  1994. this.onreadystatechange();
  1995. } else {
  1996. try {
  1997. return original.send.call(this, sourceData);
  1998. } catch(e) {
  1999. debugger;
  2000. }
  2001.  
  2002. }
  2003. };
  2004. /**
  2005. * Processing and substitution of outgoing data
  2006. *
  2007. * Обработка и подмена исходящих данных
  2008. */
  2009. async function checkChangeSend(sourceData, tempData) {
  2010. try {
  2011. /**
  2012. * A function that replaces battle data with incorrect ones to cancel combatя
  2013. *
  2014. * Функция заменяющая данные боя на неверные для отмены боя
  2015. */
  2016. const fixBattle = function (heroes) {
  2017. for (const ids in heroes) {
  2018. hero = heroes[ids];
  2019. hero.energy = random(1, 999);
  2020. if (hero.hp > 0) {
  2021. hero.hp = random(1, hero.hp);
  2022. }
  2023. }
  2024. }
  2025. /**
  2026. * Dialog window 2
  2027. *
  2028. * Диалоговое окно 2
  2029. */
  2030. const showMsg = async function (msg, ansF, ansS) {
  2031. if (typeof popup == 'object') {
  2032. return await popup.confirm(msg, [
  2033. {msg: ansF, result: false},
  2034. {msg: ansS, result: true},
  2035. ]);
  2036. } else {
  2037. return !confirm(`${msg}\n ${ansF} (${I18N('BTN_OK')})\n ${ansS} (${I18N('BTN_CANCEL')})`);
  2038. }
  2039. }
  2040. /**
  2041. * Dialog window 3
  2042. *
  2043. * Диалоговое окно 3
  2044. */
  2045. const showMsgs = async function (msg, ansF, ansS, ansT) {
  2046. return await popup.confirm(msg, [
  2047. {msg: ansF, result: 0},
  2048. {msg: ansS, result: 1},
  2049. {msg: ansT, result: 2},
  2050. ]);
  2051. }
  2052.  
  2053. let changeRequest = false;
  2054. testData = JSON.parse(tempData);
  2055. for (const call of testData.calls) {
  2056. if (!artifactChestOpen) {
  2057. requestHistory[this.uniqid].calls[call.name] = call.ident;
  2058. }
  2059. /**
  2060. * Cancellation of the battle in adventures, on VG and with minions of Asgard
  2061. * Отмена боя в приключениях, на ВГ и с прислужниками Асгарда
  2062. */
  2063. if ((call.name == 'adventure_endBattle' ||
  2064. call.name == 'adventureSolo_endBattle' ||
  2065. call.name == 'clanWarEndBattle' &&
  2066. isChecked('cancelBattle') ||
  2067. call.name == 'crossClanWar_endBattle' &&
  2068. isChecked('cancelBattle') ||
  2069. call.name == 'brawl_endBattle' ||
  2070. call.name == 'towerEndBattle' ||
  2071. call.name == 'invasion_bossEnd' ||
  2072. call.name == 'bossEndBattle' ||
  2073. call.name == 'clanRaid_endNodeBattle') &&
  2074. isCancalBattle) {
  2075. nameFuncEndBattle = call.name;
  2076. if (!call.args.result.win) {
  2077. let resultPopup = false;
  2078. if (call.name == 'adventure_endBattle' ||
  2079. call.name == 'invasion_bossEnd' ||
  2080. call.name == 'bossEndBattle' ||
  2081. call.name == 'adventureSolo_endBattle') {
  2082. resultPopup = await showMsgs(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2083. } else if (call.name == 'clanWarEndBattle' ||
  2084. call.name == 'crossClanWar_endBattle') {
  2085. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_AUTO_F5'));
  2086. } else {
  2087. resultPopup = await showMsg(I18N('MSG_HAVE_BEEN_DEFEATED'), I18N('BTN_OK'), I18N('BTN_CANCEL'));
  2088. }
  2089. if (resultPopup) {
  2090. if (call.name == 'invasion_bossEnd') {
  2091. this.errorRequest = true;
  2092. }
  2093. fixBattle(call.args.progress[0].attackers.heroes);
  2094. fixBattle(call.args.progress[0].defenders.heroes);
  2095. changeRequest = true;
  2096. if (resultPopup > 1) {
  2097. this.onReadySuccess = testAutoBattle;
  2098. // setTimeout(bossBattle, 1000);
  2099. }
  2100. }
  2101. } else if (call.args.result.stars < 3 && call.name == 'towerEndBattle') {
  2102. resultPopup = await showMsg(I18N('LOST_HEROES'), I18N('BTN_OK'), I18N('BTN_CANCEL'), I18N('BTN_AUTO'));
  2103. if (resultPopup) {
  2104. fixBattle(call.args.progress[0].attackers.heroes);
  2105. fixBattle(call.args.progress[0].defenders.heroes);
  2106. changeRequest = true;
  2107. if (resultPopup > 1) {
  2108. this.onReadySuccess = testAutoBattle;
  2109. }
  2110. }
  2111. }
  2112. // Потасовки
  2113. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_endBattle') {}
  2114. }
  2115. /**
  2116. * Save pack for Brawls
  2117. *
  2118. * Сохраняем пачку для потасовок
  2119. */
  2120. if (isChecked('autoBrawls') && !isBrawlsAutoStart && call.name == 'brawl_startBattle') {
  2121. console.log(JSON.stringify(call.args));
  2122. brawlsPack = call.args;
  2123. if (
  2124. await popup.confirm(
  2125. I18N('START_AUTO_BRAWLS'),
  2126. [
  2127. { msg: I18N('BTN_NO'), result: false },
  2128. { msg: I18N('BTN_YES'), result: true },
  2129. ],
  2130. [
  2131. {
  2132. name: 'isAuto',
  2133. label: I18N('BRAWL_AUTO_PACK'),
  2134. checked: false,
  2135. },
  2136. ]
  2137. )
  2138. ) {
  2139. isBrawlsAutoStart = true;
  2140. const isAuto = popup.getCheckBoxes().find((e) => e.name === 'isAuto');
  2141. this.errorRequest = true;
  2142. testBrawls(isAuto.checked);
  2143. }
  2144. }
  2145. /**
  2146. * Canceled fight in Asgard
  2147. * Отмена боя в Асгарде
  2148. */
  2149. if (call.name == 'clanRaid_endBossBattle' && isChecked('cancelBattle')) {
  2150. const bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  2151. let maxDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  2152. const lastDamage = maxDamage;
  2153. const resultPopup = await popup.confirm(
  2154. `${I18N('MSG_YOU_APPLIED')} ${lastDamage.toLocaleString()} ${I18N('MSG_DAMAGE')}.`,
  2155. [
  2156. { msg: I18N('BTN_OK'), result: false },
  2157. { msg: I18N('BTN_AUTO_F5'), result: 1 },
  2158. { msg: I18N('BTN_TRY_FIX_IT'), result: 2 },
  2159. ],
  2160. [
  2161. {
  2162. name: 'isStat',
  2163. label: I18N('CALC_STAT'),
  2164. checked: false,
  2165. },
  2166. ]
  2167. );
  2168. if (resultPopup) {
  2169. if (resultPopup == 2) {
  2170. setProgress(I18N('LETS_FIX'), false);
  2171. await new Promise((e) => setTimeout(e, 0));
  2172. const cloneBattle = structuredClone(lastBossBattle);
  2173. const endTime = cloneBattle.endTime - 1e4;
  2174. console.log('fixBossBattleStart');
  2175. const COUNT = 300;
  2176. let maxCount = 0;
  2177. let duration = 0;
  2178. let avgTime = 0;
  2179. for (let count = 1; count <= COUNT; count++) {
  2180. maxCount = count;
  2181. const start = Date.now();
  2182. const timer = randf(1.3, 10.3);
  2183. if ((endTime + avgTime) < start) {
  2184. break;
  2185. }
  2186. await new Promise((e) =>
  2187. setTimeout(() => {
  2188. const maxDmg = maxDamage.toLocaleString();
  2189. const avg = avgTime.toFixed(2);
  2190. const msg = `${I18N('LETS_FIX')} ${maxCount}/${COUNT}<br/>${maxDmg}<br/>${avg}ms`;
  2191. setProgress(msg, false);
  2192. e();
  2193. }, 0)
  2194. );
  2195. try {
  2196. resultBattle = await Calc(cloneBattle);
  2197. } catch (e) {
  2198. continue;
  2199. }
  2200. duration += Date.now() - start;
  2201. avgTime = duration / count;
  2202. const extraDmg = resultBattle.progress[0].defenders.heroes[1].extra;
  2203. const bossDamage = extraDmg.damageTaken + extraDmg.damageTakenNextLevel;
  2204. console.log(count + '\t' + timer.toFixed(2) + '\t' + bossDamage.toLocaleString());
  2205. if (bossDamage > maxDamage) {
  2206. maxDamage = bossDamage;
  2207. call.args.result = resultBattle.result;
  2208. call.args.progress = resultBattle.progress;
  2209. }
  2210. cloneBattle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', 0, timer] } }];
  2211. }
  2212. let msgResult = I18N('DAMAGE_NO_FIXED', {
  2213. lastDamage: lastDamage.toLocaleString()
  2214. });
  2215. if (maxDamage > lastDamage) {
  2216. msgResult = I18N('DAMAGE_FIXED', {
  2217. lastDamage: lastDamage.toLocaleString(),
  2218. maxDamage: maxDamage.toLocaleString(),
  2219. });
  2220. }
  2221. console.log(lastDamage, '>' ,maxDamage);
  2222. setProgress(
  2223. msgResult + '<br/>' +
  2224. I18N('COUNT_FIXED', {
  2225. count: maxCount,
  2226. }),
  2227. false,
  2228. hideProgress
  2229. );
  2230. } else {
  2231. fixBattle(call.args.progress[0].attackers.heroes);
  2232. fixBattle(call.args.progress[0].defenders.heroes);
  2233. }
  2234. changeRequest = true;
  2235. }
  2236. const isStat = popup.getCheckBoxes().find((e) => e.name === 'isStat');
  2237. if (isStat.checked) {
  2238. this.onReadySuccess = testBossBattle;
  2239. }
  2240. }
  2241. /**
  2242. * Save the Asgard Boss Attack Pack
  2243. * Сохраняем пачку для атаки босса Асгарда
  2244. */
  2245. if (call.name == 'clanRaid_startBossBattle') {
  2246. console.log(JSON.stringify(call.args));
  2247. }
  2248. /**
  2249. * Saving the request to start the last battle
  2250. * Сохранение запроса начала последнего боя
  2251. */
  2252. if (call.name == 'clanWarAttack' ||
  2253. call.name == 'crossClanWar_startBattle' ||
  2254. call.name == 'adventure_turnStartBattle' ||
  2255. call.name == 'bossAttack' ||
  2256. call.name == 'invasion_bossStart' ||
  2257. call.name == 'towerStartBattle') {
  2258. nameFuncStartBattle = call.name;
  2259. lastBattleArg = call.args;
  2260.  
  2261. if (call.name == 'invasion_bossStart') {
  2262. const timePassed = Date.now() - lastBossBattleStart;
  2263. if (timePassed < invasionTimer) {
  2264. await new Promise((e) => setTimeout(e, invasionTimer - timePassed));
  2265. }
  2266. invasionTimer -= 1;
  2267. }
  2268. lastBossBattleStart = Date.now();
  2269. }
  2270. if (call.name == 'invasion_bossEnd') {
  2271. const lastBattle = lastBattleInfo;
  2272. if (lastBattle && call.args.result.win) {
  2273. lastBattle.progress = call.args.progress;
  2274. const result = await Calc(lastBattle);
  2275. let timer = getTimer(result.battleTime, 1) + addBattleTimer;
  2276. const period = Math.ceil((Date.now() - lastBossBattleStart) / 1000);
  2277. console.log(timer, period);
  2278. if (period < timer) {
  2279. timer = timer - period;
  2280. await countdownTimer(timer);
  2281. }
  2282. }
  2283. }
  2284. /**
  2285. * Disable spending divination cards
  2286. * Отключить трату карт предсказаний
  2287. */
  2288. if (call.name == 'dungeonEndBattle') {
  2289. if (call.args.isRaid) {
  2290. if (countPredictionCard <= 0) {
  2291. delete call.args.isRaid;
  2292. changeRequest = true;
  2293. } else if (countPredictionCard > 0) {
  2294. countPredictionCard--;
  2295. }
  2296. }
  2297. console.log(`Cards: ${countPredictionCard}`);
  2298. /**
  2299. * Fix endless cards
  2300. * Исправление бесконечных карт
  2301. */
  2302. const lastBattle = lastDungeonBattleData;
  2303. if (lastBattle && !call.args.isRaid) {
  2304. if (changeRequest) {
  2305. lastBattle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2306. } else {
  2307. lastBattle.progress = call.args.progress;
  2308. }
  2309. const result = await Calc(lastBattle);
  2310.  
  2311. if (changeRequest) {
  2312. call.args.progress = result.progress;
  2313. call.args.result = result.result;
  2314. }
  2315.  
  2316. let timer = result.battleTimer + addBattleTimer;
  2317. const period = Math.ceil((Date.now() - lastDungeonBattleStart) / 1000);
  2318. console.log(timer, period);
  2319. if (period < timer) {
  2320. timer = timer - period;
  2321. await countdownTimer(timer);
  2322. }
  2323. }
  2324. }
  2325. /**
  2326. * Quiz Answer
  2327. * Ответ на викторину
  2328. */
  2329. if (call.name == 'quizAnswer') {
  2330. /**
  2331. * Automatically changes the answer to the correct one if there is one.
  2332. * Автоматически меняет ответ на правильный если он есть
  2333. */
  2334. if (lastAnswer && isChecked('getAnswer')) {
  2335. call.args.answerId = lastAnswer;
  2336. lastAnswer = null;
  2337. changeRequest = true;
  2338. }
  2339. }
  2340. /**
  2341. * Present
  2342. * Подарки
  2343. */
  2344. if (call.name == 'freebieCheck') {
  2345. freebieCheckInfo = call;
  2346. }
  2347. /** missionTimer */
  2348. if (call.name == 'missionEnd' && missionBattle) {
  2349. let startTimer = false;
  2350. if (!call.args.result.win) {
  2351. startTimer = await popup.confirm(I18N('DEFEAT_TURN_TIMER'), [
  2352. { msg: I18N('BTN_NO'), result: false },
  2353. { msg: I18N('BTN_YES'), result: true },
  2354. ]);
  2355. }
  2356. if (call.args.result.win || startTimer) {
  2357. missionBattle.progress = call.args.progress;
  2358. missionBattle.result = call.args.result;
  2359. const result = await Calc(missionBattle);
  2360. let timer = result.battleTimer + addBattleTimer;
  2361. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  2362. if (period < timer) {
  2363. timer = timer - period;
  2364. await countdownTimer(timer);
  2365. }
  2366. missionBattle = null;
  2367. } else {
  2368. this.errorRequest = true;
  2369. }
  2370. }
  2371. /**
  2372. * Getting mission data for auto-repeat
  2373. * Получение данных миссии для автоповтора
  2374. */
  2375. if (isChecked('repeatMission') &&
  2376. call.name == 'missionEnd') {
  2377. let missionInfo = {
  2378. id: call.args.id,
  2379. result: call.args.result,
  2380. heroes: call.args.progress[0].attackers.heroes,
  2381. count: 0,
  2382. }
  2383. setTimeout(async () => {
  2384. if (!isSendsMission && await popup.confirm(I18N('MSG_REPEAT_MISSION'), [
  2385. { msg: I18N('BTN_REPEAT'), result: true},
  2386. { msg: I18N('BTN_NO'), result: false},
  2387. ])) {
  2388. isStopSendMission = false;
  2389. isSendsMission = true;
  2390. sendsMission(missionInfo);
  2391. }
  2392. }, 0);
  2393. }
  2394. /**
  2395. * Getting mission data
  2396. * Получение данных миссии
  2397. * missionTimer
  2398. */
  2399. if (call.name == 'missionStart') {
  2400. lastMissionStart = call.args;
  2401. lastMissionBattleStart = Date.now();
  2402. }
  2403.  
  2404. /**
  2405. * Specify the quantity for Titan Orbs and Pet Eggs
  2406. * Указать количество для сфер титанов и яиц петов
  2407. */
  2408. if (isChecked('countControl') &&
  2409. (call.name == 'pet_chestOpen' ||
  2410. call.name == 'titanUseSummonCircle') &&
  2411. call.args.amount > 1) {
  2412. const startAmount = call.args.amount;
  2413. call.args.amount = 1;
  2414. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2415. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2416. ]);
  2417. if (result) {
  2418. const item = call.name == 'pet_chestOpen' ? { id: 90, type: 'consumable' } : { id: 13, type: 'coin' };
  2419. cheats.updateInventory({
  2420. [item.type]: {
  2421. [item.id]: -(result - startAmount),
  2422. },
  2423. });
  2424. call.args.amount = result;
  2425. changeRequest = true;
  2426. }
  2427. }
  2428. /**
  2429. * Specify the amount for keys and spheres of titan artifacts
  2430. * Указать колличество для ключей и сфер артефактов титанов
  2431. */
  2432. if (isChecked('countControl') &&
  2433. (call.name == 'artifactChestOpen' ||
  2434. call.name == 'titanArtifactChestOpen') &&
  2435. call.args.amount > 1 &&
  2436. call.args.free &&
  2437. !changeRequest) {
  2438. artifactChestOpenCallName = call.name;
  2439. const startAmount = call.args.amount;
  2440. let result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2441. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount },
  2442. ]);
  2443. if (result) {
  2444. const openChests = result;
  2445. let sphere = result < 10 ? 1 : 10;
  2446.  
  2447. call.args.amount = sphere;
  2448. for (let count = openChests - sphere; count > 0; count -= sphere) {
  2449. if (count < 10) sphere = 1;
  2450. const ident = artifactChestOpenCallName + "_" + count;
  2451. testData.calls.push({
  2452. name: artifactChestOpenCallName,
  2453. args: {
  2454. amount: sphere,
  2455. free: true,
  2456. },
  2457. ident: ident
  2458. });
  2459. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  2460. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  2461. }
  2462. requestHistory[this.uniqid].calls[call.name].push(ident);
  2463. }
  2464. const consumableId = call.name == 'artifactChestOpen' ? 45 : 55;
  2465. cheats.updateInventory({
  2466. consumable: {
  2467. [consumableId]: -(openChests - startAmount),
  2468. },
  2469. });
  2470.  
  2471. artifactChestOpen = true;
  2472. changeRequest = true;
  2473. }
  2474. }
  2475. if (call.name == 'consumableUseLootBox') {
  2476. lastRussianDollId = call.args.libId;
  2477. /**
  2478. * Specify quantity for gold caskets
  2479. * Указать количество для золотых шкатулок
  2480. */
  2481. if (isChecked('countControl') &&
  2482. call.args.libId == 148 &&
  2483. call.args.amount > 1) {
  2484. const result = await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2485. { msg: I18N('BTN_OPEN'), isInput: true, default: call.args.amount},
  2486. ]);
  2487. call.args.amount = result;
  2488. changeRequest = true;
  2489. }
  2490. if (isChecked('countControl') && call.args.libId >= 362 && call.args.libId <= 389) {
  2491. this.massOpen = call.args.libId;
  2492. }
  2493. }
  2494. /**
  2495. * Changing the maximum number of raids in the campaign
  2496. * Изменение максимального количества рейдов в кампании
  2497. */
  2498. // if (call.name == 'missionRaid') {
  2499. // if (isChecked('countControl') && call.args.times > 1) {
  2500. // const result = +(await popup.confirm(I18N('MSG_SPECIFY_QUANT'), [
  2501. // { msg: I18N('BTN_RUN'), isInput: true, default: call.args.times },
  2502. // ]));
  2503. // call.args.times = result > call.args.times ? call.args.times : result;
  2504. // changeRequest = true;
  2505. // }
  2506. // }
  2507. }
  2508.  
  2509. let headers = requestHistory[this.uniqid].headers;
  2510. if (changeRequest) {
  2511. sourceData = JSON.stringify(testData);
  2512. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  2513. }
  2514.  
  2515. let signature = headers['X-Auth-Signature'];
  2516. if (signature) {
  2517. original.setRequestHeader.call(this, 'X-Auth-Signature', signature);
  2518. }
  2519. } catch (err) {
  2520. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  2521. }
  2522. return sourceData;
  2523. }
  2524. /**
  2525. * Processing and substitution of incoming data
  2526. *
  2527. * Обработка и подмена входящих данных
  2528. */
  2529. async function checkChangeResponse(response) {
  2530. try {
  2531. isChange = false;
  2532. let nowTime = Math.round(Date.now() / 1000);
  2533. callsIdent = requestHistory[this.uniqid].calls;
  2534. respond = JSON.parse(response);
  2535. /**
  2536. * If the request returned an error removes the error (removes synchronization errors)
  2537. * Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации)
  2538. */
  2539. if (respond.error) {
  2540. isChange = true;
  2541. console.error(respond.error);
  2542. if (isChecked('showErrors')) {
  2543. popup.confirm(I18N('ERROR_MSG', {
  2544. name: respond.error.name,
  2545. description: respond.error.description,
  2546. }));
  2547. }
  2548. delete respond.error;
  2549. respond.results = [];
  2550. }
  2551. let mainReward = null;
  2552. const allReward = {};
  2553. let countTypeReward = 0;
  2554. let readQuestInfo = false;
  2555. for (const call of respond.results) {
  2556. /**
  2557. * Obtaining initial data for completing quests
  2558. * Получение исходных данных для выполнения квестов
  2559. */
  2560. if (readQuestInfo) {
  2561. questsInfo[call.ident] = call.result.response;
  2562. }
  2563. /**
  2564. * Getting a user ID
  2565. * Получение идетификатора пользователя
  2566. */
  2567. if (call.ident == callsIdent['registration']) {
  2568. userId = call.result.response.userId;
  2569. if (localStorage['userId'] != userId) {
  2570. localStorage['newGiftSendIds'] = '';
  2571. localStorage['userId'] = userId;
  2572. }
  2573. await openOrMigrateDatabase(userId);
  2574. readQuestInfo = true;
  2575. }
  2576. /**
  2577. * Hiding donation offers 1
  2578. * Скрываем предложения доната 1
  2579. */
  2580. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  2581. const billings = call.result.response?.billings;
  2582. const bundle = call.result.response?.bundle;
  2583. if (billings && bundle) {
  2584. call.result.response.billings = [];
  2585. call.result.response.bundle = [];
  2586. isChange = true;
  2587. }
  2588. }
  2589. /**
  2590. * Hiding donation offers 2
  2591. * Скрываем предложения доната 2
  2592. */
  2593. if (getSaveVal('noOfferDonat') &&
  2594. (call.ident == callsIdent['offerGetAll'] ||
  2595. call.ident == callsIdent['specialOffer_getAll'])) {
  2596. let offers = call.result.response;
  2597. if (offers) {
  2598. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type) || ['idleResource'].includes(e.offerType));
  2599. isChange = true;
  2600. }
  2601. }
  2602. /**
  2603. * Hiding donation offers 3
  2604. * Скрываем предложения доната 3
  2605. */
  2606. if (getSaveVal('noOfferDonat') && call.result?.bundleUpdate) {
  2607. delete call.result.bundleUpdate;
  2608. isChange = true;
  2609. }
  2610. /**
  2611. * Copies a quiz question to the clipboard
  2612. * Копирует вопрос викторины в буфер обмена и получает на него ответ если есть
  2613. */
  2614. if (call.ident == callsIdent['quizGetNewQuestion']) {
  2615. let quest = call.result.response;
  2616. console.log(quest.question);
  2617. copyText(quest.question);
  2618. setProgress(I18N('QUESTION_COPY'), true);
  2619. quest.lang = null;
  2620. if (typeof NXFlashVars !== 'undefined') {
  2621. quest.lang = NXFlashVars.interface_lang;
  2622. }
  2623. lastQuestion = quest;
  2624. if (isChecked('getAnswer')) {
  2625. const answer = await getAnswer(lastQuestion);
  2626. let showText = '';
  2627. if (answer) {
  2628. lastAnswer = answer;
  2629. console.log(answer);
  2630. showText = `${I18N('ANSWER_KNOWN')}: ${answer}`;
  2631. } else {
  2632. showText = I18N('ANSWER_NOT_KNOWN');
  2633. }
  2634.  
  2635. try {
  2636. const hint = hintQuest(quest);
  2637. if (hint) {
  2638. showText += I18N('HINT') + hint;
  2639. }
  2640. } catch(e) {}
  2641.  
  2642. setProgress(showText, true);
  2643. }
  2644. }
  2645. /**
  2646. * Submits a question with an answer to the database
  2647. * Отправляет вопрос с ответом в базу данных
  2648. */
  2649. if (call.ident == callsIdent['quizAnswer']) {
  2650. const answer = call.result.response;
  2651. if (lastQuestion) {
  2652. const answerInfo = {
  2653. answer,
  2654. question: lastQuestion,
  2655. lang: null,
  2656. }
  2657. if (typeof NXFlashVars !== 'undefined') {
  2658. answerInfo.lang = NXFlashVars.interface_lang;
  2659. }
  2660. lastQuestion = null;
  2661. setTimeout(sendAnswerInfo, 0, answerInfo);
  2662. }
  2663. }
  2664. /**
  2665. * Get user data
  2666. * Получить даныне пользователя
  2667. */
  2668. if (call.ident == callsIdent['userGetInfo']) {
  2669. let user = call.result.response;
  2670. document.title = user.name;
  2671. userInfo = Object.assign({}, user);
  2672. delete userInfo.refillable;
  2673. if (!questsInfo['userGetInfo']) {
  2674. questsInfo['userGetInfo'] = user;
  2675. }
  2676. }
  2677. /**
  2678. * Start of the battle for recalculation
  2679. * Начало боя для прерасчета
  2680. */
  2681. if (call.ident == callsIdent['clanWarAttack'] ||
  2682. call.ident == callsIdent['crossClanWar_startBattle'] ||
  2683. call.ident == callsIdent['bossAttack'] ||
  2684. call.ident == callsIdent['battleGetReplay'] ||
  2685. call.ident == callsIdent['brawl_startBattle'] ||
  2686. call.ident == callsIdent['adventureSolo_turnStartBattle'] ||
  2687. call.ident == callsIdent['invasion_bossStart'] ||
  2688. call.ident == callsIdent['towerStartBattle'] ||
  2689. call.ident == callsIdent['adventure_turnStartBattle']) {
  2690. let battle = call.result.response.battle || call.result.response.replay;
  2691. if (call.ident == callsIdent['brawl_startBattle'] ||
  2692. call.ident == callsIdent['bossAttack'] ||
  2693. call.ident == callsIdent['towerStartBattle'] ||
  2694. call.ident == callsIdent['invasion_bossStart']) {
  2695. battle = call.result.response;
  2696. }
  2697. lastBattleInfo = battle;
  2698. if (!isChecked('preCalcBattle')) {
  2699. continue;
  2700. }
  2701. setProgress(I18N('BEING_RECALC'));
  2702. let battleDuration = 120;
  2703. try {
  2704. const typeBattle = getBattleType(battle.type);
  2705. battleDuration = +lib.data.battleConfig[typeBattle.split('_')[1]].config.battleDuration;
  2706. } catch (e) { }
  2707. //console.log(battle.type);
  2708. function getBattleInfo(battle, isRandSeed) {
  2709. return new Promise(function (resolve) {
  2710. if (isRandSeed) {
  2711. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2712. }
  2713. BattleCalc(battle, getBattleType(battle.type), e => resolve(e));
  2714. });
  2715. }
  2716. let actions = [getBattleInfo(battle, false)]
  2717. const countTestBattle = getInput('countTestBattle');
  2718. if (call.ident == callsIdent['battleGetReplay']) {
  2719. battle.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  2720. }
  2721. for (let i = 0; i < countTestBattle; i++) {
  2722. actions.push(getBattleInfo(battle, true));
  2723. }
  2724. Promise.all(actions)
  2725. .then(e => {
  2726. e = e.map(n => ({win: n.result.win, time: n.battleTime}));
  2727. let firstBattle = e.shift();
  2728. const timer = Math.floor(battleDuration - firstBattle.time);
  2729. const min = ('00' + Math.floor(timer / 60)).slice(-2);
  2730. const sec = ('00' + Math.floor(timer - min * 60)).slice(-2);
  2731. const countWin = e.reduce((w, s) => w + s.win, 0);
  2732. 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)
  2733. });
  2734. }
  2735. //тест сохранки
  2736. /** Запоминаем команды в реплее*/
  2737. if (call.ident == callsIdent['battleGetReplay']) {
  2738. let battle = call.result.response.replay;
  2739. repleyBattle.attackers = battle.attackers;
  2740. repleyBattle.defenders = battle.defenders[0];
  2741. repleyBattle.effects = battle.effects.defenders;
  2742. repleyBattle.state = battle.progress[0].defenders.heroes;
  2743. repleyBattle.seed = battle.seed;
  2744. }
  2745. /** Нападение в турнире*/
  2746. if (call.ident == callsIdent['titanArenaStartBattle']) {
  2747. let bestBattle = getInput('countBattle');
  2748. let unrandom = getInput('needResource');
  2749. let maxPower = getInput('needResource2');
  2750. if (bestBattle * unrandom * maxPower == 0) {
  2751. let battle = call.result.response.battle;
  2752. if (bestBattle == 0) {
  2753. battle.progress = bestLordBattle[battle.typeId]?.progress;
  2754. }
  2755. if (unrandom == 0 && !!repleyBattle.seed) {
  2756. battle.seed = repleyBattle.seed;
  2757. }
  2758. if (maxPower == 0) {
  2759. battle.attackers = getTitansPack(Object.keys(battle.attackers));
  2760. }
  2761. isChange = true;
  2762. }
  2763. }
  2764. /** Тест боев с усилениями команд защиты*/
  2765. if (call.ident == callsIdent['chatAcceptChallenge']) {
  2766. let battle = call.result.response.battle;
  2767. addBuff(battle);
  2768. let testType = getInput('countBattle');
  2769. if (testType.slice(0, 1) == "-") {
  2770. testType = parseInt(testType.slice(1), 10);
  2771. switch (testType) {
  2772. case 1:
  2773. battle.defenders[0] = repleyBattle.defenders;
  2774. break; //наша атака против защиты из реплея
  2775. case 2:
  2776. battle.defenders[0] = repleyBattle.attackers;
  2777. break; //наша атака против атаки из реплея
  2778. case 3:
  2779. battle.attackers = repleyBattle.attackers;
  2780. break; //атака из реплея против защиты в чате
  2781. case 4:
  2782. battle.attackers = repleyBattle.defenders;
  2783. break; //защита из реплея против защиты в чате
  2784. case 5:
  2785. battle.attackers = repleyBattle.attackers;
  2786. battle.defenders[0] = repleyBattle.defenders;
  2787. break; //атака из реплея против защиты из реплея
  2788. case 6:
  2789. battle.attackers = repleyBattle.defenders;
  2790. battle.defenders[0] = repleyBattle.attackers;
  2791. break; //защита из реплея против атаки из реплея
  2792. case 7:
  2793. battle.attackers = repleyBattle.attackers;
  2794. battle.defenders[0] = repleyBattle.attackers;
  2795. break; //атака из реплея против атаки из реплея
  2796. case 8:
  2797. battle.attackers = repleyBattle.defenders;
  2798. battle.defenders[0] = repleyBattle.defenders;
  2799. break; //защита из реплея против защиты из реплея
  2800. case 15:
  2801. battle.attackers = repleyBattle.defenders;
  2802. battle.defenders[0] = repleyBattle.defenders;
  2803. break; //защита из реплея против защиты из реплея
  2804. }
  2805. }
  2806.  
  2807. isChange = true;
  2808. }
  2809. /** Тест боев с усилениями команд защиты тренировках*/
  2810. if (call.ident == callsIdent['demoBattles_startBattle']) {
  2811. let battle = call.result.response.battle;
  2812. addBuff(battle);
  2813. let testType = getInput('countBattle');
  2814. if (testType.slice(0, 1) == "-") {
  2815. testType = parseInt(testType.slice(1), 10);
  2816. switch (testType) {
  2817. case 1:
  2818. battle.defenders[0] = repleyBattle.defenders;
  2819. break; //наша атака против защиты из реплея
  2820. case 2:
  2821. battle.defenders[0] = repleyBattle.attackers;
  2822. break; //наша атака против атаки из реплея
  2823. case 3:
  2824. battle.attackers = repleyBattle.attackers;
  2825. break; //атака из реплея против защиты в чате
  2826. case 4:
  2827. battle.attackers = repleyBattle.defenders;
  2828. break; //защита из реплея против защиты в чате
  2829. case 5:
  2830. battle.attackers = repleyBattle.attackers;
  2831. battle.defenders[0] = repleyBattle.defenders;
  2832. break; //атака из реплея против защиты из реплея
  2833. case 6:
  2834. battle.attackers = repleyBattle.defenders;
  2835. battle.defenders[0] = repleyBattle.attackers;
  2836. break; //защита из реплея против атаки из реплея
  2837. case 7:
  2838. battle.attackers = repleyBattle.attackers;
  2839. battle.defenders[0] = repleyBattle.attackers;
  2840. break; //атака из реплея против атаки из реплея
  2841. case 8:
  2842. battle.attackers = repleyBattle.defenders;
  2843. battle.defenders[0] = repleyBattle.defenders;
  2844. break; //защита из реплея против защиты из реплея
  2845. }
  2846. }
  2847.  
  2848. isChange = true;
  2849. }
  2850. //тест сохранки
  2851. /**
  2852. * Start of the Asgard boss fight
  2853. * Начало боя с боссом Асгарда
  2854. */
  2855. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  2856. lastBossBattle = call.result.response.battle;
  2857. lastBossBattle.endTime = Date.now() + 160 * 1000;
  2858. if (isChecked('preCalcBattle')) {
  2859. const result = await Calc(lastBossBattle).then(e => e.progress[0].defenders.heroes[1].extra);
  2860. const bossDamage = result.damageTaken + result.damageTakenNextLevel;
  2861. setProgress(I18N('BOSS_DAMAGE') + bossDamage.toLocaleString(), false, hideProgress);
  2862. }
  2863. }
  2864. /**
  2865. * Cancel tutorial
  2866. * Отмена туториала
  2867. */
  2868. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  2869. let chains = call.result.response.chains;
  2870. for (let n in chains) {
  2871. chains[n] = 9999;
  2872. }
  2873. isChange = true;
  2874. }
  2875. /**
  2876. * Opening keys and spheres of titan artifacts
  2877. * Открытие ключей и сфер артефактов титанов
  2878. */
  2879. if (artifactChestOpen &&
  2880. (call.ident == callsIdent[artifactChestOpenCallName] ||
  2881. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  2882. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  2883.  
  2884. reward.forEach(e => {
  2885. for (let f in e) {
  2886. if (!allReward[f]) {
  2887. allReward[f] = {};
  2888. }
  2889. for (let o in e[f]) {
  2890. if (!allReward[f][o]) {
  2891. allReward[f][o] = e[f][o];
  2892. countTypeReward++;
  2893. } else {
  2894. allReward[f][o] += e[f][o];
  2895. }
  2896. }
  2897. }
  2898. });
  2899.  
  2900. if (!call.ident.includes(artifactChestOpenCallName)) {
  2901. mainReward = call.result.response;
  2902. }
  2903. }
  2904.  
  2905. if (countTypeReward > 20) {
  2906. correctShowOpenArtifact = 3;
  2907. } else {
  2908. correctShowOpenArtifact = 0;
  2909. }
  2910.  
  2911. /**
  2912. * Sum the result of opening Pet Eggs
  2913. * Суммирование результата открытия яиц питомцев
  2914. */
  2915. if (isChecked('countControl') && call.ident == callsIdent['pet_chestOpen']) {
  2916. const rewards = call.result.response.rewards;
  2917. if (rewards.length > 10) {
  2918. /**
  2919. * Removing pet cards
  2920. * Убираем карточки петов
  2921. */
  2922. for (const reward of rewards) {
  2923. if (reward.petCard) {
  2924. delete reward.petCard;
  2925. }
  2926. }
  2927. }
  2928. rewards.forEach(e => {
  2929. for (let f in e) {
  2930. if (!allReward[f]) {
  2931. allReward[f] = {};
  2932. }
  2933. for (let o in e[f]) {
  2934. if (!allReward[f][o]) {
  2935. allReward[f][o] = e[f][o];
  2936. } else {
  2937. allReward[f][o] += e[f][o];
  2938. }
  2939. }
  2940. }
  2941. });
  2942. call.result.response.rewards = [allReward];
  2943. isChange = true;
  2944. }
  2945. /**
  2946. * Removing titan cards
  2947. * Убираем карточки титанов
  2948. */
  2949. if (call.ident == callsIdent['titanUseSummonCircle']) {
  2950. if (call.result.response.rewards.length > 10) {
  2951. for (const reward of call.result.response.rewards) {
  2952. if (reward.titanCard) {
  2953. delete reward.titanCard;
  2954. }
  2955. }
  2956. isChange = true;
  2957. }
  2958. }
  2959. /**
  2960. * Auto-repeat opening matryoshkas
  2961. * АвтоПовтор открытия матрешек
  2962. */
  2963. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  2964. let lootBox = call.result.response;
  2965. let newCount = 0;
  2966. for (let n of lootBox) {
  2967. if (n?.consumable && n.consumable[lastRussianDollId]) {
  2968. newCount += n.consumable[lastRussianDollId]
  2969. }
  2970. }
  2971. if (
  2972. newCount && (await popup.confirm(`${I18N('BTN_OPEN')} ${newCount} ${I18N('OPEN_DOLLS')}?`, [
  2973. { msg: I18N('BTN_OPEN'), result: true },
  2974. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2975. ]))
  2976. ) {
  2977. const recursionResult = await openRussianDolls(lastRussianDollId, newCount);
  2978. lootBox = [...lootBox, ...recursionResult];
  2979. }
  2980.  
  2981. if (this.massOpen) {
  2982. if (
  2983. await popup.confirm(I18N('OPEN_ALL_EQUIP_BOXES'), [
  2984. { msg: I18N('BTN_OPEN'), result: true },
  2985. { msg: I18N('BTN_NO'), result: false, isClose: true },
  2986. ])
  2987. ) {
  2988. const consumable = await Send({ calls: [{ name: 'inventoryGet', args: {}, ident: 'inventoryGet' }] }).then((e) =>
  2989. Object.entries(e.results[0].result.response.consumable)
  2990. );
  2991. const calls = [];
  2992. const deleteItems = {};
  2993. for (const [libId, amount] of consumable) {
  2994. if (libId != this.massOpen && libId >= 362 && libId <= 389) {
  2995. calls.push({
  2996. name: 'consumableUseLootBox',
  2997. args: { libId, amount },
  2998. ident: 'consumableUseLootBox_' + libId,
  2999. });
  3000. deleteItems[libId] = -amount;
  3001. }
  3002. }
  3003. const result = await Send({ calls }).then((e) => e.results.map((r) => r.result.response).flat());
  3004. lootBox = [...lootBox, ...result];
  3005. this.onReadySuccess = () => {
  3006. cheats.updateInventory({ consumable: deleteItems });
  3007. cheats.refreshInventory();
  3008. };
  3009. }
  3010. }
  3011.  
  3012. /** Объединение результата лутбоксов */
  3013. const allLootBox = {};
  3014. lootBox.forEach(e => {
  3015. for (let f in e) {
  3016. if (!allLootBox[f]) {
  3017. if (typeof e[f] == 'object') {
  3018. allLootBox[f] = {};
  3019. } else {
  3020. allLootBox[f] = 0;
  3021. }
  3022. }
  3023. if (typeof e[f] == 'object') {
  3024. for (let o in e[f]) {
  3025. if (newCount && o == lastRussianDollId) {
  3026. continue;
  3027. }
  3028. if (!allLootBox[f][o]) {
  3029. allLootBox[f][o] = e[f][o];
  3030. } else {
  3031. allLootBox[f][o] += e[f][o];
  3032. }
  3033. }
  3034. } else {
  3035. allLootBox[f] += e[f];
  3036. }
  3037. }
  3038. });
  3039. /** Разбитие результата */
  3040. const output = [];
  3041. const maxCount = 5;
  3042. let currentObj = {};
  3043. let count = 0;
  3044. for (let f in allLootBox) {
  3045. if (!currentObj[f]) {
  3046. if (typeof allLootBox[f] == 'object') {
  3047. for (let o in allLootBox[f]) {
  3048. currentObj[f] ||= {}
  3049. if (!currentObj[f][o]) {
  3050. currentObj[f][o] = allLootBox[f][o];
  3051. count++;
  3052. if (count === maxCount) {
  3053. output.push(currentObj);
  3054. currentObj = {};
  3055. count = 0;
  3056. }
  3057. }
  3058. }
  3059. } else {
  3060. currentObj[f] = allLootBox[f];
  3061. count++;
  3062. if (count === maxCount) {
  3063. output.push(currentObj);
  3064. currentObj = {};
  3065. count = 0;
  3066. }
  3067. }
  3068. }
  3069. }
  3070. if (count > 0) {
  3071. output.push(currentObj);
  3072. }
  3073.  
  3074. console.log(output);
  3075. call.result.response = output;
  3076. isChange = true;
  3077. }
  3078. /**
  3079. * Dungeon recalculation (fix endless cards)
  3080. * Прерасчет подземки (исправление бесконечных карт)
  3081. */
  3082. if (call.ident == callsIdent['dungeonStartBattle']) {
  3083. lastDungeonBattleData = call.result.response;
  3084. lastDungeonBattleStart = Date.now();
  3085. }
  3086. /**
  3087. * Getting the number of prediction cards
  3088. * Получение количества карт предсказаний
  3089. */
  3090. if (call.ident == callsIdent['inventoryGet']) {
  3091. countPredictionCard = call.result.response.consumable[81] || 0;
  3092. }
  3093. /**
  3094. * Getting subscription status
  3095. * Получение состояния подписки
  3096. */
  3097. if (call.ident == callsIdent['subscriptionGetInfo']) {
  3098. const subscription = call.result.response.subscription;
  3099. if (subscription) {
  3100. subEndTime = subscription.endTime * 1000;
  3101. }
  3102. }
  3103. /**
  3104. * Getting prediction cards
  3105. * Получение карт предсказаний
  3106. */
  3107. if (call.ident == callsIdent['questFarm']) {
  3108. const consumable = call.result.response?.consumable;
  3109. if (consumable && consumable[81]) {
  3110. countPredictionCard += consumable[81];
  3111. console.log(`Cards: ${countPredictionCard}`);
  3112. }
  3113. }
  3114. /**
  3115. * Hiding extra servers
  3116. * Скрытие лишних серверов
  3117. */
  3118. if (call.ident == callsIdent['serverGetAll'] && isChecked('hideServers')) {
  3119. let servers = call.result.response.users.map(s => s.serverId)
  3120. call.result.response.servers = call.result.response.servers.filter(s => servers.includes(s.id));
  3121. isChange = true;
  3122. }
  3123. /**
  3124. * Displays player positions in the adventure
  3125. * Отображает позиции игроков в приключении
  3126. */
  3127. if (call.ident == callsIdent['adventure_getLobbyInfo']) {
  3128. const users = Object.values(call.result.response.users);
  3129. const mapIdent = call.result.response.mapIdent;
  3130. const adventureId = call.result.response.adventureId;
  3131. const maps = {
  3132. adv_strongford_3pl_hell: 9,
  3133. adv_valley_3pl_hell: 10,
  3134. adv_ghirwil_3pl_hell: 11,
  3135. adv_angels_3pl_hell: 12,
  3136. }
  3137. let msg = I18N('MAP') + (mapIdent in maps ? maps[mapIdent] : adventureId);
  3138. msg += '<br>' + I18N('PLAYER_POS');
  3139. for (const user of users) {
  3140. msg += `<br>${user.user.name} - ${user.currentNode}`;
  3141. }
  3142. setProgress(msg, false, hideProgress);
  3143. }
  3144. /**
  3145. * Automatic launch of a raid at the end of the adventure
  3146. * Автоматический запуск рейда при окончании приключения
  3147. */
  3148. if (call.ident == callsIdent['adventure_end']) {
  3149. autoRaidAdventure()
  3150. }
  3151. /** Удаление лавки редкостей */
  3152. if (call.ident == callsIdent['missionRaid']) {
  3153. if (call.result?.heroesMerchant) {
  3154. delete call.result.heroesMerchant;
  3155. isChange = true;
  3156. }
  3157. }
  3158. /** missionTimer */
  3159. if (call.ident == callsIdent['missionStart']) {
  3160. missionBattle = call.result.response;
  3161. }
  3162. /** Награды турнира стихий */
  3163. if (call.ident == callsIdent['hallOfFameGetTrophies']) {
  3164. const trophys = call.result.response;
  3165. const calls = [];
  3166. for (const week in trophys) {
  3167. const trophy = trophys[week];
  3168. if (!trophy.championRewardFarmed) {
  3169. calls.push({
  3170. name: 'hallOfFameFarmTrophyReward',
  3171. args: { trophyId: week, rewardType: 'champion' },
  3172. ident: 'body_champion_' + week,
  3173. });
  3174. }
  3175. if (Object.keys(trophy.clanReward).length && !trophy.clanRewardFarmed) {
  3176. calls.push({
  3177. name: 'hallOfFameFarmTrophyReward',
  3178. args: { trophyId: week, rewardType: 'clan' },
  3179. ident: 'body_clan_' + week,
  3180. });
  3181. }
  3182. }
  3183. if (calls.length) {
  3184. Send({ calls })
  3185. .then((e) => e.results.map((e) => e.result.response))
  3186. .then(async results => {
  3187. let coin18 = 0,
  3188. coin19 = 0,
  3189. gold = 0,
  3190. starmoney = 0;
  3191. for (const r of results) {
  3192. coin18 += r?.coin ? +r.coin[18] : 0;
  3193. coin19 += r?.coin ? +r.coin[19] : 0;
  3194. gold += r?.gold ? +r.gold : 0;
  3195. starmoney += r?.starmoney ? +r.starmoney : 0;
  3196. }
  3197. let msg = I18N('ELEMENT_TOURNAMENT_REWARD') + '<br>';
  3198. if (coin18) {
  3199. msg += cheats.translate('LIB_COIN_NAME_18') + `: ${coin18}<br>`;
  3200. }
  3201. if (coin19) {
  3202. msg += cheats.translate('LIB_COIN_NAME_19') + `: ${coin19}<br>`;
  3203. }
  3204. if (gold) {
  3205. msg += cheats.translate('LIB_PSEUDO_COIN') + `: ${gold}<br>`;
  3206. }
  3207. if (starmoney) {
  3208. msg += cheats.translate('LIB_PSEUDO_STARMONEY') + `: ${starmoney}<br>`;
  3209. }
  3210. await popup.confirm(msg, [{ msg: I18N('BTN_OK'), result: 0 }]);
  3211. });
  3212. }
  3213. }
  3214. if (call.ident == callsIdent['clanDomination_getInfo']) {
  3215. clanDominationGetInfo = call.result.response;
  3216. }
  3217. /*
  3218. if (call.ident == callsIdent['chatGetAll'] && call.args.chatType == 'clanDomination' && !callsIdent['clanDomination_mapState']) {
  3219. this.onReadySuccess = async function () {
  3220. const result = await Send({
  3221. calls: [
  3222. {
  3223. name: 'clanDomination_mapState',
  3224. args: {},
  3225. ident: 'clanDomination_mapState',
  3226. },
  3227. ],
  3228. }).then((e) => e.results[0].result.response);
  3229. let townPositions = result.townPositions;
  3230. let positions = {};
  3231. for (let pos in townPositions) {
  3232. let townPosition = townPositions[pos];
  3233. positions[townPosition.position] = townPosition;
  3234. }
  3235. Object.assign(clanDominationGetInfo, {
  3236. townPositions: positions,
  3237. });
  3238. let userPositions = result.userPositions;
  3239. for (let pos in clanDominationGetInfo.townPositions) {
  3240. let townPosition = clanDominationGetInfo.townPositions[pos];
  3241. if (townPosition.status) {
  3242. userPositions[townPosition.userId] = +pos;
  3243. }
  3244. }
  3245. cheats.updateMap(result);
  3246. };
  3247. }
  3248. if (call.ident == callsIdent['clanDomination_mapState']) {
  3249. const townPositions = call.result.response.townPositions;
  3250. const userPositions = call.result.response.userPositions;
  3251. for (let pos in townPositions) {
  3252. let townPos = townPositions[pos];
  3253. if (townPos.status) {
  3254. userPositions[townPos.userId] = townPos.position;
  3255. }
  3256. }
  3257. isChange = true;
  3258. }
  3259. */
  3260. }
  3261. if (mainReward && artifactChestOpen) {
  3262. console.log(allReward);
  3263. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  3264. artifactChestOpen = false;
  3265. artifactChestOpenCallName = '';
  3266. isChange = true;
  3267. }
  3268. } catch(err) {
  3269. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  3270. }
  3271.  
  3272. if (isChange) {
  3273. Object.defineProperty(this, 'responseText', {
  3274. writable: true
  3275. });
  3276. this.responseText = JSON.stringify(respond);
  3277. }
  3278. }
  3279.  
  3280. /** Добавляет в бой эффекты усиления*/
  3281. function addBuff(battle) {
  3282. let effects = battle.effects;
  3283. let buffType = getInput('needResource2');
  3284. if (-1 < buffType && buffType < 7) {
  3285. let percentBuff = getInput('needResource');
  3286. effects.defenders = {};
  3287. effects.defenders[buffs[buffType]] = percentBuff;
  3288. } else if (buffType.slice(0, 1) == "-" || isChecked('treningBattle')) {
  3289. buffType = parseInt(buffType.slice(1), 10);
  3290. effects.defenders = repleyBattle.effects;
  3291. battle.defenders[0] = repleyBattle.defenders;
  3292. let def = battle.defenders[0];
  3293. if (buffType == 1) {
  3294. for (let i in def) {
  3295. let state = def[i].state;
  3296. state.hp = state.maxHp;
  3297. state.energy = 0;
  3298. state.isDead = false;
  3299. }
  3300. } else if (buffType == 2 || isChecked('finishingBattle')) {
  3301. for (let i in def) {
  3302. let state2 = def[i].state;
  3303. let rState = repleyBattle.state[i];
  3304. if (!!rState) {
  3305. state2.hp = rState.hp;
  3306. state2.energy = rState.energy;
  3307. state2.isDead = rState.isDead;
  3308. } else {
  3309. state2.hp = 0;
  3310. state2.energy = 0;
  3311. state2.isDead = true;
  3312. }
  3313. }
  3314. }
  3315. }
  3316. }
  3317. const buffs = ['percentBuffAll_allAttacks', 'percentBuffAll_armor', 'percentBuffAll_magicResist', 'percentBuffAll_physicalAttack', 'percentBuffAll_magicPower', 'percentDamageBuff_dot', 'percentBuffAll_healing', 'percentBuffAllForFallenAllies', 'percentBuffAll_energyIncrease', 'percentIncomeDamageReduce_any', 'percentIncomeDamageReduce_physical', 'percentIncomeDamageReduce_magic', 'percentIncomeDamageReduce_dot', 'percentBuffHp', 'percentBuffByPerk_energyIncrease_8', 'percentBuffByPerk_energyIncrease_5', 'percentBuffByPerk_energyIncrease_4', 'percentBuffByPerk_allAttacks_5', 'percentBuffByPerk_allAttacks_4', 'percentBuffByPerk_allAttacks_9', 'percentBuffByPerk_castSpeed_7', 'percentBuffByPerk_castSpeed_6', 'percentBuffByPerk_castSpeed_10', 'percentBuffByPerk_armorPenetration_6', 'percentBuffByPerk_physicalAttack_6', 'percentBuffByPerk_armorPenetration_10', 'percentBuffByPerk_physicalAttack_10', 'percentBuffByPerk_magicPower_7', 'percentDamageBuff_any','percentDamageBuff_physical','percentDamageBuff_magic','corruptedBoss_25_80_1_100_10','tutorialPetUlt_1.2','tutorialBossPercentDamage_1','corruptedBoss_50_80_1_100_10','corruptedBoss_75_80_1_100_10','corruptedBoss_80_80_1_100_10','percentBuffByPerk_castSpeed_4','percentBuffByPerk_energyIncrease_7','percentBuffByPerk_castSpeed_9','percentBuffByPerk_castSpeed_8','bossStageBuff_1000000_20000','bossStageBuff_1500000_30000','bossStageBuff_2000000_40000','bossStageBuff_3000000_50000','bossStageBuff_4000000_60000','bossStageBuff_5000000_70000','bossStageBuff_7500000_80000','bossStageBuff_11000000_90000','bossStageBuff_15000000_100000','bossStageBuff_20000000_120000','bossStageBuff_30000000_150000','bossStageBuff_40000000_200000','bossStageBuff_50000000_250000','percentBuffPet_strength','percentBuffPet_castSpeed','percentBuffPet_petEnergyIncrease','stormPowerBuff_100_1000','stormPowerBuff_100','changeStarSphereIncomingDamage_any','changeBlackHoleDamage','buffSpeedWhenStarfall','changeTeamStartEnergy','decreaseStarSphereDamage','avoidAllBlackholeDamageOnce','groveKeeperAvoidBlackholeDamageChance_3','undeadPreventsNightmares_3','engeneerIncreaseStarMachineIncomingDamage_3','overloadHealDamageStarSphere','nightmareDeathGiveLifesteal_100','starfallIncreaseAllyHeal_9_100','decreaseStarSphereDamage_4','increaseNightmaresIncomingDamageByCount','debuffNightmareOnSpawnFrom_7_hp','damageNightmareGiveEnergy','ultEnergyCompensationOnPlanetParade_6','bestDamagerBeforeParadeGetsImprovedBuff_any','starSphereDeathGiveEnergy','bestDamagerOnParadeBecomesImmortal_any','preventNightmare','buffStatWithHealing_physicalAttack_magic_100','buffStatWithHealing_magicPower_physical_100','buffStatWithHealing_hp_dot_100','replaceHealingWithDamage_magic','critWithRetaliation_10_dot','posessionWithBuffStat_25_20_5_10','energyBurnDamageWithEffect_magic_Silence_5_5','percentBuffHp','percentBuffAll_energyIncrease','percentBuffAll_magicResist','percentBuffAll_armor','percentIncomeDamageReduce_any','percentBuffAll_healing','percentIncomeDamageReduce_any','percentBuffHp','percentBuffAll_energyIncrease','percentIncomeDamageReduce_any','percentBuffHp','percentBuffByPerk_castSpeed_All','percentBuffAll_castSpeed'];
  3318.  
  3319. /**
  3320. * Request an answer to a question
  3321. *
  3322. * Запрос ответа на вопрос
  3323. */
  3324. async function getAnswer(question) {
  3325. // c29tZSBzdHJhbmdlIHN5bWJvbHM=
  3326. const quizAPI = new ZingerYWebsiteAPI('getAnswer.php', arguments, { question });
  3327. return new Promise((resolve, reject) => {
  3328. quizAPI.request().then((data) => {
  3329. if (data.result) {
  3330. resolve(data.result);
  3331. } else {
  3332. resolve(false);
  3333. }
  3334. }).catch((error) => {
  3335. console.error(error);
  3336. resolve(false);
  3337. });
  3338. })
  3339. }
  3340.  
  3341. /**
  3342. * Submitting a question and answer to a database
  3343. *
  3344. * Отправка вопроса и ответа в базу данных
  3345. */
  3346. function sendAnswerInfo(answerInfo) {
  3347. // c29tZSBub25zZW5zZQ==
  3348. const quizAPI = new ZingerYWebsiteAPI('setAnswer.php', arguments, { answerInfo });
  3349. quizAPI.request().then((data) => {
  3350. if (data.result) {
  3351. console.log(I18N('SENT_QUESTION'));
  3352. }
  3353. });
  3354. }
  3355.  
  3356. /**
  3357. * Returns the battle type by preset type
  3358. *
  3359. * Возвращает тип боя по типу пресета
  3360. */
  3361. function getBattleType(strBattleType) {
  3362. if (!strBattleType) {
  3363. return null;
  3364. }
  3365. switch (strBattleType) {
  3366. case 'titan_pvp':
  3367. return 'get_titanPvp';
  3368. case 'titan_pvp_manual':
  3369. case 'titan_clan_pvp':
  3370. case 'clan_pvp_titan':
  3371. case 'clan_global_pvp_titan':
  3372. case 'brawl_titan':
  3373. case 'challenge_titan':
  3374. case 'titan_mission':
  3375. return 'get_titanPvpManual';
  3376. case 'clan_raid': // Asgard Boss // Босс асгарда
  3377. case 'adventure': // Adventures // Приключения
  3378. case 'clan_global_pvp':
  3379. case 'epic_brawl':
  3380. case 'clan_pvp':
  3381. return 'get_clanPvp';
  3382. case 'dungeon_titan':
  3383. case 'titan_tower':
  3384. return 'get_titan';
  3385. case 'tower':
  3386. return 'get_tower';
  3387. case 'clan_dungeon':
  3388. case 'pve':
  3389. case 'mission':
  3390. return 'get_pve';
  3391. case 'mission_boss':
  3392. return 'get_missionBoss';
  3393. case 'challenge':
  3394. case 'pvp_manual':
  3395. return 'get_pvpManual';
  3396. case 'grand':
  3397. case 'arena':
  3398. case 'pvp':
  3399. case 'clan_domination':
  3400. return 'get_pvp';
  3401. case 'core':
  3402. return 'get_core';
  3403. default: {
  3404. if (strBattleType.includes('invasion')) {
  3405. return 'get_invasion';
  3406. }
  3407. if (strBattleType.includes('boss')) {
  3408. return 'get_boss';
  3409. }
  3410. if (strBattleType.includes('titan_arena')) {
  3411. return 'get_titanPvpManual';
  3412. }
  3413. return 'get_clanPvp';
  3414. }
  3415. }
  3416. }
  3417. /**
  3418. * Returns the class name of the passed object
  3419. *
  3420. * Возвращает название класса переданного объекта
  3421. */
  3422. function getClass(obj) {
  3423. return {}.toString.call(obj).slice(8, -1);
  3424. }
  3425. /**
  3426. * Calculates the request signature
  3427. *
  3428. * Расчитывает сигнатуру запроса
  3429. */
  3430. this.getSignature = function(headers, data) {
  3431. const sign = {
  3432. signature: '',
  3433. length: 0,
  3434. add: function (text) {
  3435. this.signature += text;
  3436. if (this.length < this.signature.length) {
  3437. this.length = 3 * (this.signature.length + 1) >> 1;
  3438. }
  3439. },
  3440. }
  3441. sign.add(headers["X-Request-Id"]);
  3442. sign.add(':');
  3443. sign.add(headers["X-Auth-Token"]);
  3444. sign.add(':');
  3445. sign.add(headers["X-Auth-Session-Id"]);
  3446. sign.add(':');
  3447. sign.add(data);
  3448. sign.add(':');
  3449. sign.add('LIBRARY-VERSION=1');
  3450. sign.add('UNIQUE-SESSION-ID=' + headers["X-Env-Unique-Session-Id"]);
  3451.  
  3452. return md5(sign.signature);
  3453. }
  3454. /**
  3455. * Creates an interface
  3456. *
  3457. * Создает интерфейс
  3458. */
  3459. function createInterface() {
  3460. popup.init();
  3461. scriptMenu.init({
  3462. showMenu: true
  3463. });
  3464. scriptMenu.addHeader(GM_info.script.name, justInfo);
  3465. scriptMenu.addHeader('v' + GM_info.script.version);
  3466. }
  3467.  
  3468. function addControls() {
  3469. createInterface();
  3470. const checkboxDetails = scriptMenu.addDetails(I18N('SETTINGS'));
  3471. for (let name in checkboxes) {
  3472. if (checkboxes[name].hide) {
  3473. continue;
  3474. }
  3475. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  3476. /**
  3477. * Getting the state of checkboxes from storage
  3478. * Получаем состояние чекбоксов из storage
  3479. */
  3480. let val = storage.get(name, null);
  3481. if (val != null) {
  3482. checkboxes[name].cbox.checked = val;
  3483. } else {
  3484. storage.set(name, checkboxes[name].default);
  3485. checkboxes[name].cbox.checked = checkboxes[name].default;
  3486. }
  3487. /**
  3488. * Tracing the change event of the checkbox for writing to storage
  3489. * Отсеживание события изменения чекбокса для записи в storage
  3490. */
  3491. checkboxes[name].cbox.dataset['name'] = name;
  3492. checkboxes[name].cbox.addEventListener('change', async function (event) {
  3493. const nameCheckbox = this.dataset['name'];
  3494. /*
  3495. if (this.checked && nameCheckbox == 'cancelBattle') {
  3496. this.checked = false;
  3497. if (await popup.confirm(I18N('MSG_BAN_ATTENTION'), [
  3498. { msg: I18N('BTN_NO_I_AM_AGAINST'), result: true },
  3499. { msg: I18N('BTN_YES_I_AGREE'), result: false },
  3500. ])) {
  3501. return;
  3502. }
  3503. this.checked = true;
  3504. }
  3505. */
  3506. storage.set(nameCheckbox, this.checked);
  3507. })
  3508. }
  3509.  
  3510. const inputDetails = scriptMenu.addDetails(I18N('VALUES'));
  3511. for (let name in inputs) {
  3512. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  3513. /**
  3514. * Get inputText state from storage
  3515. * Получаем состояние inputText из storage
  3516. */
  3517. let val = storage.get(name, null);
  3518. if (val != null) {
  3519. inputs[name].input.value = val;
  3520. } else {
  3521. storage.set(name, inputs[name].default);
  3522. inputs[name].input.value = inputs[name].default;
  3523. }
  3524. /**
  3525. * Tracing a field change event for a record in storage
  3526. * Отсеживание события изменения поля для записи в storage
  3527. */
  3528. inputs[name].input.dataset['name'] = name;
  3529. inputs[name].input.addEventListener('input', function () {
  3530. const inputName = this.dataset['name'];
  3531. let value = +this.value;
  3532. if (!value || Number.isNaN(value)) {
  3533. value = storage.get(inputName, inputs[inputName].default);
  3534. inputs[name].input.value = value;
  3535. }
  3536. storage.set(inputName, value);
  3537. })
  3538. }
  3539. const inputDetails2 = scriptMenu.addDetails(I18N('SAVING'));
  3540. for (let name in inputs2) {
  3541. inputs2[name].input = scriptMenu.addInputText(inputs2[name].title, false, inputDetails2);
  3542. /**
  3543. * Get inputText state from storage
  3544. * Получаем состояние inputText из storage
  3545. */
  3546. let val = storage.get(name, null);
  3547. if (val != null) {
  3548. inputs2[name].input.value = val;
  3549. } else {
  3550. storage.set(name, inputs2[name].default);
  3551. inputs2[name].input.value = inputs2[name].default;
  3552. }
  3553. /**
  3554. * Tracing a field change event for a record in storage
  3555. * Отсеживание события изменения поля для записи в storage
  3556. */
  3557. inputs2[name].input.dataset['name'] = name;
  3558. inputs2[name].input.addEventListener('input', function () {
  3559. const inputName = this.dataset['name'];
  3560. let value = +this.value;
  3561. if (!value || Number.isNaN(value)) {
  3562. value = storage.get(inputName, inputs2[inputName].default);
  3563. inputs2[name].input.value = value;
  3564. }
  3565. storage.set(inputName, value);
  3566. })
  3567. }
  3568. /* const inputDetails3 = scriptMenu.addDetails(I18N('USER_ID'));
  3569. for (let name in inputs3) {
  3570. inputs3[name].input = scriptMenu.addInputText(inputs3[name].title, false, inputDetails3);
  3571. /**
  3572. * Get inputText state from storage
  3573. * Получаем состояние inputText из storage
  3574. *
  3575. let val = storage.get(name, null);
  3576. if (val != null) {
  3577. inputs3[name].input.value = val;
  3578. } else {
  3579. storage.set(name, inputs3[name].default);
  3580. inputs3[name].input.value = inputs3[name].default;
  3581. }
  3582. /**
  3583. * Tracing a field change event for a record in storage
  3584. * Отсеживание события изменения поля для записи в storage
  3585. *
  3586. inputs3[name].input.dataset['name'] = name;
  3587. inputs3[name].input.addEventListener('input', function () {
  3588. const inputName = this.dataset['name'];
  3589. let value = +this.value;
  3590. if (!value || Number.isNaN(value)) {
  3591. value = storage.get(inputName, inputs3[inputName].default);
  3592. inputs3[name].input.value = value;
  3593. }
  3594. storage.set(inputName, value);
  3595. })
  3596. }*/
  3597. }
  3598.  
  3599. /**
  3600. * Sending a request
  3601. *
  3602. * Отправка запроса
  3603. */
  3604. function send(json, callback, pr) {
  3605. if (typeof json == 'string') {
  3606. json = JSON.parse(json);
  3607. }
  3608. for (const call of json.calls) {
  3609. if (!call?.context?.actionTs) {
  3610. call.context = {
  3611. actionTs: Math.floor(performance.now())
  3612. }
  3613. }
  3614. }
  3615. json = JSON.stringify(json);
  3616. /**
  3617. * We get the headlines of the previous intercepted request
  3618. * Получаем заголовки предыдущего перехваченого запроса
  3619. */
  3620. let headers = lastHeaders;
  3621. /**
  3622. * We increase the header of the query Certifier by 1
  3623. * Увеличиваем заголовок идетификатора запроса на 1
  3624. */
  3625. headers["X-Request-Id"]++;
  3626. /**
  3627. * We calculate the title with the signature
  3628. * Расчитываем заголовок с сигнатурой
  3629. */
  3630. headers["X-Auth-Signature"] = getSignature(headers, json);
  3631. /**
  3632. * Create a new ajax request
  3633. * Создаем новый AJAX запрос
  3634. */
  3635. let xhr = new XMLHttpRequest;
  3636. /**
  3637. * Indicate the previously saved URL for API queries
  3638. * Указываем ранее сохраненный URL для API запросов
  3639. */
  3640. xhr.open('POST', apiUrl, true);
  3641. /**
  3642. * Add the function to the event change event
  3643. * Добавляем функцию к событию смены статуса запроса
  3644. */
  3645. xhr.onreadystatechange = function() {
  3646. /**
  3647. * If the result of the request is obtained, we call the flask function
  3648. * Если результат запроса получен вызываем колбек функцию
  3649. */
  3650. if(xhr.readyState == 4) {
  3651. callback(xhr.response, pr);
  3652. }
  3653. };
  3654. /**
  3655. * Indicate the type of request
  3656. * Указываем тип запроса
  3657. */
  3658. xhr.responseType = 'json';
  3659. /**
  3660. * We set the request headers
  3661. * Задаем заголовки запроса
  3662. */
  3663. for(let nameHeader in headers) {
  3664. let head = headers[nameHeader];
  3665. xhr.setRequestHeader(nameHeader, head);
  3666. }
  3667. /**
  3668. * Sending a request
  3669. * Отправляем запрос
  3670. */
  3671. xhr.send(json);
  3672. }
  3673.  
  3674. let hideTimeoutProgress = 0;
  3675. /**
  3676. * Hide progress
  3677. *
  3678. * Скрыть прогресс
  3679. */
  3680. function hideProgress(timeout) {
  3681. timeout = timeout || 0;
  3682. clearTimeout(hideTimeoutProgress);
  3683. hideTimeoutProgress = setTimeout(function () {
  3684. scriptMenu.setStatus('');
  3685. }, timeout);
  3686. }
  3687. /**
  3688. * Progress display
  3689. *
  3690. * Отображение прогресса
  3691. */
  3692. function setProgress(text, hide, onclick) {
  3693. scriptMenu.setStatus(text, onclick);
  3694. hide = hide || false;
  3695. if (hide) {
  3696. hideProgress(3000);
  3697. }
  3698. }
  3699.  
  3700. /**
  3701. * Returns the timer value depending on the subscription
  3702. *
  3703. * Возвращает значение таймера в зависимости от подписки
  3704. */
  3705. function getTimer(time, div) {
  3706. let speedDiv = 5;
  3707. if (subEndTime < Date.now()) {
  3708. speedDiv = div || 1.5;
  3709. }
  3710. return Math.max(Math.ceil(time / speedDiv + 1.5), 4);
  3711. }
  3712.  
  3713. /**
  3714. * Calculates HASH MD5 from string
  3715. *
  3716. * Расчитывает HASH MD5 из строки
  3717. *
  3718. * [js-md5]{@link https://github.com/emn178/js-md5}
  3719. *
  3720. * @namespace md5
  3721. * @version 0.7.3
  3722. * @author Chen, Yi-Cyuan [emn178@gmail.com]
  3723. * @copyright Chen, Yi-Cyuan 2014-2017
  3724. * @license MIT
  3725. */
  3726. !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 _}))}();
  3727.  
  3728. /**
  3729. * Script for beautiful dialog boxes
  3730. *
  3731. * Скрипт для красивых диалоговых окошек
  3732. */
  3733. const popup = new (function () {
  3734. this.popUp,
  3735. this.downer,
  3736. this.middle,
  3737. this.msgText,
  3738. this.buttons = [];
  3739. this.checkboxes = [];
  3740. this.dialogPromice = null;
  3741.  
  3742. this.init = function () {
  3743. addStyle();
  3744. addBlocks();
  3745. addEventListeners();
  3746. }
  3747.  
  3748. const addEventListeners = () => {
  3749. document.addEventListener('keyup', (e) => {
  3750. if (e.key == 'Escape') {
  3751. if (this.dialogPromice) {
  3752. const { func, result } = this.dialogPromice;
  3753. this.dialogPromice = null;
  3754. popup.hide();
  3755. func(result);
  3756. }
  3757. }
  3758. });
  3759. }
  3760.  
  3761. const addStyle = () => {
  3762. let style = document.createElement('style');
  3763. style.innerText = `
  3764. .PopUp_ {
  3765. position: absolute;
  3766. min-width: 300px;
  3767. max-width: 500px;
  3768. max-height: 600px;
  3769. background-color: #190e08e6;
  3770. z-index: 10001;
  3771. top: 169px;
  3772. left: 345px;
  3773. border: 3px #ce9767 solid;
  3774. border-radius: 10px;
  3775. display: flex;
  3776. flex-direction: column;
  3777. justify-content: space-around;
  3778. padding: 15px 9px;
  3779. box-sizing: border-box;
  3780. }
  3781.  
  3782. .PopUp_back {
  3783. position: absolute;
  3784. background-color: #00000066;
  3785. width: 100%;
  3786. height: 100%;
  3787. z-index: 10000;
  3788. top: 0;
  3789. left: 0;
  3790. }
  3791.  
  3792. .PopUp_close {
  3793. width: 40px;
  3794. height: 40px;
  3795. position: absolute;
  3796. right: -18px;
  3797. top: -18px;
  3798. border: 3px solid #c18550;
  3799. border-radius: 20px;
  3800. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  3801. background-position-y: 3px;
  3802. box-shadow: -1px 1px 3px black;
  3803. cursor: pointer;
  3804. box-sizing: border-box;
  3805. }
  3806.  
  3807. .PopUp_close:hover {
  3808. filter: brightness(1.2);
  3809. }
  3810.  
  3811. .PopUp_crossClose {
  3812. width: 100%;
  3813. height: 100%;
  3814. background-size: 65%;
  3815. background-position: center;
  3816. background-repeat: no-repeat;
  3817. 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")
  3818. }
  3819.  
  3820. .PopUp_blocks {
  3821. width: 100%;
  3822. height: 50%;
  3823. display: flex;
  3824. justify-content: space-evenly;
  3825. align-items: center;
  3826. flex-wrap: wrap;
  3827. justify-content: center;
  3828. }
  3829.  
  3830. .PopUp_blocks:last-child {
  3831. margin-top: 25px;
  3832. }
  3833.  
  3834. .PopUp_buttons {
  3835. display: flex;
  3836. margin: 7px 10px;
  3837. flex-direction: column;
  3838. }
  3839.  
  3840. .PopUp_button {
  3841. background-color: #52A81C;
  3842. border-radius: 5px;
  3843. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3844. cursor: pointer;
  3845. padding: 4px 12px 6px;
  3846. }
  3847.  
  3848. .PopUp_input {
  3849. text-align: center;
  3850. font-size: 16px;
  3851. height: 27px;
  3852. border: 1px solid #cf9250;
  3853. border-radius: 9px 9px 0px 0px;
  3854. background: transparent;
  3855. color: #fce1ac;
  3856. padding: 1px 10px;
  3857. box-sizing: border-box;
  3858. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  3859. }
  3860.  
  3861. .PopUp_checkboxes {
  3862. display: flex;
  3863. flex-direction: column;
  3864. margin: 15px 15px -5px 15px;
  3865. align-items: flex-start;
  3866. }
  3867.  
  3868. .PopUp_ContCheckbox {
  3869. margin: 2px 0px;
  3870. }
  3871.  
  3872. .PopUp_checkbox {
  3873. position: absolute;
  3874. z-index: -1;
  3875. opacity: 0;
  3876. }
  3877. .PopUp_checkbox+label {
  3878. display: inline-flex;
  3879. align-items: center;
  3880. user-select: none;
  3881.  
  3882. font-size: 15px;
  3883. font-family: sans-serif;
  3884. font-weight: 600;
  3885. font-stretch: condensed;
  3886. letter-spacing: 1px;
  3887. color: #fce1ac;
  3888. text-shadow: 0px 0px 1px;
  3889. }
  3890. .PopUp_checkbox+label::before {
  3891. content: '';
  3892. display: inline-block;
  3893. width: 20px;
  3894. height: 20px;
  3895. border: 1px solid #cf9250;
  3896. border-radius: 7px;
  3897. margin-right: 7px;
  3898. }
  3899. .PopUp_checkbox:checked+label::before {
  3900. 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");
  3901. }
  3902.  
  3903. .PopUp_input::placeholder {
  3904. color: #fce1ac75;
  3905. }
  3906.  
  3907. .PopUp_input:focus {
  3908. outline: 0;
  3909. }
  3910.  
  3911. .PopUp_input + .PopUp_button {
  3912. border-radius: 0px 0px 5px 5px;
  3913. padding: 2px 18px 5px;
  3914. }
  3915.  
  3916. .PopUp_button:hover {
  3917. filter: brightness(1.2);
  3918. }
  3919.  
  3920. .PopUp_button:active {
  3921. box-shadow: inset 0px 5px 10px, inset 0px 1px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  3922. }
  3923.  
  3924. .PopUp_text {
  3925. font-size: 22px;
  3926. font-family: sans-serif;
  3927. font-weight: 600;
  3928. font-stretch: condensed;
  3929. white-space: pre-wrap;
  3930. letter-spacing: 1px;
  3931. text-align: center;
  3932. }
  3933.  
  3934. .PopUp_buttonText {
  3935. color: #E4FF4C;
  3936. text-shadow: 0px 1px 2px black;
  3937. }
  3938.  
  3939. .PopUp_msgText {
  3940. color: #FDE5B6;
  3941. text-shadow: 0px 0px 2px;
  3942. }
  3943.  
  3944. .PopUp_hideBlock {
  3945. display: none;
  3946. }
  3947. `;
  3948. document.head.appendChild(style);
  3949. }
  3950.  
  3951. const addBlocks = () => {
  3952. this.back = document.createElement('div');
  3953. this.back.classList.add('PopUp_back');
  3954. this.back.classList.add('PopUp_hideBlock');
  3955. document.body.append(this.back);
  3956.  
  3957. this.popUp = document.createElement('div');
  3958. this.popUp.classList.add('PopUp_');
  3959. this.back.append(this.popUp);
  3960.  
  3961. let upper = document.createElement('div')
  3962. upper.classList.add('PopUp_blocks');
  3963. this.popUp.append(upper);
  3964.  
  3965. this.middle = document.createElement('div')
  3966. this.middle.classList.add('PopUp_blocks');
  3967. this.middle.classList.add('PopUp_checkboxes');
  3968. this.popUp.append(this.middle);
  3969.  
  3970. this.downer = document.createElement('div')
  3971. this.downer.classList.add('PopUp_blocks');
  3972. this.popUp.append(this.downer);
  3973.  
  3974. this.msgText = document.createElement('div');
  3975. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  3976. upper.append(this.msgText);
  3977. }
  3978.  
  3979. this.showBack = function () {
  3980. this.back.classList.remove('PopUp_hideBlock');
  3981. }
  3982.  
  3983. this.hideBack = function () {
  3984. this.back.classList.add('PopUp_hideBlock');
  3985. }
  3986.  
  3987. this.show = function () {
  3988. if (this.checkboxes.length) {
  3989. this.middle.classList.remove('PopUp_hideBlock');
  3990. }
  3991. this.showBack();
  3992. this.popUp.classList.remove('PopUp_hideBlock');
  3993. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  3994. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  3995. }
  3996.  
  3997. this.hide = function () {
  3998. this.hideBack();
  3999. this.popUp.classList.add('PopUp_hideBlock');
  4000. }
  4001.  
  4002. this.addAnyButton = (option) => {
  4003. const contButton = document.createElement('div');
  4004. contButton.classList.add('PopUp_buttons');
  4005. this.downer.append(contButton);
  4006.  
  4007. let inputField = {
  4008. value: option.result || option.default
  4009. }
  4010. if (option.isInput) {
  4011. inputField = document.createElement('input');
  4012. inputField.type = 'text';
  4013. if (option.placeholder) {
  4014. inputField.placeholder = option.placeholder;
  4015. }
  4016. if (option.default) {
  4017. inputField.value = option.default;
  4018. }
  4019. inputField.classList.add('PopUp_input');
  4020. contButton.append(inputField);
  4021. }
  4022.  
  4023. const button = document.createElement('div');
  4024. button.classList.add('PopUp_button');
  4025. button.title = option.title || '';
  4026. contButton.append(button);
  4027.  
  4028. const buttonText = document.createElement('div');
  4029. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  4030. buttonText.innerHTML = option.msg;
  4031. button.append(buttonText);
  4032.  
  4033. return { button, contButton, inputField };
  4034. }
  4035.  
  4036. this.addCloseButton = () => {
  4037. let button = document.createElement('div')
  4038. button.classList.add('PopUp_close');
  4039. this.popUp.append(button);
  4040.  
  4041. let crossClose = document.createElement('div')
  4042. crossClose.classList.add('PopUp_crossClose');
  4043. button.append(crossClose);
  4044.  
  4045. return { button, contButton: button };
  4046. }
  4047.  
  4048. this.addButton = (option, buttonClick) => {
  4049.  
  4050. const { button, contButton, inputField } = option.isClose ? this.addCloseButton() : this.addAnyButton(option);
  4051. if (option.isClose) {
  4052. this.dialogPromice = {func: buttonClick, result: option.result};
  4053. }
  4054. button.addEventListener('click', () => {
  4055. let result = '';
  4056. if (option.isInput) {
  4057. result = inputField.value;
  4058. }
  4059. if (option.isClose || option.isCancel) {
  4060. this.dialogPromice = null;
  4061. }
  4062. buttonClick(result);
  4063. });
  4064.  
  4065. this.buttons.push(contButton);
  4066. }
  4067.  
  4068. this.clearButtons = () => {
  4069. while (this.buttons.length) {
  4070. this.buttons.pop().remove();
  4071. }
  4072. }
  4073.  
  4074. this.addCheckBox = (checkBox) => {
  4075. const contCheckbox = document.createElement('div');
  4076. contCheckbox.classList.add('PopUp_ContCheckbox');
  4077. this.middle.append(contCheckbox);
  4078.  
  4079. const checkbox = document.createElement('input');
  4080. checkbox.type = 'checkbox';
  4081. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  4082. checkbox.dataset.name = checkBox.name;
  4083. checkbox.checked = checkBox.checked;
  4084. checkbox.label = checkBox.label;
  4085. checkbox.title = checkBox.title || '';
  4086. checkbox.classList.add('PopUp_checkbox');
  4087. contCheckbox.appendChild(checkbox)
  4088.  
  4089. const checkboxLabel = document.createElement('label');
  4090. checkboxLabel.innerText = checkBox.label;
  4091. checkboxLabel.title = checkBox.title || '';
  4092. checkboxLabel.setAttribute('for', checkbox.id);
  4093. contCheckbox.appendChild(checkboxLabel);
  4094.  
  4095. this.checkboxes.push(checkbox);
  4096. }
  4097.  
  4098. this.clearCheckBox = () => {
  4099. this.middle.classList.add('PopUp_hideBlock');
  4100. while (this.checkboxes.length) {
  4101. this.checkboxes.pop().parentNode.remove();
  4102. }
  4103. }
  4104.  
  4105. this.setMsgText = (text) => {
  4106. this.msgText.innerHTML = text;
  4107. }
  4108.  
  4109. this.getCheckBoxes = () => {
  4110. const checkBoxes = [];
  4111.  
  4112. for (const checkBox of this.checkboxes) {
  4113. checkBoxes.push({
  4114. name: checkBox.dataset.name,
  4115. label: checkBox.label,
  4116. checked: checkBox.checked
  4117. });
  4118. }
  4119.  
  4120. return checkBoxes;
  4121. }
  4122.  
  4123. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  4124. this.clearButtons();
  4125. this.clearCheckBox();
  4126. return new Promise((complete, failed) => {
  4127. this.setMsgText(msg);
  4128. if (!buttOpt) {
  4129. buttOpt = [{ msg: 'Ok', result: true, isInput: false }];
  4130. }
  4131. for (const checkBox of checkBoxes) {
  4132. this.addCheckBox(checkBox);
  4133. }
  4134. for (let butt of buttOpt) {
  4135. this.addButton(butt, (result) => {
  4136. result = result || butt.result;
  4137. complete(result);
  4138. popup.hide();
  4139. });
  4140. if (butt.isCancel) {
  4141. this.dialogPromice = {func: complete, result: butt.result};
  4142. }
  4143. }
  4144. this.show();
  4145. });
  4146. }
  4147.  
  4148. });
  4149.  
  4150. /**
  4151. * Script control panel
  4152. *
  4153. * Панель управления скриптом
  4154. */
  4155. const scriptMenu = new (function () {
  4156.  
  4157. this.mainMenu,
  4158. this.buttons = [],
  4159. this.checkboxes = [];
  4160. this.option = {
  4161. showMenu: false,
  4162. showDetails: {}
  4163. };
  4164.  
  4165. this.init = function (option = {}) {
  4166. this.option = Object.assign(this.option, option);
  4167. this.option.showDetails = this.loadShowDetails();
  4168. addStyle();
  4169. addBlocks();
  4170. }
  4171.  
  4172. const addStyle = () => {
  4173. style = document.createElement('style');
  4174. style.innerText = `
  4175. .scriptMenu_status {
  4176. position: absolute;
  4177. z-index: 10001;
  4178. white-space: pre-wrap; //тест для выравнивания кнопок
  4179. /* max-height: 30px; */
  4180. top: -1px;
  4181. left: 30%;
  4182. cursor: pointer;
  4183. border-radius: 0px 0px 10px 10px;
  4184. background: #190e08e6;
  4185. border: 1px #ce9767 solid;
  4186. font-size: 18px;
  4187. font-family: sans-serif;
  4188. font-weight: 600;
  4189. font-stretch: condensed;
  4190. letter-spacing: 1px;
  4191. color: #fce1ac;
  4192. text-shadow: 0px 0px 1px;
  4193. transition: 0.5s;
  4194. padding: 2px 10px 3px;
  4195. }
  4196. .scriptMenu_statusHide {
  4197. top: -35px;
  4198. height: 30px;
  4199. overflow: hidden;
  4200. }
  4201. .scriptMenu_label {
  4202. position: absolute;
  4203. top: 30%;
  4204. left: -4px;
  4205. z-index: 9999;
  4206. cursor: pointer;
  4207. width: 30px;
  4208. height: 30px;
  4209. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  4210. border: 1px solid #1a2f04;
  4211. border-radius: 5px;
  4212. box-shadow:
  4213. inset 0px 2px 4px #83ce26,
  4214. inset 0px -4px 6px #1a2f04,
  4215. 0px 0px 2px black,
  4216. 0px 0px 0px 2px #ce9767;
  4217. }
  4218. .scriptMenu_label:hover {
  4219. filter: brightness(1.2);
  4220. }
  4221. .scriptMenu_arrowLabel {
  4222. width: 100%;
  4223. height: 100%;
  4224. background-size: 75%;
  4225. background-position: center;
  4226. background-repeat: no-repeat;
  4227. 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");
  4228. box-shadow: 0px 1px 2px #000;
  4229. border-radius: 5px;
  4230. filter: drop-shadow(0px 1px 2px #000D);
  4231. }
  4232. .scriptMenu_main {
  4233. position: absolute;
  4234. max-width: 285px;
  4235. z-index: 9999;
  4236. top: 50%;
  4237. transform: translateY(-40%);
  4238. background: #190e08e6;
  4239. border: 1px #ce9767 solid;
  4240. border-radius: 0px 10px 10px 0px;
  4241. border-left: none;
  4242. padding: 5px 10px 5px 5px;
  4243. box-sizing: border-box;
  4244. font-size: 15px;
  4245. font-family: sans-serif;
  4246. font-weight: 600;
  4247. font-stretch: condensed;
  4248. letter-spacing: 1px;
  4249. color: #fce1ac;
  4250. text-shadow: 0px 0px 1px;
  4251. transition: 1s;
  4252. display: flex;
  4253. flex-direction: column;
  4254. flex-wrap: nowrap;
  4255. }
  4256. .scriptMenu_showMenu {
  4257. display: none;
  4258. }
  4259. .scriptMenu_showMenu:checked~.scriptMenu_main {
  4260. left: 0px;
  4261. }
  4262. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  4263. left: -300px;
  4264. }
  4265. .scriptMenu_divInput {
  4266. margin: 2px;
  4267. }
  4268. .scriptMenu_divInputText {
  4269. margin: 2px;
  4270. align-self: center;
  4271. display: flex;
  4272. }
  4273. .scriptMenu_checkbox {
  4274. position: absolute;
  4275. z-index: -1;
  4276. opacity: 0;
  4277. }
  4278. .scriptMenu_checkbox+label {
  4279. display: inline-flex;
  4280. align-items: center;
  4281. user-select: none;
  4282. }
  4283. .scriptMenu_checkbox+label::before {
  4284. content: '';
  4285. display: inline-block;
  4286. width: 20px;
  4287. height: 20px;
  4288. border: 1px solid #cf9250;
  4289. border-radius: 7px;
  4290. margin-right: 7px;
  4291. }
  4292. .scriptMenu_checkbox:checked+label::before {
  4293. 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");
  4294. }
  4295. .scriptMenu_close {
  4296. width: 40px;
  4297. height: 40px;
  4298. position: absolute;
  4299. right: -18px;
  4300. top: -18px;
  4301. border: 3px solid #c18550;
  4302. border-radius: 20px;
  4303. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  4304. background-position-y: 3px;
  4305. box-shadow: -1px 1px 3px black;
  4306. cursor: pointer;
  4307. box-sizing: border-box;
  4308. }
  4309. .scriptMenu_close:hover {
  4310. filter: brightness(1.2);
  4311. }
  4312. .scriptMenu_crossClose {
  4313. width: 100%;
  4314. height: 100%;
  4315. background-size: 65%;
  4316. background-position: center;
  4317. background-repeat: no-repeat;
  4318. 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")
  4319. }
  4320. .scriptMenu_button {
  4321. user-select: none;
  4322. border-radius: 5px;
  4323. cursor: pointer;
  4324. padding: 5px 14px 8px;
  4325. margin: 4px;
  4326. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  4327. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4328. }
  4329. .scriptMenu_button:hover {
  4330. filter: brightness(1.2);
  4331. }
  4332. .scriptMenu_button:active {
  4333. box-shadow: inset 0px 4px 6px #442901, inset 0px 4px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  4334. }
  4335. .scriptMenu_buttonText {
  4336. color: #fce5b7;
  4337. text-shadow: 0px 1px 2px black;
  4338. text-align: center;
  4339. }
  4340. .scriptMenu_header {
  4341. text-align: center;
  4342. align-self: center;
  4343. font-size: 15px;
  4344. margin: 0px 15px;
  4345. }
  4346. .scriptMenu_header a {
  4347. color: #fce5b7;
  4348. text-decoration: none;
  4349. }
  4350. .scriptMenu_InputText {
  4351. text-align: center;
  4352. width: 130px;
  4353. height: 24px;
  4354. border: 1px solid #cf9250;
  4355. border-radius: 9px;
  4356. background: transparent;
  4357. color: #fce1ac;
  4358. padding: 0px 10px;
  4359. box-sizing: border-box;
  4360. }
  4361. .scriptMenu_InputText:focus {
  4362. filter: brightness(1.2);
  4363. outline: 0;
  4364. }
  4365. .scriptMenu_InputText::placeholder {
  4366. color: #fce1ac75;
  4367. }
  4368. .scriptMenu_Summary {
  4369. cursor: pointer;
  4370. margin-left: 7px;
  4371. }
  4372. .scriptMenu_Details {
  4373. align-self: center;
  4374. }
  4375. `;
  4376. document.head.appendChild(style);
  4377. }
  4378.  
  4379. const addBlocks = () => {
  4380. const main = document.createElement('div');
  4381. document.body.appendChild(main);
  4382.  
  4383. this.status = document.createElement('div');
  4384. this.status.classList.add('scriptMenu_status');
  4385. this.setStatus('');
  4386. main.appendChild(this.status);
  4387.  
  4388. const label = document.createElement('label');
  4389. label.classList.add('scriptMenu_label');
  4390. label.setAttribute('for', 'checkbox_showMenu');
  4391. main.appendChild(label);
  4392.  
  4393. const arrowLabel = document.createElement('div');
  4394. arrowLabel.classList.add('scriptMenu_arrowLabel');
  4395. label.appendChild(arrowLabel);
  4396.  
  4397. const checkbox = document.createElement('input');
  4398. checkbox.type = 'checkbox';
  4399. checkbox.id = 'checkbox_showMenu';
  4400. checkbox.checked = this.option.showMenu;
  4401. checkbox.classList.add('scriptMenu_showMenu');
  4402. main.appendChild(checkbox);
  4403.  
  4404. this.mainMenu = document.createElement('div');
  4405. this.mainMenu.classList.add('scriptMenu_main');
  4406. main.appendChild(this.mainMenu);
  4407.  
  4408. const closeButton = document.createElement('label');
  4409. closeButton.classList.add('scriptMenu_close');
  4410. closeButton.setAttribute('for', 'checkbox_showMenu');
  4411. this.mainMenu.appendChild(closeButton);
  4412.  
  4413. const crossClose = document.createElement('div');
  4414. crossClose.classList.add('scriptMenu_crossClose');
  4415. closeButton.appendChild(crossClose);
  4416. }
  4417.  
  4418. this.setStatus = (text, onclick) => {
  4419. if (!text) {
  4420. this.status.classList.add('scriptMenu_statusHide');
  4421. } else {
  4422. this.status.classList.remove('scriptMenu_statusHide');
  4423. this.status.innerHTML = text;
  4424. }
  4425.  
  4426. if (typeof onclick == 'function') {
  4427. this.status.addEventListener("click", onclick, {
  4428. once: true
  4429. });
  4430. }
  4431. }
  4432.  
  4433. /**
  4434. * Adding a text element
  4435. *
  4436. * Добавление текстового элемента
  4437. * @param {String} text text // текст
  4438. * @param {Function} func Click function // функция по клику
  4439. * @param {HTMLDivElement} main parent // родитель
  4440. */
  4441. this.addHeader = (text, func, main) => {
  4442. main = main || this.mainMenu;
  4443. const header = document.createElement('div');
  4444. header.classList.add('scriptMenu_header');
  4445. header.innerHTML = text;
  4446. if (typeof func == 'function') {
  4447. header.addEventListener('click', func);
  4448. }
  4449. main.appendChild(header);
  4450. }
  4451.  
  4452. /**
  4453. * Adding a button
  4454. *
  4455. * Добавление кнопки
  4456. * @param {String} text
  4457. * @param {Function} func
  4458. * @param {String} title
  4459. * @param {HTMLDivElement} main parent // родитель
  4460. */
  4461. this.addButton = (text, func, title, main) => {
  4462. main = main || this.mainMenu;
  4463. const button = document.createElement('div');
  4464. button.classList.add('scriptMenu_button');
  4465. button.title = title;
  4466. button.addEventListener('click', func);
  4467. main.appendChild(button);
  4468.  
  4469. const buttonText = document.createElement('div');
  4470. buttonText.classList.add('scriptMenu_buttonText');
  4471. buttonText.innerText = text;
  4472. button.appendChild(buttonText);
  4473. this.buttons.push(button);
  4474.  
  4475. return button;
  4476. }
  4477.  
  4478. /**
  4479. * Adding checkbox
  4480. *
  4481. * Добавление чекбокса
  4482. * @param {String} label
  4483. * @param {String} title
  4484. * @param {HTMLDivElement} main parent // родитель
  4485. * @returns
  4486. */
  4487. this.addCheckbox = (label, title, main) => {
  4488. main = main || this.mainMenu;
  4489. const divCheckbox = document.createElement('div');
  4490. divCheckbox.classList.add('scriptMenu_divInput');
  4491. divCheckbox.title = title;
  4492. main.appendChild(divCheckbox);
  4493.  
  4494. const checkbox = document.createElement('input');
  4495. checkbox.type = 'checkbox';
  4496. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  4497. checkbox.classList.add('scriptMenu_checkbox');
  4498. divCheckbox.appendChild(checkbox)
  4499.  
  4500. const checkboxLabel = document.createElement('label');
  4501. checkboxLabel.innerText = label;
  4502. checkboxLabel.setAttribute('for', checkbox.id);
  4503. divCheckbox.appendChild(checkboxLabel);
  4504.  
  4505. this.checkboxes.push(checkbox);
  4506. return checkbox;
  4507. }
  4508.  
  4509. /**
  4510. * Adding input field
  4511. *
  4512. * Добавление поля ввода
  4513. * @param {String} title
  4514. * @param {String} placeholder
  4515. * @param {HTMLDivElement} main parent // родитель
  4516. * @returns
  4517. */
  4518. this.addInputText = (title, placeholder, main) => {
  4519. main = main || this.mainMenu;
  4520. const divInputText = document.createElement('div');
  4521. divInputText.classList.add('scriptMenu_divInputText');
  4522. divInputText.title = title;
  4523. main.appendChild(divInputText);
  4524.  
  4525. const newInputText = document.createElement('input');
  4526. newInputText.type = 'text';
  4527. if (placeholder) {
  4528. newInputText.placeholder = placeholder;
  4529. }
  4530. newInputText.classList.add('scriptMenu_InputText');
  4531. divInputText.appendChild(newInputText)
  4532. return newInputText;
  4533. }
  4534.  
  4535. /**
  4536. * Adds a dropdown block
  4537. *
  4538. * Добавляет раскрывающийся блок
  4539. * @param {String} summary
  4540. * @param {String} name
  4541. * @returns
  4542. */
  4543. this.addDetails = (summaryText, name = null) => {
  4544. const details = document.createElement('details');
  4545. details.classList.add('scriptMenu_Details');
  4546. this.mainMenu.appendChild(details);
  4547.  
  4548. const summary = document.createElement('summary');
  4549. summary.classList.add('scriptMenu_Summary');
  4550. summary.innerText = summaryText;
  4551. if (name) {
  4552. const self = this;
  4553. details.open = this.option.showDetails[name];
  4554. details.dataset.name = name;
  4555. summary.addEventListener('click', () => {
  4556. self.option.showDetails[details.dataset.name] = !details.open;
  4557. self.saveShowDetails(self.option.showDetails);
  4558. });
  4559. }
  4560. details.appendChild(summary);
  4561.  
  4562. return details;
  4563. }
  4564.  
  4565. /**
  4566. * Saving the expanded state of the details blocks
  4567. *
  4568. * Сохранение состояния развенутости блоков details
  4569. * @param {*} value
  4570. */
  4571. this.saveShowDetails = (value) => {
  4572. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  4573. }
  4574.  
  4575. /**
  4576. * Loading the state of expanded blocks details
  4577. *
  4578. * Загрузка состояния развенутости блоков details
  4579. * @returns
  4580. */
  4581. this.loadShowDetails = () => {
  4582. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  4583.  
  4584. if (!showDetails) {
  4585. return {};
  4586. }
  4587.  
  4588. try {
  4589. showDetails = JSON.parse(showDetails);
  4590. } catch (e) {
  4591. return {};
  4592. }
  4593.  
  4594. return showDetails;
  4595. }
  4596. });
  4597.  
  4598. /**
  4599. * Пример использования
  4600. scriptMenu.init();
  4601. scriptMenu.addHeader('v1.508');
  4602. scriptMenu.addCheckbox('testHack', 'Тестовый взлом игры!');
  4603. scriptMenu.addButton('Запуск!', () => console.log('click'), 'подсказака');
  4604. scriptMenu.addInputText('input подсказака');
  4605. */
  4606. /**
  4607. * Game Library
  4608. *
  4609. * Игровая библиотека
  4610. */
  4611. class Library {
  4612. defaultLibUrl = 'https://heroesru-a.akamaihd.net/vk/v1101/lib/lib.json';
  4613.  
  4614. constructor() {
  4615. if (!Library.instance) {
  4616. Library.instance = this;
  4617. }
  4618.  
  4619. return Library.instance;
  4620. }
  4621.  
  4622. async load() {
  4623. try {
  4624. await this.getUrlLib();
  4625. console.log(this.defaultLibUrl);
  4626. this.data = await fetch(this.defaultLibUrl).then(e => e.json())
  4627. } catch (error) {
  4628. console.error('Не удалось загрузить библиотеку', error)
  4629. }
  4630. }
  4631.  
  4632. async getUrlLib() {
  4633. try {
  4634. const db = new Database('hw_cache', 'cache');
  4635. await db.open();
  4636. const cacheLibFullUrl = await db.get('lib/lib.json.gz', false);
  4637. this.defaultLibUrl = cacheLibFullUrl.fullUrl.split('.gz').shift();
  4638. } catch(e) {}
  4639. }
  4640.  
  4641. getData(id) {
  4642. return this.data[id];
  4643. }
  4644. }
  4645.  
  4646. this.lib = new Library();
  4647. /**
  4648. * Database
  4649. *
  4650. * База данных
  4651. */
  4652. class Database {
  4653. constructor(dbName, storeName) {
  4654. this.dbName = dbName;
  4655. this.storeName = storeName;
  4656. this.db = null;
  4657. }
  4658.  
  4659. async open() {
  4660. return new Promise((resolve, reject) => {
  4661. const request = indexedDB.open(this.dbName);
  4662.  
  4663. request.onerror = () => {
  4664. reject(new Error(`Failed to open database ${this.dbName}`));
  4665. };
  4666.  
  4667. request.onsuccess = () => {
  4668. this.db = request.result;
  4669. resolve();
  4670. };
  4671.  
  4672. request.onupgradeneeded = (event) => {
  4673. const db = event.target.result;
  4674. if (!db.objectStoreNames.contains(this.storeName)) {
  4675. db.createObjectStore(this.storeName);
  4676. }
  4677. };
  4678. });
  4679. }
  4680.  
  4681. async set(key, value) {
  4682. return new Promise((resolve, reject) => {
  4683. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4684. const store = transaction.objectStore(this.storeName);
  4685. const request = store.put(value, key);
  4686.  
  4687. request.onerror = () => {
  4688. reject(new Error(`Failed to save value with key ${key}`));
  4689. };
  4690.  
  4691. request.onsuccess = () => {
  4692. resolve();
  4693. };
  4694. });
  4695. }
  4696.  
  4697. async get(key, def) {
  4698. return new Promise((resolve, reject) => {
  4699. const transaction = this.db.transaction([this.storeName], 'readonly');
  4700. const store = transaction.objectStore(this.storeName);
  4701. const request = store.get(key);
  4702.  
  4703. request.onerror = () => {
  4704. resolve(def);
  4705. };
  4706.  
  4707. request.onsuccess = () => {
  4708. resolve(request.result);
  4709. };
  4710. });
  4711. }
  4712.  
  4713. async delete(key) {
  4714. return new Promise((resolve, reject) => {
  4715. const transaction = this.db.transaction([this.storeName], 'readwrite');
  4716. const store = transaction.objectStore(this.storeName);
  4717. const request = store.delete(key);
  4718.  
  4719. request.onerror = () => {
  4720. reject(new Error(`Failed to delete value with key ${key}`));
  4721. };
  4722.  
  4723. request.onsuccess = () => {
  4724. resolve();
  4725. };
  4726. });
  4727. }
  4728. }
  4729.  
  4730. /**
  4731. * Returns the stored value
  4732. *
  4733. * Возвращает сохраненное значение
  4734. */
  4735. function getSaveVal(saveName, def) {
  4736. const result = storage.get(saveName, def);
  4737. return result;
  4738. }
  4739.  
  4740. /**
  4741. * Stores value
  4742. *
  4743. * Сохраняет значение
  4744. */
  4745. function setSaveVal(saveName, value) {
  4746. storage.set(saveName, value);
  4747. }
  4748.  
  4749. /**
  4750. * Database initialization
  4751. *
  4752. * Инициализация базы данных
  4753. */
  4754. const db = new Database(GM_info.script.name, 'settings');
  4755.  
  4756. /**
  4757. * Data store
  4758. *
  4759. * Хранилище данных
  4760. */
  4761. const storage = {
  4762. userId: 0,
  4763. /**
  4764. * Default values
  4765. *
  4766. * Значения по умолчанию
  4767. */
  4768. values: [
  4769. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  4770. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  4771. ...Object.entries(inputs2).map(e => ({ [e[0]]: e[1].default })),
  4772. //...Object.entries(inputs3).map(e => ({ [e[0]]: e[1].default })),
  4773. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  4774. name: GM_info.script.name,
  4775. get: function (key, def) {
  4776. if (key in this.values) {
  4777. return this.values[key];
  4778. }
  4779. return def;
  4780. },
  4781. set: function (key, value) {
  4782. this.values[key] = value;
  4783. db.set(this.userId, this.values).catch(
  4784. e => null
  4785. );
  4786. localStorage[this.name + ':' + key] = value;
  4787. },
  4788. delete: function (key) {
  4789. delete this.values[key];
  4790. db.set(this.userId, this.values);
  4791. delete localStorage[this.name + ':' + key];
  4792. }
  4793. }
  4794.  
  4795. /**
  4796. * Returns all keys from localStorage that start with prefix (for migration)
  4797. *
  4798. * Возвращает все ключи из localStorage которые начинаются с prefix (для миграции)
  4799. */
  4800. function getAllValuesStartingWith(prefix) {
  4801. const values = [];
  4802. for (let i = 0; i < localStorage.length; i++) {
  4803. const key = localStorage.key(i);
  4804. if (key.startsWith(prefix)) {
  4805. const val = localStorage.getItem(key);
  4806. const keyValue = key.split(':')[1];
  4807. values.push({ key: keyValue, val });
  4808. }
  4809. }
  4810. return values;
  4811. }
  4812.  
  4813. /**
  4814. * Opens or migrates to a database
  4815. *
  4816. * Открывает или мигрирует в базу данных
  4817. */
  4818. async function openOrMigrateDatabase(userId) {
  4819. storage.userId = userId;
  4820. try {
  4821. await db.open();
  4822. } catch(e) {
  4823. return;
  4824. }
  4825. let settings = await db.get(userId, false);
  4826.  
  4827. if (settings) {
  4828. storage.values = settings;
  4829. return;
  4830. }
  4831.  
  4832. const values = getAllValuesStartingWith(GM_info.script.name);
  4833. for (const value of values) {
  4834. let val = null;
  4835. try {
  4836. val = JSON.parse(value.val);
  4837. } catch {
  4838. break;
  4839. }
  4840. storage.values[value.key] = val;
  4841. }
  4842. await db.set(userId, storage.values);
  4843. }
  4844.  
  4845. class ZingerYWebsiteAPI {
  4846. /**
  4847. * Class for interaction with the API of the zingery.ru website
  4848. * Intended only for use with the HeroWarsHelper script:
  4849. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  4850. * Copyright ZingerY
  4851. */
  4852. url = 'https://zingery32.ru/heroes/'; //убрано
  4853. // YWJzb2x1dGVseSB1c2VsZXNzIGxpbmU=
  4854. constructor(urn, env, data = {}) {
  4855. this.urn = urn;
  4856. this.fd = {
  4857. now: Date.now(),
  4858. fp: this.constructor.toString().replaceAll(/\s/g, ''),
  4859. env: env.callee.toString().replaceAll(/\s/g, ''),
  4860. info: (({ name, version, author }) => [name, version, author])(GM_info.script),
  4861. ...data,
  4862. };
  4863. }
  4864. sign() {
  4865. return md5([...this.fd.info, ~(this.fd.now % 1e3), this.fd.fp].join('_'));
  4866. }
  4867. encode(data) {
  4868. return btoa(encodeURIComponent(JSON.stringify(data)));
  4869. }
  4870. decode(data) {
  4871. return JSON.parse(decodeURIComponent(atob(data)));
  4872. }
  4873. headers() {
  4874. return {
  4875. 'X-Request-Signature': this.sign(),
  4876. 'X-Script-Name': GM_info.script.name,
  4877. 'X-Script-Version': GM_info.script.version,
  4878. 'X-Script-Author': GM_info.script.author,
  4879. 'X-Script-ZingerY': 42,
  4880. };
  4881. }
  4882. async request() {
  4883. try {
  4884. const response = await fetch(this.url + this.urn, {
  4885. method: 'POST',
  4886. headers: this.headers(),
  4887. body: this.encode(this.fd),
  4888. });
  4889. const text = await response.text();
  4890. return this.decode(text);
  4891. } catch (e) {
  4892. console.error(e);
  4893. return [];
  4894. }
  4895. }
  4896. /**
  4897. * Класс для взаимодействия с API сайта zingery.ru
  4898. * Предназначен только для использования со скриптом HeroWarsHelper:
  4899. * https://greasyfork.org/ru/scripts/450693-herowarshelper
  4900. * Copyright ZingerY
  4901. */
  4902. }
  4903.  
  4904. /**
  4905. * Sending expeditions
  4906. *
  4907. * Отправка экспедиций
  4908. */
  4909. function checkExpedition() {
  4910. return new Promise((resolve, reject) => {
  4911. const expedition = new Expedition(resolve, reject);
  4912. expedition.start();
  4913. });
  4914. }
  4915.  
  4916. class Expedition {
  4917. checkExpedInfo = {
  4918. calls: [
  4919. {
  4920. name: 'expeditionGet',
  4921. args: {},
  4922. ident: 'expeditionGet',
  4923. },
  4924. {
  4925. name: 'heroGetAll',
  4926. args: {},
  4927. ident: 'heroGetAll',
  4928. },
  4929. ],
  4930. };
  4931.  
  4932. constructor(resolve, reject) {
  4933. this.resolve = resolve;
  4934. this.reject = reject;
  4935. }
  4936.  
  4937. async start() {
  4938. const data = await Send(JSON.stringify(this.checkExpedInfo));
  4939.  
  4940. const expedInfo = data.results[0].result.response;
  4941. const dataHeroes = data.results[1].result.response;
  4942. const dataExped = { useHeroes: [], exped: [] };
  4943. const calls = [];
  4944.  
  4945. /**
  4946. * Adding expeditions to collect
  4947. * Добавляем экспедиции для сбора
  4948. */
  4949. let countGet = 0;
  4950. for (var n in expedInfo) {
  4951. const exped = expedInfo[n];
  4952. const dateNow = Date.now() / 1000;
  4953. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  4954. countGet++;
  4955. calls.push({
  4956. name: 'expeditionFarm',
  4957. args: { expeditionId: exped.id },
  4958. ident: 'expeditionFarm_' + exped.id,
  4959. });
  4960. } else {
  4961. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  4962. }
  4963. if (exped.status == 1) {
  4964. dataExped.exped.push({ id: exped.id, power: exped.power });
  4965. }
  4966. }
  4967. dataExped.exped = dataExped.exped.sort((a, b) => b.power - a.power);
  4968.  
  4969. /**
  4970. * Putting together a list of heroes
  4971. * Собираем список героев
  4972. */
  4973. const heroesArr = [];
  4974. for (let n in dataHeroes) {
  4975. const hero = dataHeroes[n];
  4976. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  4977. let heroPower = hero.power;
  4978. // Лара Крофт * 3
  4979. if (hero.id == 63 && hero.color >= 16) {
  4980. heroPower *= 3;
  4981. }
  4982. heroesArr.push({ id: hero.id, power: heroPower });
  4983. }
  4984. }
  4985.  
  4986. /**
  4987. * Adding expeditions to send
  4988. * Добавляем экспедиции для отправки
  4989. */
  4990. let countSend = 0;
  4991. heroesArr.sort((a, b) => a.power - b.power);
  4992. for (const exped of dataExped.exped) {
  4993. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  4994. if (heroesIds && heroesIds.length > 4) {
  4995. for (let q in heroesArr) {
  4996. if (heroesIds.includes(heroesArr[q].id)) {
  4997. delete heroesArr[q];
  4998. }
  4999. }
  5000. countSend++;
  5001. calls.push({
  5002. name: 'expeditionSendHeroes',
  5003. args: {
  5004. expeditionId: exped.id,
  5005. heroes: heroesIds,
  5006. },
  5007. ident: 'expeditionSendHeroes_' + exped.id,
  5008. });
  5009. }
  5010. }
  5011.  
  5012. if (calls.length) {
  5013. await Send({ calls });
  5014. this.end(I18N('EXPEDITIONS_SENT', {countGet, countSend}));
  5015. return;
  5016. }
  5017. this.end(I18N('EXPEDITIONS_NOTHING'));
  5018. }
  5019.  
  5020. /**
  5021. * Selection of heroes for expeditions
  5022. *
  5023. * Подбор героев для экспедиций
  5024. */
  5025. selectionHeroes(heroes, power) {
  5026. const resultHeroers = [];
  5027. const heroesIds = [];
  5028. for (let q = 0; q < 5; q++) {
  5029. for (let i in heroes) {
  5030. let hero = heroes[i];
  5031. if (heroesIds.includes(hero.id)) {
  5032. continue;
  5033. }
  5034.  
  5035. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5036. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  5037. if (hero.power > need) {
  5038. resultHeroers.push(hero);
  5039. heroesIds.push(hero.id);
  5040. break;
  5041. }
  5042. }
  5043. }
  5044.  
  5045. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  5046. if (summ < power) {
  5047. return false;
  5048. }
  5049. return heroesIds;
  5050. }
  5051.  
  5052. /**
  5053. * Ends expedition script
  5054. *
  5055. * Завершает скрипт экспедиции
  5056. */
  5057. end(msg) {
  5058. setProgress(msg, true);
  5059. this.resolve();
  5060. }
  5061. }
  5062.  
  5063. /**
  5064. * Walkthrough of the dungeon
  5065. *
  5066. * Прохождение подземелья
  5067. */
  5068. function testDungeon() {
  5069. return new Promise((resolve, reject) => {
  5070. const dung = new executeDungeon(resolve, reject);
  5071. const titanit = getInput('countTitanit');
  5072. dung.start(titanit);
  5073. });
  5074. }
  5075.  
  5076. /**
  5077. * Walkthrough of the dungeon
  5078. *
  5079. * Прохождение подземелья
  5080. */
  5081. function executeDungeon(resolve, reject) {
  5082. dungeonActivity = 0;
  5083. maxDungeonActivity = 150;
  5084.  
  5085. titanGetAll = [];
  5086.  
  5087. teams = {
  5088. heroes: [],
  5089. earth: [],
  5090. fire: [],
  5091. neutral: [],
  5092. water: [],
  5093. }
  5094.  
  5095. titanStats = [];
  5096.  
  5097. titansStates = {};
  5098.  
  5099. callsExecuteDungeon = {
  5100. calls: [{
  5101. name: "dungeonGetInfo",
  5102. args: {},
  5103. ident: "dungeonGetInfo"
  5104. }, {
  5105. name: "teamGetAll",
  5106. args: {},
  5107. ident: "teamGetAll"
  5108. }, {
  5109. name: "teamGetFavor",
  5110. args: {},
  5111. ident: "teamGetFavor"
  5112. }, {
  5113. name: "clanGetInfo",
  5114. args: {},
  5115. ident: "clanGetInfo"
  5116. }, {
  5117. name: "titanGetAll",
  5118. args: {},
  5119. ident: "titanGetAll"
  5120. }, {
  5121. name: "inventoryGet",
  5122. args: {},
  5123. ident: "inventoryGet"
  5124. }]
  5125. }
  5126.  
  5127. this.start = function(titanit) {
  5128. maxDungeonActivity = titanit || getInput('countTitanit');
  5129. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  5130. }
  5131.  
  5132. /**
  5133. * Getting data on the dungeon
  5134. *
  5135. * Получаем данные по подземелью
  5136. */
  5137. function startDungeon(e) {
  5138. stopDung = false; // стоп подземка
  5139. res = e.results;
  5140. dungeonGetInfo = res[0].result.response;
  5141. if (!dungeonGetInfo) {
  5142. endDungeon('noDungeon', res);
  5143. return;
  5144. }
  5145. teamGetAll = res[1].result.response;
  5146. teamGetFavor = res[2].result.response;
  5147. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  5148. titanGetAll = Object.values(res[4].result.response);
  5149. countPredictionCard = res[5].result.response.consumable[81];
  5150.  
  5151. teams.hero = {
  5152. favor: teamGetFavor.dungeon_hero,
  5153. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  5154. teamNum: 0,
  5155. }
  5156. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  5157. if (heroPet) {
  5158. teams.hero.pet = heroPet;
  5159. }
  5160.  
  5161. teams.neutral = {
  5162. favor: {},
  5163. heroes: getTitanTeam(titanGetAll, 'neutral'),
  5164. teamNum: 0,
  5165. };
  5166. teams.water = {
  5167. favor: {},
  5168. heroes: getTitanTeam(titanGetAll, 'water'),
  5169. teamNum: 0,
  5170. };
  5171. teams.fire = {
  5172. favor: {},
  5173. heroes: getTitanTeam(titanGetAll, 'fire'),
  5174. teamNum: 0,
  5175. };
  5176. teams.earth = {
  5177. favor: {},
  5178. heroes: getTitanTeam(titanGetAll, 'earth'),
  5179. teamNum: 0,
  5180. };
  5181.  
  5182.  
  5183. checkFloor(dungeonGetInfo);
  5184. }
  5185.  
  5186. function getTitanTeam(titans, type) {
  5187. switch (type) {
  5188. case 'neutral':
  5189. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5190. case 'water':
  5191. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  5192. case 'fire':
  5193. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  5194. case 'earth':
  5195. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  5196. }
  5197. }
  5198.  
  5199. function getNeutralTeam() {
  5200. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5201. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5202. }
  5203.  
  5204. function fixTitanTeam(titans) {
  5205. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  5206. return titans;
  5207. }
  5208.  
  5209. /**
  5210. * Checking the floor
  5211. *
  5212. * Проверяем этаж
  5213. */
  5214. async function checkFloor(dungeonInfo) {
  5215. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  5216. saveProgress();
  5217. return;
  5218. }
  5219. // console.log(dungeonInfo, dungeonActivity);
  5220. setProgress(`${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  5221. if (dungeonActivity >= maxDungeonActivity) {
  5222. endDungeon('endDungeon', 'maxActive ' + dungeonActivity + '/' + maxDungeonActivity);
  5223. return;
  5224. }
  5225. titansStates = dungeonInfo.states.titans;
  5226. titanStats = titanObjToArray(titansStates);
  5227. if (stopDung){
  5228. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  5229. return;
  5230. }
  5231. const floorChoices = dungeonInfo.floor.userData;
  5232. const floorType = dungeonInfo.floorType;
  5233. //const primeElement = dungeonInfo.elements.prime;
  5234. if (floorType == "battle") {
  5235. const calls = [];
  5236. for (let teamNum in floorChoices) {
  5237. attackerType = floorChoices[teamNum].attackerType;
  5238. const args = fixTitanTeam(teams[attackerType]);
  5239. if (attackerType == 'neutral') {
  5240. args.heroes = getNeutralTeam();
  5241. }
  5242. if (!args.heroes.length) {
  5243. continue;
  5244. }
  5245. args.teamNum = teamNum;
  5246. calls.push({
  5247. name: "dungeonStartBattle",
  5248. args,
  5249. ident: "body_" + teamNum
  5250. })
  5251. }
  5252. if (!calls.length) {
  5253. endDungeon('endDungeon', 'All Dead');
  5254. return;
  5255. }
  5256. const battleDatas = await Send(JSON.stringify({ calls }))
  5257. .then(e => e.results.map(n => n.result.response))
  5258. const battleResults = [];
  5259. for (n in battleDatas) {
  5260. battleData = battleDatas[n]
  5261. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5262. battleResults.push(await Calc(battleData).then(result => {
  5263. result.teamNum = n;
  5264. result.attackerType = floorChoices[n].attackerType;
  5265. return result;
  5266. }));
  5267. }
  5268. processingPromises(battleResults)
  5269. }
  5270. }
  5271.  
  5272. function processingPromises(results) {
  5273. let selectBattle = results[0];
  5274. if (results.length < 2) {
  5275. // console.log(selectBattle);
  5276. if (!selectBattle.result.win) {
  5277. endDungeon('dungeonEndBattle\n', selectBattle);
  5278. return;
  5279. }
  5280. endBattle(selectBattle);
  5281. return;
  5282. }
  5283.  
  5284. selectBattle = false;
  5285. let bestState = -1000;
  5286. for (const result of results) {
  5287. const recovery = getState(result);
  5288. if (recovery > bestState) {
  5289. bestState = recovery;
  5290. selectBattle = result
  5291. }
  5292. }
  5293. // console.log(selectBattle.teamNum, results);
  5294. if (!selectBattle || bestState <= -1000) {
  5295. endDungeon('dungeonEndBattle\n', results);
  5296. return;
  5297. }
  5298.  
  5299. startBattle(selectBattle.teamNum, selectBattle.attackerType)
  5300. .then(endBattle);
  5301. }
  5302.  
  5303. /**
  5304. * Let's start the fight
  5305. *
  5306. * Начинаем бой
  5307. */
  5308. function startBattle(teamNum, attackerType) {
  5309. return new Promise(function (resolve, reject) {
  5310. args = fixTitanTeam(teams[attackerType]);
  5311. args.teamNum = teamNum;
  5312. if (attackerType == 'neutral') {
  5313. const titans = titanGetAll.filter(e => !titansStates[e.id]?.isDead)
  5314. args.heroes = titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5315. }
  5316. startBattleCall = {
  5317. calls: [{
  5318. name: "dungeonStartBattle",
  5319. args,
  5320. ident: "body"
  5321. }]
  5322. }
  5323. send(JSON.stringify(startBattleCall), resultBattle, {
  5324. resolve,
  5325. teamNum,
  5326. attackerType
  5327. });
  5328. });
  5329. }
  5330. /**
  5331. * Returns the result of the battle in a promise
  5332. *
  5333. * Возращает резульат боя в промис
  5334. */
  5335. function resultBattle(resultBattles, args) {
  5336. battleData = resultBattles.results[0].result.response;
  5337. battleType = "get_tower";
  5338. if (battleData.type == "dungeon_titan") {
  5339. battleType = "get_titan";
  5340. }
  5341. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  5342. BattleCalc(battleData, battleType, function (result) {
  5343. result.teamNum = args.teamNum;
  5344. result.attackerType = args.attackerType;
  5345. args.resolve(result);
  5346. });
  5347. }
  5348. /**
  5349. * Finishing the fight
  5350. *
  5351. * Заканчиваем бой
  5352. */
  5353. async function endBattle(battleInfo) {
  5354. if (battleInfo.result.win) {
  5355. const args = {
  5356. result: battleInfo.result,
  5357. progress: battleInfo.progress,
  5358. }
  5359. if (countPredictionCard > 0) {
  5360. args.isRaid = true;
  5361. } else {
  5362. const timer = getTimer(battleInfo.battleTime);
  5363. console.log(timer);
  5364. await countdownTimer(timer, `${I18N('DUNGEON')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  5365. }
  5366. const calls = [{
  5367. name: "dungeonEndBattle",
  5368. args,
  5369. ident: "body"
  5370. }];
  5371. lastDungeonBattleData = null;
  5372. send(JSON.stringify({ calls }), resultEndBattle);
  5373. } else {
  5374. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  5375. }
  5376. }
  5377.  
  5378. /**
  5379. * Getting and processing battle results
  5380. *
  5381. * Получаем и обрабатываем результаты боя
  5382. */
  5383. function resultEndBattle(e) {
  5384. if ('error' in e) {
  5385. popup.confirm(I18N('ERROR_MSG', {
  5386. name: e.error.name,
  5387. description: e.error.description,
  5388. }));
  5389. endDungeon('errorRequest', e);
  5390. return;
  5391. }
  5392. battleResult = e.results[0].result.response;
  5393. if ('error' in battleResult) {
  5394. endDungeon('errorBattleResult', battleResult);
  5395. return;
  5396. }
  5397. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  5398. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  5399. checkFloor(dungeonGetInfo);
  5400. }
  5401.  
  5402. /**
  5403. * Returns the coefficient of condition of the
  5404. * difference in titanium before and after the battle
  5405. *
  5406. * Возвращает коэффициент состояния титанов после боя
  5407. */
  5408. function getState(result) {
  5409. if (!result.result.win) {
  5410. return -1000;
  5411. }
  5412.  
  5413. let beforeSumFactor = 0;
  5414. const beforeTitans = result.battleData.attackers;
  5415. for (let titanId in beforeTitans) {
  5416. const titan = beforeTitans[titanId];
  5417. const state = titan.state;
  5418. let factor = 1;
  5419. if (state) {
  5420. const hp = state.hp / titan.hp;
  5421. const energy = state.energy / 1e3;
  5422. factor = hp + energy / 20
  5423. }
  5424. beforeSumFactor += factor;
  5425. }
  5426.  
  5427. let afterSumFactor = 0;
  5428. const afterTitans = result.progress[0].attackers.heroes;
  5429. for (let titanId in afterTitans) {
  5430. const titan = afterTitans[titanId];
  5431. const hp = titan.hp / beforeTitans[titanId].hp;
  5432. const energy = titan.energy / 1e3;
  5433. const factor = hp + energy / 20;
  5434. afterSumFactor += factor;
  5435. }
  5436. return afterSumFactor - beforeSumFactor;
  5437. }
  5438.  
  5439. /**
  5440. * Converts an object with IDs to an array with IDs
  5441. *
  5442. * Преобразует объект с идетификаторами в массив с идетификаторами
  5443. */
  5444. function titanObjToArray(obj) {
  5445. let titans = [];
  5446. for (let id in obj) {
  5447. obj[id].id = id;
  5448. titans.push(obj[id]);
  5449. }
  5450. return titans;
  5451. }
  5452.  
  5453. function saveProgress() {
  5454. let saveProgressCall = {
  5455. calls: [{
  5456. name: "dungeonSaveProgress",
  5457. args: {},
  5458. ident: "body"
  5459. }]
  5460. }
  5461. send(JSON.stringify(saveProgressCall), resultEndBattle);
  5462. }
  5463.  
  5464. function endDungeon(reason, info) {
  5465. console.warn(reason, info);
  5466. setProgress(`${I18N('DUNGEON')} ${I18N('COMPLETED')}`, true);
  5467. resolve();
  5468. }
  5469. }
  5470.  
  5471. /**
  5472. * Passing the tower
  5473. *
  5474. * Прохождение башни
  5475. */
  5476. function testTower() {
  5477. return new Promise((resolve, reject) => {
  5478. tower = new executeTower(resolve, reject);
  5479. tower.start();
  5480. });
  5481. }
  5482.  
  5483. /**
  5484. * Passing the tower
  5485. *
  5486. * Прохождение башни
  5487. */
  5488. function executeTower(resolve, reject) {
  5489. lastTowerInfo = {};
  5490.  
  5491. scullCoin = 0;
  5492.  
  5493. heroGetAll = [];
  5494.  
  5495. heroesStates = {};
  5496.  
  5497. argsBattle = {
  5498. heroes: [],
  5499. favor: {},
  5500. };
  5501.  
  5502. callsExecuteTower = {
  5503. calls: [{
  5504. name: "towerGetInfo",
  5505. args: {},
  5506. ident: "towerGetInfo"
  5507. }, {
  5508. name: "teamGetAll",
  5509. args: {},
  5510. ident: "teamGetAll"
  5511. }, {
  5512. name: "teamGetFavor",
  5513. args: {},
  5514. ident: "teamGetFavor"
  5515. }, {
  5516. name: "inventoryGet",
  5517. args: {},
  5518. ident: "inventoryGet"
  5519. }, {
  5520. name: "heroGetAll",
  5521. args: {},
  5522. ident: "heroGetAll"
  5523. }]
  5524. }
  5525.  
  5526. buffIds = [
  5527. {id: 0, cost: 0, isBuy: false}, // plug // заглушка
  5528. {id: 1, cost: 1, isBuy: true}, // 3% attack // 3% атака
  5529. {id: 2, cost: 6, isBuy: true}, // 2% attack // 2% атака
  5530. {id: 3, cost: 16, isBuy: true}, // 4% attack // 4% атака
  5531. {id: 4, cost: 40, isBuy: true}, // 8% attack // 8% атака
  5532. {id: 5, cost: 1, isBuy: true}, // 10% armor // 10% броня
  5533. {id: 6, cost: 6, isBuy: true}, // 5% armor // 5% броня
  5534. {id: 7, cost: 16, isBuy: true}, // 10% armor // 10% броня
  5535. {id: 8, cost: 40, isBuy: true}, // 20% armor // 20% броня
  5536. { id: 9, cost: 1, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5537. { id: 10, cost: 6, isBuy: true }, // 5% protection from magic // 5% защита от магии
  5538. { id: 11, cost: 16, isBuy: true }, // 10% protection from magic // 10% защита от магии
  5539. { id: 12, cost: 40, isBuy: true }, // 20% protection from magic // 20% защита от магии
  5540. { id: 13, cost: 1, isBuy: false }, // 40% health hero // 40% здоровья герою
  5541. { id: 14, cost: 6, isBuy: false }, // 40% health hero // 40% здоровья герою
  5542. { id: 15, cost: 16, isBuy: false }, // 80% health hero // 80% здоровья герою
  5543. { id: 16, cost: 40, isBuy: false }, // 40% health to all heroes // 40% здоровья всем героям
  5544. { id: 17, cost: 1, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5545. { id: 18, cost: 3, isBuy: false }, // 40% energy to the hero // 40% энергии герою
  5546. { id: 19, cost: 8, isBuy: false }, // 80% energy to the hero // 80% энергии герою
  5547. { id: 20, cost: 20, isBuy: false }, // 40% energy to all heroes // 40% энергии всем героям
  5548. { id: 21, cost: 40, isBuy: false }, // Hero Resurrection // Воскрешение героя
  5549. ]
  5550.  
  5551. this.start = function () {
  5552. send(JSON.stringify(callsExecuteTower), startTower);
  5553. }
  5554.  
  5555. /**
  5556. * Getting data on the Tower
  5557. *
  5558. * Получаем данные по башне
  5559. */
  5560. function startTower(e) {
  5561. res = e.results;
  5562. towerGetInfo = res[0].result.response;
  5563. if (!towerGetInfo) {
  5564. endTower('noTower', res);
  5565. return;
  5566. }
  5567. teamGetAll = res[1].result.response;
  5568. teamGetFavor = res[2].result.response;
  5569. inventoryGet = res[3].result.response;
  5570. heroGetAll = Object.values(res[4].result.response);
  5571.  
  5572. scullCoin = inventoryGet.coin[7] ?? 0;
  5573.  
  5574. argsBattle.favor = teamGetFavor.tower;
  5575. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5576. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  5577. if (pet) {
  5578. argsBattle.pet = pet;
  5579. }
  5580.  
  5581. checkFloor(towerGetInfo);
  5582. }
  5583.  
  5584. function fixHeroesTeam(argsBattle) {
  5585. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  5586. if (fixHeroes.length < 5) {
  5587. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  5588. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  5589. Object.keys(argsBattle.favor).forEach(e => {
  5590. if (!fixHeroes.includes(+e)) {
  5591. delete argsBattle.favor[e];
  5592. }
  5593. })
  5594. }
  5595. argsBattle.heroes = fixHeroes;
  5596. return argsBattle;
  5597. }
  5598.  
  5599. /**
  5600. * Check the floor
  5601. *
  5602. * Проверяем этаж
  5603. */
  5604. function checkFloor(towerInfo) {
  5605. lastTowerInfo = towerInfo;
  5606. maySkipFloor = +towerInfo.maySkipFloor;
  5607. floorNumber = +towerInfo.floorNumber;
  5608. heroesStates = towerInfo.states.heroes;
  5609. floorInfo = towerInfo.floor;
  5610.  
  5611. /**
  5612. * Is there at least one chest open on the floor
  5613. * Открыт ли на этаже хоть один сундук
  5614. */
  5615. isOpenChest = false;
  5616. if (towerInfo.floorType == "chest") {
  5617. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  5618. }
  5619.  
  5620. setProgress(`${I18N('TOWER')}: ${I18N('FLOOR')} ${floorNumber}`);
  5621. if (floorNumber > 49) {
  5622. if (isOpenChest) {
  5623. endTower('alreadyOpenChest 50 floor', floorNumber);
  5624. return;
  5625. }
  5626. }
  5627. /**
  5628. * If the chest is open and you can skip floors, then move on
  5629. * Если сундук открыт и можно скипать этажи, то переходим дальше
  5630. */
  5631. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  5632. if (isOpenChest) {
  5633. nextOpenChest(floorNumber);
  5634. } else {
  5635. nextChestOpen(floorNumber);
  5636. }
  5637. return;
  5638. }
  5639.  
  5640. // console.log(towerInfo, scullCoin);
  5641. switch (towerInfo.floorType) {
  5642. case "battle":
  5643. if (floorNumber <= maySkipFloor) {
  5644. skipFloor();
  5645. return;
  5646. }
  5647. if (floorInfo.state == 2) {
  5648. nextFloor();
  5649. return;
  5650. }
  5651. startBattle().then(endBattle);
  5652. return;
  5653. case "buff":
  5654. checkBuff(towerInfo);
  5655. return;
  5656. case "chest":
  5657. openChest(floorNumber);
  5658. return;
  5659. default:
  5660. console.log('!', towerInfo.floorType, towerInfo);
  5661. break;
  5662. }
  5663. }
  5664.  
  5665. /**
  5666. * Let's start the fight
  5667. *
  5668. * Начинаем бой
  5669. */
  5670. function startBattle() {
  5671. return new Promise(function (resolve, reject) {
  5672. towerStartBattle = {
  5673. calls: [{
  5674. name: "towerStartBattle",
  5675. args: fixHeroesTeam(argsBattle),
  5676. ident: "body"
  5677. }]
  5678. }
  5679. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  5680. });
  5681. }
  5682. /**
  5683. * Returns the result of the battle in a promise
  5684. *
  5685. * Возращает резульат боя в промис
  5686. */
  5687. function resultBattle(resultBattles, resolve) {
  5688. battleData = resultBattles.results[0].result.response;
  5689. battleType = "get_tower";
  5690. BattleCalc(battleData, battleType, function (result) {
  5691. resolve(result);
  5692. });
  5693. }
  5694. /**
  5695. * Finishing the fight
  5696. *
  5697. * Заканчиваем бой
  5698. */
  5699. function endBattle(battleInfo) {
  5700. if (battleInfo.result.stars >= 3) {
  5701. endBattleCall = {
  5702. calls: [{
  5703. name: "towerEndBattle",
  5704. args: {
  5705. result: battleInfo.result,
  5706. progress: battleInfo.progress,
  5707. },
  5708. ident: "body"
  5709. }]
  5710. }
  5711. send(JSON.stringify(endBattleCall), resultEndBattle);
  5712. } else {
  5713. endTower('towerEndBattle win: false\n', battleInfo);
  5714. }
  5715. }
  5716.  
  5717. /**
  5718. * Getting and processing battle results
  5719. *
  5720. * Получаем и обрабатываем результаты боя
  5721. */
  5722. function resultEndBattle(e) {
  5723. battleResult = e.results[0].result.response;
  5724. if ('error' in battleResult) {
  5725. endTower('errorBattleResult', battleResult);
  5726. return;
  5727. }
  5728. if ('reward' in battleResult) {
  5729. scullCoin += battleResult.reward?.coin[7] ?? 0;
  5730. }
  5731. nextFloor();
  5732. }
  5733.  
  5734. function nextFloor() {
  5735. nextFloorCall = {
  5736. calls: [{
  5737. name: "towerNextFloor",
  5738. args: {},
  5739. ident: "body"
  5740. }]
  5741. }
  5742. send(JSON.stringify(nextFloorCall), checkDataFloor);
  5743. }
  5744.  
  5745. function openChest(floorNumber) {
  5746. floorNumber = floorNumber || 0;
  5747. openChestCall = {
  5748. calls: [{
  5749. name: "towerOpenChest",
  5750. args: {
  5751. num: 2
  5752. },
  5753. ident: "body"
  5754. }]
  5755. }
  5756. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  5757. }
  5758.  
  5759. function lastChest() {
  5760. endTower('openChest 50 floor', floorNumber);
  5761. }
  5762.  
  5763. function skipFloor() {
  5764. skipFloorCall = {
  5765. calls: [{
  5766. name: "towerSkipFloor",
  5767. args: {},
  5768. ident: "body"
  5769. }]
  5770. }
  5771. send(JSON.stringify(skipFloorCall), checkDataFloor);
  5772. }
  5773.  
  5774. function checkBuff(towerInfo) {
  5775. buffArr = towerInfo.floor;
  5776. promises = [];
  5777. for (let buff of buffArr) {
  5778. buffInfo = buffIds[buff.id];
  5779. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  5780. scullCoin -= buffInfo.cost;
  5781. promises.push(buyBuff(buff.id));
  5782. }
  5783. }
  5784. Promise.all(promises).then(nextFloor);
  5785. }
  5786.  
  5787. function buyBuff(buffId) {
  5788. return new Promise(function (resolve, reject) {
  5789. buyBuffCall = {
  5790. calls: [{
  5791. name: "towerBuyBuff",
  5792. args: {
  5793. buffId
  5794. },
  5795. ident: "body"
  5796. }]
  5797. }
  5798. send(JSON.stringify(buyBuffCall), resolve);
  5799. });
  5800. }
  5801.  
  5802. function checkDataFloor(result) {
  5803. towerInfo = result.results[0].result.response;
  5804. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  5805. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  5806. }
  5807. if ('tower' in towerInfo) {
  5808. towerInfo = towerInfo.tower;
  5809. }
  5810. if ('skullReward' in towerInfo) {
  5811. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  5812. }
  5813. checkFloor(towerInfo);
  5814. }
  5815. /**
  5816. * Getting tower rewards
  5817. *
  5818. * Получаем награды башни
  5819. */
  5820. function farmTowerRewards(reason) {
  5821. let { pointRewards, points } = lastTowerInfo;
  5822. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  5823. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  5824. if (!farmPoints.length) {
  5825. return;
  5826. }
  5827. let farmTowerRewardsCall = {
  5828. calls: [{
  5829. name: "tower_farmPointRewards",
  5830. args: {
  5831. points: farmPoints
  5832. },
  5833. ident: "tower_farmPointRewards"
  5834. }]
  5835. }
  5836.  
  5837. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  5838. farmTowerRewardsCall.calls.push({
  5839. name: "tower_farmSkullReward",
  5840. args: {},
  5841. ident: "tower_farmSkullReward"
  5842. });
  5843. }
  5844.  
  5845. send(JSON.stringify(farmTowerRewardsCall), () => { });
  5846. }
  5847.  
  5848. function fullSkipTower() {
  5849. /**
  5850. * Next chest
  5851. *
  5852. * Следующий сундук
  5853. */
  5854. function nextChest(n) {
  5855. return {
  5856. name: "towerNextChest",
  5857. args: {},
  5858. ident: "group_" + n + "_body"
  5859. }
  5860. }
  5861. /**
  5862. * Open chest
  5863. *
  5864. * Открыть сундук
  5865. */
  5866. function openChest(n) {
  5867. return {
  5868. name: "towerOpenChest",
  5869. args: {
  5870. "num": 2
  5871. },
  5872. ident: "group_" + n + "_body"
  5873. }
  5874. }
  5875.  
  5876. const fullSkipTowerCall = {
  5877. calls: []
  5878. }
  5879.  
  5880. let n = 0;
  5881. for (let i = 0; i < 15; i++) {
  5882. fullSkipTowerCall.calls.push(nextChest(++n));
  5883. fullSkipTowerCall.calls.push(openChest(++n));
  5884. }
  5885.  
  5886. send(JSON.stringify(fullSkipTowerCall), data => {
  5887. data.results[0] = data.results[28];
  5888. checkDataFloor(data);
  5889. });
  5890. }
  5891.  
  5892. function nextChestOpen(floorNumber) {
  5893. const calls = [{
  5894. name: "towerOpenChest",
  5895. args: {
  5896. num: 2
  5897. },
  5898. ident: "towerOpenChest"
  5899. }];
  5900.  
  5901. Send(JSON.stringify({ calls })).then(e => {
  5902. nextOpenChest(floorNumber);
  5903. });
  5904. }
  5905.  
  5906. function nextOpenChest(floorNumber) {
  5907. if (floorNumber > 49) {
  5908. endTower('openChest 50 floor', floorNumber);
  5909. return;
  5910. }
  5911. if (floorNumber == 1) {
  5912. fullSkipTower();
  5913. return;
  5914. }
  5915.  
  5916. let nextOpenChestCall = {
  5917. calls: [{
  5918. name: "towerNextChest",
  5919. args: {},
  5920. ident: "towerNextChest"
  5921. }, {
  5922. name: "towerOpenChest",
  5923. args: {
  5924. num: 2
  5925. },
  5926. ident: "towerOpenChest"
  5927. }]
  5928. }
  5929. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  5930. }
  5931.  
  5932. function endTower(reason, info) {
  5933. console.log(reason, info);
  5934. if (reason != 'noTower') {
  5935. farmTowerRewards(reason);
  5936. }
  5937. setProgress(`${I18N('TOWER')} ${I18N('COMPLETED')}!`, true);
  5938. resolve();
  5939. }
  5940. }
  5941.  
  5942. /**
  5943. * Passage of the arena of the titans
  5944. *
  5945. * Прохождение арены титанов
  5946. */
  5947. function testTitanArena() {
  5948. return new Promise((resolve, reject) => {
  5949. titAren = new executeTitanArena(resolve, reject);
  5950. titAren.start();
  5951. });
  5952. }
  5953.  
  5954. /**
  5955. * Passage of the arena of the titans
  5956. *
  5957. * Прохождение арены титанов
  5958. */
  5959. function executeTitanArena(resolve, reject) {
  5960. let titan_arena = [];
  5961. let finishListBattle = [];
  5962. /**
  5963. * ID of the current batch
  5964. *
  5965. * Идетификатор текущей пачки
  5966. */
  5967. let currentRival = 0;
  5968. /**
  5969. * Number of attempts to finish off the pack
  5970. *
  5971. * Количество попыток добития пачки
  5972. */
  5973. let attempts = 0;
  5974. /**
  5975. * Was there an attempt to finish off the current shooting range
  5976. *
  5977. * Была ли попытка добития текущего тира
  5978. */
  5979. let isCheckCurrentTier = false;
  5980. /**
  5981. * Current shooting range
  5982. *
  5983. * Текущий тир
  5984. */
  5985. let currTier = 0;
  5986. /**
  5987. * Number of battles on the current dash
  5988. *
  5989. * Количество битв на текущем тире
  5990. */
  5991. let countRivalsTier = 0;
  5992.  
  5993. let callsStart = {
  5994. calls: [{
  5995. name: "titanArenaGetStatus",
  5996. args: {},
  5997. ident: "titanArenaGetStatus"
  5998. }, {
  5999. name: "teamGetAll",
  6000. args: {},
  6001. ident: "teamGetAll"
  6002. }]
  6003. }
  6004.  
  6005. this.start = function () {
  6006. send(JSON.stringify(callsStart), startTitanArena);
  6007. }
  6008.  
  6009. function startTitanArena(data) {
  6010. let titanArena = data.results[0].result.response;
  6011. if (titanArena.status == 'disabled') {
  6012. endTitanArena('disabled', titanArena);
  6013. return;
  6014. }
  6015.  
  6016. let teamGetAll = data.results[1].result.response;
  6017. titan_arena = teamGetAll.titan_arena;
  6018.  
  6019. checkTier(titanArena)
  6020. }
  6021.  
  6022. function checkTier(titanArena) {
  6023. if (titanArena.status == "peace_time") {
  6024. endTitanArena('Peace_time', titanArena);
  6025. return;
  6026. }
  6027. currTier = titanArena.tier;
  6028. if (currTier) {
  6029. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier}`);
  6030. }
  6031.  
  6032. if (titanArena.status == "completed_tier") {
  6033. titanArenaCompleteTier();
  6034. return;
  6035. }
  6036. /**
  6037. * Checking for the possibility of a raid
  6038. * Проверка на возможность рейда
  6039. */
  6040. if (titanArena.canRaid) {
  6041. titanArenaStartRaid();
  6042. return;
  6043. }
  6044. /**
  6045. * Check was an attempt to achieve the current shooting range
  6046. * Проверка была ли попытка добития текущего тира
  6047. */
  6048. if (!isCheckCurrentTier) {
  6049. checkRivals(titanArena.rivals);
  6050. return;
  6051. }
  6052.  
  6053. endTitanArena('Done or not canRaid', titanArena);
  6054. }
  6055. /**
  6056. * Submit dash information for verification
  6057. *
  6058. * Отправка информации о тире на проверку
  6059. */
  6060. function checkResultInfo(data) {
  6061. let titanArena = data.results[0].result.response;
  6062. checkTier(titanArena);
  6063. }
  6064. /**
  6065. * Finish the current tier
  6066. *
  6067. * Завершить текущий тир
  6068. */
  6069. function titanArenaCompleteTier() {
  6070. isCheckCurrentTier = false;
  6071. let calls = [{
  6072. name: "titanArenaCompleteTier",
  6073. args: {},
  6074. ident: "body"
  6075. }];
  6076. send(JSON.stringify({calls}), checkResultInfo);
  6077. }
  6078. /**
  6079. * Gathering points to be completed
  6080. *
  6081. * Собираем точки которые нужно добить
  6082. */
  6083. function checkRivals(rivals) {
  6084. finishListBattle = [];
  6085. for (let n in rivals) {
  6086. if (rivals[n].attackScore < 250) {
  6087. finishListBattle.push(n);
  6088. }
  6089. }
  6090. console.log('checkRivals', finishListBattle);
  6091. countRivalsTier = finishListBattle.length;
  6092. roundRivals();
  6093. }
  6094. /**
  6095. * Selecting the next point to finish off
  6096. *
  6097. * Выбор следующей точки для добития
  6098. */
  6099. function roundRivals() {
  6100. let countRivals = finishListBattle.length;
  6101. if (!countRivals) {
  6102. /**
  6103. * Whole range checked
  6104. *
  6105. * Весь тир проверен
  6106. */
  6107. isCheckCurrentTier = true;
  6108. titanArenaGetStatus();
  6109. return;
  6110. }
  6111. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  6112. currentRival = finishListBattle.pop();
  6113. attempts = +currentRival;
  6114. // console.log('roundRivals', currentRival);
  6115. titanArenaStartBattle(currentRival);
  6116. }
  6117. /**
  6118. * The start of a solo battle
  6119. *
  6120. * Начало одиночной битвы
  6121. */
  6122. function titanArenaStartBattle(rivalId) {
  6123. let calls = [{
  6124. name: "titanArenaStartBattle",
  6125. args: {
  6126. rivalId: rivalId,
  6127. titans: titan_arena
  6128. },
  6129. ident: "body"
  6130. }];
  6131. send(JSON.stringify({calls}), calcResult);
  6132. }
  6133. /**
  6134. * Calculation of the results of the battle
  6135. *
  6136. * Расчет результатов боя
  6137. */
  6138. function calcResult(data) {
  6139. let battlesInfo = data.results[0].result.response.battle;
  6140. /**
  6141. * If attempts are equal to the current battle number we make
  6142. * Если попытки равны номеру текущего боя делаем прерасчет
  6143. */
  6144. if (attempts == currentRival) {
  6145. preCalcBattle(battlesInfo);
  6146. return;
  6147. }
  6148. /**
  6149. * If there are still attempts, we calculate a new battle
  6150. * Если попытки еще есть делаем расчет нового боя
  6151. */
  6152. if (attempts > 0) {
  6153. attempts--;
  6154. calcBattleResult(battlesInfo)
  6155. .then(resultCalcBattle);
  6156. return;
  6157. }
  6158. /**
  6159. * Otherwise, go to the next opponent
  6160. * Иначе переходим к следующему сопернику
  6161. */
  6162. roundRivals();
  6163. }
  6164. /**
  6165. * Processing the results of the battle calculation
  6166. *
  6167. * Обработка результатов расчета битвы
  6168. */
  6169. function resultCalcBattle(resultBattle) {
  6170. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  6171. /**
  6172. * If the current calculation of victory is not a chance or the attempt ended with the finish the battle
  6173. * Если текущий расчет победа или шансов нет или попытки кончились завершаем бой
  6174. */
  6175. if (resultBattle.result.win || !attempts) {
  6176. titanArenaEndBattle({
  6177. progress: resultBattle.progress,
  6178. result: resultBattle.result,
  6179. rivalId: resultBattle.battleData.typeId
  6180. });
  6181. return;
  6182. }
  6183. /**
  6184. * If not victory and there are attempts we start a new battle
  6185. * Если не победа и есть попытки начинаем новый бой
  6186. */
  6187. titanArenaStartBattle(resultBattle.battleData.typeId);
  6188. }
  6189. /**
  6190. * Returns the promise of calculating the results of the battle
  6191. *
  6192. * Возращает промис расчета результатов битвы
  6193. */
  6194. function getBattleInfo(battle, isRandSeed) {
  6195. return new Promise(function (resolve) {
  6196. if (isRandSeed) {
  6197. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  6198. }
  6199. // console.log(battle.seed);
  6200. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  6201. });
  6202. }
  6203. /**
  6204. * Recalculate battles
  6205. *
  6206. * Прерасчтет битвы
  6207. */
  6208. function preCalcBattle(battle) {
  6209. let actions = [getBattleInfo(battle, false)];
  6210. const countTestBattle = getInput('countTestBattle');
  6211. for (let i = 0; i < countTestBattle; i++) {
  6212. actions.push(getBattleInfo(battle, true));
  6213. }
  6214. Promise.all(actions)
  6215. .then(resultPreCalcBattle);
  6216. }
  6217. /**
  6218. * Processing the results of the battle recalculation
  6219. *
  6220. * Обработка результатов прерасчета битвы
  6221. */
  6222. function resultPreCalcBattle(e) {
  6223. let wins = e.map(n => n.result.win);
  6224. let firstBattle = e.shift();
  6225. let countWin = wins.reduce((w, s) => w + s);
  6226. const countTestBattle = getInput('countTestBattle');
  6227. console.log('resultPreCalcBattle', `${countWin}/${countTestBattle}`)
  6228. if (countWin > 0) {
  6229. attempts = getInput('countAutoBattle');
  6230. } else {
  6231. attempts = 0;
  6232. }
  6233. resultCalcBattle(firstBattle);
  6234. }
  6235.  
  6236. /**
  6237. * Complete an arena battle
  6238. *
  6239. * Завершить битву на арене
  6240. */
  6241. function titanArenaEndBattle(args) {
  6242. let calls = [{
  6243. name: "titanArenaEndBattle",
  6244. args,
  6245. ident: "body"
  6246. }];
  6247. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  6248. }
  6249.  
  6250. function resultTitanArenaEndBattle(e) {
  6251. let attackScore = e.results[0].result.response.attackScore;
  6252. let numReval = countRivalsTier - finishListBattle.length;
  6253. setProgress(`${I18N('TITAN_ARENA')}: ${I18N('LEVEL')} ${currTier} </br>${I18N('BATTLES')}: ${numReval}/${countRivalsTier} - ${attackScore}`);
  6254. /**
  6255. * TODO: Might need to improve the results.
  6256. * TODO: Возможно стоит сделать улучшение результатов
  6257. */
  6258. // console.log('resultTitanArenaEndBattle', e)
  6259. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  6260. roundRivals();
  6261. }
  6262. /**
  6263. * Arena State
  6264. *
  6265. * Состояние арены
  6266. */
  6267. function titanArenaGetStatus() {
  6268. let calls = [{
  6269. name: "titanArenaGetStatus",
  6270. args: {},
  6271. ident: "body"
  6272. }];
  6273. send(JSON.stringify({calls}), checkResultInfo);
  6274. }
  6275. /**
  6276. * Arena Raid Request
  6277. *
  6278. * Запрос рейда арены
  6279. */
  6280. function titanArenaStartRaid() {
  6281. let calls = [{
  6282. name: "titanArenaStartRaid",
  6283. args: {
  6284. titans: titan_arena
  6285. },
  6286. ident: "body"
  6287. }];
  6288. send(JSON.stringify({calls}), calcResults);
  6289. }
  6290.  
  6291. function calcResults(data) {
  6292. let battlesInfo = data.results[0].result.response;
  6293. let {attackers, rivals} = battlesInfo;
  6294.  
  6295. let promises = [];
  6296. for (let n in rivals) {
  6297. rival = rivals[n];
  6298. promises.push(calcBattleResult({
  6299. attackers: attackers,
  6300. defenders: [rival.team],
  6301. seed: rival.seed,
  6302. typeId: n,
  6303. }));
  6304. }
  6305.  
  6306. Promise.all(promises)
  6307. .then(results => {
  6308. const endResults = {};
  6309. for (let info of results) {
  6310. let id = info.battleData.typeId;
  6311. endResults[id] = {
  6312. progress: info.progress,
  6313. result: info.result,
  6314. }
  6315. }
  6316. titanArenaEndRaid(endResults);
  6317. });
  6318. }
  6319.  
  6320. function calcBattleResult(battleData) {
  6321. return new Promise(function (resolve, reject) {
  6322. BattleCalc(battleData, "get_titanClanPvp", resolve);
  6323. });
  6324. }
  6325.  
  6326. /**
  6327. * Sending Raid Results
  6328. *
  6329. * Отправка результатов рейда
  6330. */
  6331. function titanArenaEndRaid(results) {
  6332. titanArenaEndRaidCall = {
  6333. calls: [{
  6334. name: "titanArenaEndRaid",
  6335. args: {
  6336. results
  6337. },
  6338. ident: "body"
  6339. }]
  6340. }
  6341. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  6342. }
  6343.  
  6344. function checkRaidResults(data) {
  6345. results = data.results[0].result.response.results;
  6346. isSucsesRaid = true;
  6347. for (let i in results) {
  6348. isSucsesRaid &&= (results[i].attackScore >= 250);
  6349. }
  6350.  
  6351. if (isSucsesRaid) {
  6352. titanArenaCompleteTier();
  6353. } else {
  6354. titanArenaGetStatus();
  6355. }
  6356. }
  6357.  
  6358. function titanArenaFarmDailyReward() {
  6359. titanArenaFarmDailyRewardCall = {
  6360. calls: [{
  6361. name: "titanArenaFarmDailyReward",
  6362. args: {},
  6363. ident: "body"
  6364. }]
  6365. }
  6366. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  6367. }
  6368.  
  6369. function endTitanArena(reason, info) {
  6370. if (!['Peace_time', 'disabled'].includes(reason)) {
  6371. titanArenaFarmDailyReward();
  6372. }
  6373. console.log(reason, info);
  6374. setProgress(`${I18N('TITAN_ARENA')} ${I18N('COMPLETED')}!`, true);
  6375. resolve();
  6376. }
  6377. }
  6378.  
  6379. function hackGame() {
  6380. const self = this;
  6381. selfGame = null;
  6382. bindId = 1e9;
  6383. this.libGame = null;
  6384.  
  6385. /**
  6386. * List of correspondence of used classes to their names
  6387. *
  6388. * Список соответствия используемых классов их названиям
  6389. */
  6390. ObjectsList = [
  6391. { name: 'BattlePresets', prop: 'game.battle.controller.thread.BattlePresets' },
  6392. { name: 'DataStorage', prop: 'game.data.storage.DataStorage' },
  6393. { name: 'BattleConfigStorage', prop: 'game.data.storage.battle.BattleConfigStorage' },
  6394. { name: 'BattleInstantPlay', prop: 'game.battle.controller.instant.BattleInstantPlay' },
  6395. { name: 'MultiBattleInstantReplay', prop: 'game.battle.controller.instant.MultiBattleInstantReplay' },
  6396. { name: 'MultiBattleResult', prop: 'game.battle.controller.MultiBattleResult' },
  6397. { name: 'PlayerMissionData', prop: 'game.model.user.mission.PlayerMissionData' },
  6398. { name: 'PlayerMissionBattle', prop: 'game.model.user.mission.PlayerMissionBattle' },
  6399. { name: 'GameModel', prop: 'game.model.GameModel' },
  6400. { name: 'CommandManager', prop: 'game.command.CommandManager' },
  6401. { name: 'MissionCommandList', prop: 'game.command.rpc.mission.MissionCommandList' },
  6402. { name: 'RPCCommandBase', prop: 'game.command.rpc.RPCCommandBase' },
  6403. { name: 'PlayerTowerData', prop: 'game.model.user.tower.PlayerTowerData' },
  6404. { name: 'TowerCommandList', prop: 'game.command.tower.TowerCommandList' },
  6405. { name: 'PlayerHeroTeamResolver', prop: 'game.model.user.hero.PlayerHeroTeamResolver' },
  6406. { name: 'BattlePausePopup', prop: 'game.view.popup.battle.BattlePausePopup' },
  6407. { name: 'BattlePopup', prop: 'game.view.popup.battle.BattlePopup' },
  6408. { name: 'DisplayObjectContainer', prop: 'starling.display.DisplayObjectContainer' },
  6409. { name: 'GuiClipContainer', prop: 'engine.core.clipgui.GuiClipContainer' },
  6410. { name: 'BattlePausePopupClip', prop: 'game.view.popup.battle.BattlePausePopupClip' },
  6411. { name: 'ClipLabel', prop: 'game.view.gui.components.ClipLabel' },
  6412. { name: 'ClipLabelBase', prop: 'game.view.gui.components.ClipLabelBase' },
  6413. { name: 'Translate', prop: 'com.progrestar.common.lang.Translate' },
  6414. { name: 'ClipButtonLabeledCentered', prop: 'game.view.gui.components.ClipButtonLabeledCentered' },
  6415. { name: 'BattlePausePopupMediator', prop: 'game.mediator.gui.popup.battle.BattlePausePopupMediator' },
  6416. { name: 'SettingToggleButton', prop: 'game.mechanics.settings.popup.view.SettingToggleButton' },
  6417. { name: 'PlayerDungeonData', prop: 'game.mechanics.dungeon.model.PlayerDungeonData' },
  6418. { name: 'NextDayUpdatedManager', prop: 'game.model.user.NextDayUpdatedManager' },
  6419. { name: 'BattleController', prop: 'game.battle.controller.BattleController' },
  6420. { name: 'BattleSettingsModel', prop: 'game.battle.controller.BattleSettingsModel' },
  6421. { name: 'BooleanProperty', prop: 'engine.core.utils.property.BooleanProperty' },
  6422. { name: 'RuleStorage', prop: 'game.data.storage.rule.RuleStorage' },
  6423. { name: 'BattleConfig', prop: 'battle.BattleConfig' },
  6424. { name: 'BattleGuiMediator', prop: 'game.battle.gui.BattleGuiMediator' },
  6425. { name: 'BooleanPropertyWriteable', prop: 'engine.core.utils.property.BooleanPropertyWriteable' },
  6426. { name: 'BattleLogEncoder', prop: 'battle.log.BattleLogEncoder' },
  6427. { name: 'BattleLogReader', prop: 'battle.log.BattleLogReader' },
  6428. { name: 'PlayerSubscriptionInfoValueObject', prop: 'game.model.user.subscription.PlayerSubscriptionInfoValueObject' },
  6429. { name: 'AdventureMapCamera', prop: 'game.mechanics.adventure.popup.map.AdventureMapCamera' },
  6430. { name: 'SendReplayPopUp', prop: 'game.mediator.gui.popup.chat.sendreplay.SendReplayPopUp' }, //полное окно реплей на вг
  6431. ];
  6432.  
  6433. /**
  6434. * Contains the game classes needed to write and override game methods
  6435. *
  6436. * Содержит классы игры необходимые для написания и подмены методов игры
  6437. */
  6438. Game = {
  6439. /**
  6440. * Function 'e'
  6441. * Функция 'e'
  6442. */
  6443. bindFunc: function (a, b) {
  6444. if (null == b)
  6445. return null;
  6446. null == b.__id__ && (b.__id__ = bindId++);
  6447. var c;
  6448. null == a.hx__closures__ ? a.hx__closures__ = {} :
  6449. c = a.hx__closures__[b.__id__];
  6450. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  6451. return c
  6452. },
  6453. };
  6454.  
  6455. /**
  6456. * Connects to game objects via the object creation event
  6457. *
  6458. * Подключается к объектам игры через событие создания объекта
  6459. */
  6460. function connectGame() {
  6461. for (let obj of ObjectsList) {
  6462. /**
  6463. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  6464. */
  6465. Object.defineProperty(Object.prototype, obj.prop, {
  6466. set: function (value) {
  6467. if (!selfGame) {
  6468. selfGame = this;
  6469. }
  6470. if (!Game[obj.name]) {
  6471. Game[obj.name] = value;
  6472. }
  6473. // console.log('set ' + obj.prop, this, value);
  6474. this[obj.prop + '_'] = value;
  6475. },
  6476. get: function () {
  6477. // console.log('get ' + obj.prop, this);
  6478. return this[obj.prop + '_'];
  6479. }
  6480. });
  6481. }
  6482. }
  6483.  
  6484. /**
  6485. * Game.BattlePresets
  6486. * @param {bool} a isReplay
  6487. * @param {bool} b autoToggleable
  6488. * @param {bool} c auto On Start
  6489. * @param {object} d config
  6490. * @param {bool} f showBothTeams
  6491. */
  6492. /**
  6493. * Returns the results of the battle to the callback function
  6494. * Возвращает в функцию callback результаты боя
  6495. * @param {*} battleData battle data данные боя
  6496. * @param {*} battleConfig combat configuration type options:
  6497. *
  6498. * тип конфигурации боя варианты:
  6499. *
  6500. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  6501. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  6502. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  6503. *
  6504. * You can specify the xYc function in the game.assets.storage.BattleAssetStorage class
  6505. *
  6506. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  6507. * @param {*} callback функция в которую вернуться результаты боя
  6508. */
  6509. this.BattleCalc = function (battleData, battleConfig, callback) {
  6510. // battleConfig = battleConfig || getBattleType(battleData.type)
  6511. if (!Game.BattlePresets) throw Error('Use connectGame');
  6512. battlePresets = new Game.BattlePresets(battleData.progress, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 24)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  6513. let battleInstantPlay;
  6514. if (battleData.progress?.length > 1) {
  6515. battleInstantPlay = new Game.MultiBattleInstantReplay(battleData, battlePresets);
  6516. } else {
  6517. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  6518. }
  6519. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 9)].add((battleInstant) => {
  6520. const MBR_2 = getProtoFn(Game.MultiBattleResult, 2);
  6521. const battleResults = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  6522. const battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  6523. const battleLogs = [];
  6524. const timeLimit = battlePresets[getF(Game.BattlePresets, 'get_timeLimit')]();
  6525. let battleTime = 0;
  6526. let battleTimer = 0;
  6527. for (const battleResult of battleResults[MBR_2]) {
  6528. const battleLog = Game.BattleLogEncoder.read(new Game.BattleLogReader(battleResult));
  6529. battleLogs.push(battleLog);
  6530. const maxTime = Math.max(...battleLog.map((e) => (e.time < timeLimit && e.time !== 168.8 ? e.time : 0)));
  6531. battleTimer += getTimer(maxTime)
  6532. battleTime += maxTime;
  6533. }
  6534. callback({
  6535. battleLogs,
  6536. battleTime,
  6537. battleTimer,
  6538. battleData,
  6539. progress: battleResults[getF(Game.MultiBattleResult, 'get_progress')](),
  6540. result: battleResults[getF(Game.MultiBattleResult, 'get_result')](),
  6541. });
  6542. });
  6543. battleInstantPlay.start();
  6544. }
  6545.  
  6546. /**
  6547. * Returns a function with the specified name from the class
  6548. *
  6549. * Возвращает из класса функцию с указанным именем
  6550. * @param {Object} classF Class // класс
  6551. * @param {String} nameF function name // имя функции
  6552. * @param {String} pos name and alias order // порядок имени и псевдонима
  6553. * @returns
  6554. */
  6555. function getF(classF, nameF, pos) {
  6556. pos = pos || false;
  6557. let prop = Object.entries(classF.prototype.__properties__)
  6558. if (!pos) {
  6559. return prop.filter((e) => e[1] == nameF).pop()[0];
  6560. } else {
  6561. return prop.filter((e) => e[0] == nameF).pop()[1];
  6562. }
  6563. }
  6564.  
  6565. /**
  6566. * Returns a function with the specified name from the class
  6567. *
  6568. * Возвращает из класса функцию с указанным именем
  6569. * @param {Object} classF Class // класс
  6570. * @param {String} nameF function name // имя функции
  6571. * @returns
  6572. */
  6573. function getFnP(classF, nameF) {
  6574. let prop = Object.entries(classF.__properties__)
  6575. return prop.filter((e) => e[1] == nameF).pop()[0];
  6576. }
  6577.  
  6578. /**
  6579. * Returns the function name with the specified ordinal from the class
  6580. *
  6581. * Возвращает имя функции с указаным порядковым номером из класса
  6582. * @param {Object} classF Class // класс
  6583. * @param {Number} nF Order number of function // порядковый номер функции
  6584. * @returns
  6585. */
  6586. function getFn(classF, nF) {
  6587. let prop = Object.keys(classF);
  6588. return prop[nF];
  6589. }
  6590.  
  6591. /**
  6592. * Returns the name of the function with the specified serial number from the prototype of the class
  6593. *
  6594. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  6595. * @param {Object} classF Class // класс
  6596. * @param {Number} nF Order number of function // порядковый номер функции
  6597. * @returns
  6598. */
  6599. function getProtoFn(classF, nF) {
  6600. let prop = Object.keys(classF.prototype);
  6601. return prop[nF];
  6602. }
  6603. /**
  6604. * Description of replaced functions
  6605. *
  6606. * Описание подменяемых функций
  6607. */
  6608. replaceFunction = {
  6609. company: function () {
  6610. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  6611. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  6612. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  6613. if (!isChecked('passBattle')) {
  6614. oldSkipMisson.call(this, a, b, c);
  6615. return;
  6616. }
  6617.  
  6618. try {
  6619. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  6620.  
  6621. var a = new Game.BattlePresets(
  6622. !1,
  6623. !1,
  6624. !0,
  6625. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6626. !1
  6627. );
  6628. a = new Game.BattleInstantPlay(c, a);
  6629. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6630. a.start();
  6631. } catch (error) {
  6632. console.error('company', error);
  6633. oldSkipMisson.call(this, a, b, c);
  6634. }
  6635. };
  6636.  
  6637. Game.PlayerMissionData.prototype.P$h = function (a) {
  6638. let GM_2 = getFn(Game.GameModel, 2);
  6639. let GM_P2 = getProtoFn(Game.GameModel, 2);
  6640. let CM_20 = getProtoFn(Game.CommandManager, 20);
  6641. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  6642. let MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6643. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 16);
  6644. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  6645. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]));
  6646. };
  6647. },
  6648. /*
  6649. tower: function () {
  6650. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  6651. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  6652. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  6653. if (!isChecked('passBattle')) {
  6654. oldSkipTower.call(this, a);
  6655. return;
  6656. }
  6657. try {
  6658. var p = new Game.BattlePresets(
  6659. !1,
  6660. !1,
  6661. !0,
  6662. Game.DataStorage[getFn(Game.DataStorage, 24)][getProtoFn(Game.BattleConfigStorage, 20)](),
  6663. !1
  6664. );
  6665. a = new Game.BattleInstantPlay(a, p);
  6666. a[getProtoFn(Game.BattleInstantPlay, 9)].add(Game.bindFunc(this, this.P$h));
  6667. a.start();
  6668. } catch (error) {
  6669. console.error('tower', error);
  6670. oldSkipMisson.call(this, a, b, c);
  6671. }
  6672. };
  6673.  
  6674. Game.PlayerTowerData.prototype.P$h = function (a) {
  6675. const GM_2 = getFnP(Game.GameModel, 'get_instance');
  6676. const GM_P2 = getProtoFn(Game.GameModel, 2);
  6677. const CM_29 = getProtoFn(Game.CommandManager, 29);
  6678. const TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  6679. const MBR_15 = getF(Game.MultiBattleResult, 'get_result');
  6680. const RPCCB_15 = getProtoFn(Game.RPCCommandBase, 17);
  6681. const PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  6682. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]));
  6683. };
  6684. },
  6685. */
  6686. // skipSelectHero: function() {
  6687. // if (!HOST) throw Error('Use connectGame');
  6688. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  6689. // },
  6690. // кнопка пропустить
  6691. passBattle: function () {
  6692. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  6693. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  6694. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  6695. if (!isChecked('passBattle')) {
  6696. oldPassBattle.call(this, a);
  6697. return;
  6698. }
  6699. try {
  6700. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  6701. this[getProtoFn(Game.BattlePausePopup, 3)]();
  6702. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  6703. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabelBase, 9)](
  6704. Game.Translate.translate('UI_POPUP_BATTLE_PAUSE')
  6705. );
  6706. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6707. Game.Translate.translate('UI_POPUP_BATTLE_RETREAT'),
  6708. ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 17)]))
  6709. );
  6710. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  6711. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 14)](),
  6712. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 13)]()
  6713. ? ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6714. : ((q = this[getProtoFn(Game.BattlePausePopup, 1)]), Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 18)]))
  6715. );
  6716. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][
  6717. getProtoFn(Game.ClipLabelBase, 24)
  6718. ]();
  6719. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](
  6720. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]()
  6721. );
  6722. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](
  6723. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 10)]()
  6724. );
  6725. this.clip[getProtoFn(Game.BattlePausePopupClip, 6)][getProtoFn(Game.SettingToggleButton, 3)](
  6726. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]()
  6727. );
  6728. } catch (error) {
  6729. console.error('passBattle', error);
  6730. oldPassBattle.call(this, a);
  6731. }
  6732. };
  6733. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, 'get_retreatButtonLabel');
  6734. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  6735. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  6736. if (isChecked('passBattle')) {
  6737. return I18N('BTN_PASS');
  6738. } else {
  6739. return oldFunc.call(this);
  6740. }
  6741. };
  6742. },
  6743. endlessCards: function () {
  6744. let PDD_21 = getProtoFn(Game.PlayerDungeonData, 21);
  6745. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_21];
  6746. Game.PlayerDungeonData.prototype[PDD_21] = function () {
  6747. if (countPredictionCard <= 0) {
  6748. return true;
  6749. } else {
  6750. return oldEndlessCards.call(this);
  6751. }
  6752. };
  6753. },
  6754. speedBattle: function () {
  6755. const get_timeScale = getF(Game.BattleController, 'get_timeScale');
  6756. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  6757. Game.BattleController.prototype[get_timeScale] = function () {
  6758. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  6759. if (!speedBattle) {
  6760. return oldSpeedBattle.call(this);
  6761. }
  6762. try {
  6763. const BC_12 = getProtoFn(Game.BattleController, 12);
  6764. const BSM_12 = getProtoFn(Game.BattleSettingsModel, 12);
  6765. const BP_get_value = getF(Game.BooleanProperty, 'get_value');
  6766. if (this[BC_12][BSM_12][BP_get_value]()) {
  6767. return 0;
  6768. }
  6769. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  6770. const BC_49 = getProtoFn(Game.BattleController, 49);
  6771. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  6772. const BC_14 = getProtoFn(Game.BattleController, 14);
  6773. const BC_3 = getFn(Game.BattleController, 3);
  6774. if (this[BC_12][BSM_2][BP_get_value]()) {
  6775. var a = speedBattle * this[BC_49]();
  6776. } else {
  6777. a = this[BC_12][BSM_1][BP_get_value]();
  6778. const maxSpeed = Math.max(...this[BC_14]);
  6779. const multiple = a == this[BC_14].indexOf(maxSpeed) ? (maxSpeed >= 4 ? speedBattle : this[BC_14][a]) : this[BC_14][a];
  6780. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_49]();
  6781. }
  6782. const BSM_24 = getProtoFn(Game.BattleSettingsModel, 24);
  6783. a > this[BC_12][BSM_24][BP_get_value]() && (a = this[BC_12][BSM_24][BP_get_value]());
  6784. const DS_23 = getFn(Game.DataStorage, 23);
  6785. const get_battleSpeedMultiplier = getF(Game.RuleStorage, 'get_battleSpeedMultiplier', true);
  6786. var b = Game.DataStorage[DS_23][get_battleSpeedMultiplier]();
  6787. const R_1 = getFn(selfGame.Reflect, 1);
  6788. const BC_1 = getFn(Game.BattleController, 1);
  6789. const get_config = getF(Game.BattlePresets, 'get_config');
  6790. null != b &&
  6791. (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  6792. ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident)
  6793. : a * selfGame.Reflect[R_1](b, 'default'));
  6794. return a;
  6795. } catch (error) {
  6796. console.error('passBatspeedBattletle', error);
  6797. return oldSpeedBattle.call(this);
  6798. }
  6799. };
  6800. },
  6801.  
  6802. /**
  6803. * Acceleration button without Valkyries favor
  6804. *
  6805. * Кнопка ускорения без Покровительства Валькирий
  6806. */
  6807. battleFastKey: function () {
  6808. const PSIVO_9 = getProtoFn(Game.PlayerSubscriptionInfoValueObject, 9);
  6809. const oldBattleFastKey = Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9];
  6810. Game.PlayerSubscriptionInfoValueObject.prototype[PSIVO_9] = function () {
  6811. //const BGM_44 = getProtoFn(Game.BattleGuiMediator, 44);
  6812. //const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_44];
  6813. //Game.BattleGuiMediator.prototype[BGM_44] = function () {
  6814. let flag = true;
  6815. //console.log(flag)
  6816. if (flag) {
  6817. return true;
  6818. } else {
  6819. return oldBattleFastKey.call(this);
  6820. }
  6821. };
  6822. },
  6823. fastSeason: function () {
  6824. const GameNavigator = selfGame['game.screen.navigator.GameNavigator'];
  6825. const oldFuncName = getProtoFn(GameNavigator, 18);
  6826. const newFuncName = getProtoFn(GameNavigator, 16);
  6827. const oldFastSeason = GameNavigator.prototype[oldFuncName];
  6828. const newFastSeason = GameNavigator.prototype[newFuncName];
  6829. GameNavigator.prototype[oldFuncName] = function (a, b) {
  6830. if (isChecked('fastSeason')) {
  6831. return newFastSeason.apply(this, [a]);
  6832. } else {
  6833. return oldFastSeason.apply(this, [a, b]);
  6834. }
  6835. };
  6836. },
  6837. ShowChestReward: function () {
  6838. const TitanArtifactChest = selfGame['game.mechanics.titan_arena.mediator.chest.TitanArtifactChestRewardPopupMediator'];
  6839. const getOpenAmountTitan = getF(TitanArtifactChest, 'get_openAmount');
  6840. const oldGetOpenAmountTitan = TitanArtifactChest.prototype[getOpenAmountTitan];
  6841. TitanArtifactChest.prototype[getOpenAmountTitan] = function () {
  6842. if (correctShowOpenArtifact) {
  6843. correctShowOpenArtifact--;
  6844. return 100;
  6845. }
  6846. return oldGetOpenAmountTitan.call(this);
  6847. };
  6848.  
  6849. const ArtifactChest = selfGame['game.view.popup.artifactchest.rewardpopup.ArtifactChestRewardPopupMediator'];
  6850. const getOpenAmount = getF(ArtifactChest, 'get_openAmount');
  6851. const oldGetOpenAmount = ArtifactChest.prototype[getOpenAmount];
  6852. ArtifactChest.prototype[getOpenAmount] = function () {
  6853. if (correctShowOpenArtifact) {
  6854. correctShowOpenArtifact--;
  6855. return 100;
  6856. }
  6857. return oldGetOpenAmount.call(this);
  6858. };
  6859.  
  6860. },
  6861. fixCompany: function () {
  6862. const GameBattleView = selfGame['game.mediator.gui.popup.battle.GameBattleView'];
  6863. const BattleThread = selfGame['game.battle.controller.thread.BattleThread'];
  6864. const getOnViewDisposed = getF(BattleThread, 'get_onViewDisposed');
  6865. const getThread = getF(GameBattleView, 'get_thread');
  6866. const oldFunc = GameBattleView.prototype[getThread];
  6867. GameBattleView.prototype[getThread] = function () {
  6868. return (
  6869. oldFunc.call(this) || {
  6870. [getOnViewDisposed]: async () => {},
  6871. }
  6872. );
  6873. };
  6874. },
  6875. BuyTitanArtifact: function () {
  6876. const BIP_4 = getProtoFn(selfGame['game.view.popup.shop.buy.BuyItemPopup'], 4);
  6877. const BuyItemPopup = selfGame['game.view.popup.shop.buy.BuyItemPopup'];
  6878. const oldFunc = BuyItemPopup.prototype[BIP_4];
  6879. BuyItemPopup.prototype[BIP_4] = function () {
  6880. if (isChecked('countControl')) {
  6881. const BuyTitanArtifactItemPopup = selfGame['game.view.popup.shop.buy.BuyTitanArtifactItemPopup'];
  6882. const BTAP_0 = getProtoFn(BuyTitanArtifactItemPopup, 0);
  6883. if (this[BTAP_0]) {
  6884. const BuyTitanArtifactPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyTitanArtifactItemPopupMediator'];
  6885. const BTAM_1 = getProtoFn(BuyTitanArtifactPopupMediator, 1);
  6886. const BuyItemPopupMediator = selfGame['game.mediator.gui.popup.shop.buy.BuyItemPopupMediator'];
  6887. const BIPM_5 = getProtoFn(BuyItemPopupMediator, 5);
  6888. const BIPM_7 = getProtoFn(BuyItemPopupMediator, 7);
  6889. const BIPM_9 = getProtoFn(BuyItemPopupMediator, 9);
  6890.  
  6891. let need = Math.min(this[BTAP_0][BTAM_1](), this[BTAP_0][BIPM_7]);
  6892. need = need ? need : 60;
  6893. this[BTAP_0][BIPM_9] = need;
  6894. this[BTAP_0][BIPM_5] = 10;
  6895. }
  6896. }
  6897. oldFunc.call(this);
  6898. };
  6899. },
  6900. ClanQuestsFastFarm: function () {
  6901. const VipRuleValueObject = selfGame['game.data.storage.rule.VipRuleValueObject'];
  6902. const getClanQuestsFastFarm = getF(VipRuleValueObject, 'get_clanQuestsFastFarm', 1);
  6903. VipRuleValueObject.prototype[getClanQuestsFastFarm] = function () {
  6904. return 0;
  6905. };
  6906. },
  6907. adventureCamera: function () {
  6908. const AMC_40 = getProtoFn(Game.AdventureMapCamera, 40);
  6909. const AMC_5 = getProtoFn(Game.AdventureMapCamera, 5);
  6910. const oldFunc = Game.AdventureMapCamera.prototype[AMC_40];
  6911. Game.AdventureMapCamera.prototype[AMC_40] = function (a) {
  6912. this[AMC_5] = 0.4;
  6913. oldFunc.bind(this)(a);
  6914. };
  6915. },
  6916. unlockMission: function () {
  6917. const WorldMapStoryDrommerHelper = selfGame['game.mediator.gui.worldmap.WorldMapStoryDrommerHelper'];
  6918. const WMSDH_4 = getFn(WorldMapStoryDrommerHelper, 4);
  6919. const WMSDH_7 = getFn(WorldMapStoryDrommerHelper, 7);
  6920. WorldMapStoryDrommerHelper[WMSDH_4] = function () {
  6921. return true;
  6922. };
  6923. WorldMapStoryDrommerHelper[WMSDH_7] = function () {
  6924. return true;
  6925. };
  6926. },
  6927. SendReplayPopUp: function() {
  6928. game_view_popup_ClipBasedPopup.prototype.SendReplayPopUp.call(this);
  6929. //if(this.mediator.get_canShareChat()) {
  6930. var clipFull = new game_mediator_gui_popup_chat_sendreplay_SendReplayPopUpClip();
  6931. game_assets_storage_AssetStorage.rsx.popup_theme.get_factory().create(clipFull,game_assets_storage_AssetStorage.rsx.popup_theme.data.getClipByName("send_replay_popup"));
  6932. this.addChild(clipFull.get_graphics());
  6933. clipFull.tf_title.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_SEND_REPLAY_TEXT"));
  6934. clipFull.replay_info.tf_label.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_REPLAY_TEXT"));
  6935. clipFull.action_btn.set_label(com_progrestar_common_lang_Translate.translate("UI_POPUP_CHAT_SEND"));
  6936. clipFull.tf_message_input.set_prompt(com_progrestar_common_lang_Translate.translate("UI_DIALOG_CHAT_INPUT_MESSAGE_PROMPT"));
  6937. clipFull.tf_message_input.set_text(this.mediator.get_defauiltText());
  6938. clipFull.action_btn.get_signal_click().add($bind(this,this.handler_sendClick));
  6939. clipFull.replay_info.btn_option.get_signal_click().add($bind(this,this.handler_replayClick));
  6940. this.clip = clipFull;
  6941. /*} else {
  6942. var clipShort = new game_mediator_gui_popup_chat_sendreplay_SendReplayPopUpClipShort();
  6943. game_assets_storage_AssetStorage.rsx.popup_theme.get_factory().create(clipShort,game_assets_storage_AssetStorage.rsx.popup_theme.data.getClipByName("send_replay_popup_short"));
  6944. this.addChild(clipShort.get_graphics());
  6945. this.clip = clipShort;
  6946. }*/
  6947. this.clip.button_close.get_signal_click().add(($_=this.mediator,$bind($_,$_.close)));
  6948. this.clip.tf_replay.set_text(com_progrestar_common_lang_Translate.translate("UI_DIALOG_ARENA_REPLAY_URL"));
  6949. this.clip.replay_url_input.set_text(this.mediator.get_replayURL());
  6950. this.clip.replay_url_input.addEventListener("change",$bind(this,this.handler_replayUrlInputChange));
  6951. this.clip.copy_btn.set_label(com_progrestar_common_lang_Translate.translate("UI_DIALOG_BUTTON_COPY"));
  6952. },
  6953. };
  6954.  
  6955. /**
  6956. * Starts replacing recorded functions
  6957. *
  6958. * Запускает замену записанных функций
  6959. */
  6960. this.activateHacks = function () {
  6961. if (!selfGame) throw Error('Use connectGame');
  6962. for (let func in replaceFunction) {
  6963. try {
  6964. replaceFunction[func]();
  6965. } catch (error) {
  6966. console.error(error);
  6967. }
  6968. }
  6969. }
  6970.  
  6971. /**
  6972. * Returns the game object
  6973. *
  6974. * Возвращает объект игры
  6975. */
  6976. this.getSelfGame = function () {
  6977. return selfGame;
  6978. }
  6979.  
  6980. /**
  6981. * Updates game data
  6982. *
  6983. * Обновляет данные игры
  6984. */
  6985. this.refreshGame = function () {
  6986. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  6987. try {
  6988. cheats.refreshInventory();
  6989. } catch (e) { }
  6990. }
  6991.  
  6992. /**
  6993. * Update inventory
  6994. *
  6995. * Обновляет инвентарь
  6996. */
  6997. this.refreshInventory = async function () {
  6998. const GM_INST = getFnP(Game.GameModel, "get_instance");
  6999. const GM_0 = getProtoFn(Game.GameModel, 0);
  7000. const P_24 = getProtoFn(selfGame["game.model.user.Player"], 24);
  7001. const Player = Game.GameModel[GM_INST]()[GM_0];
  7002. Player[P_24] = new selfGame["game.model.user.inventory.PlayerInventory"]
  7003. Player[P_24].init(await Send({calls:[{name:"inventoryGet",args:{},ident:"body"}]}).then(e => e.results[0].result.response))
  7004. }
  7005. this.updateInventory = function (reward) {
  7006. const GM_INST = getFnP(Game.GameModel, 'get_instance');
  7007. const GM_0 = getProtoFn(Game.GameModel, 0);
  7008. const P_24 = getProtoFn(selfGame['game.model.user.Player'], 24);
  7009. const Player = Game.GameModel[GM_INST]()[GM_0];
  7010. Player[P_24].init(reward);
  7011. };
  7012. this.updateMap = function (data) {
  7013. const PCDD_21 = getProtoFn(selfGame['game.mechanics.clanDomination.model.PlayerClanDominationData'], 21);
  7014. const P_60 = getProtoFn(selfGame['game.model.user.Player'], 60);
  7015. const GM_0 = getProtoFn(Game.GameModel, 0);
  7016. const getInstance = getFnP(selfGame['Game'], 'get_instance');
  7017. const PlayerClanDominationData = Game.GameModel[getInstance]()[GM_0];
  7018. PlayerClanDominationData[P_60][PCDD_21].update(data);
  7019. };
  7020.  
  7021. /**
  7022. * Change the play screen on windowName
  7023. *
  7024. * Сменить экран игры на windowName
  7025. *
  7026. * Possible options:
  7027. *
  7028. * Возможные варианты:
  7029. *
  7030. * 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
  7031. */
  7032. this.goNavigtor = function (windowName) {
  7033. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  7034. let window = mechanicStorage[windowName];
  7035. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  7036. let Game = selfGame['Game'];
  7037. let navigator = getF(Game, "get_navigator")
  7038. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 20)
  7039. let instance = getFnP(Game, 'get_instance');
  7040. Game[instance]()[navigator]()[navigate](window, event);
  7041. }
  7042.  
  7043. /**
  7044. * Move to the sanctuary cheats.goSanctuary()
  7045. *
  7046. * Переместиться в святилище cheats.goSanctuary()
  7047. */
  7048. this.goSanctuary = () => {
  7049. this.goNavigtor("SANCTUARY");
  7050. }
  7051.  
  7052. /**
  7053. * Go to Guild War
  7054. *
  7055. * Перейти к Войне Гильдий
  7056. */
  7057. this.goClanWar = function() {
  7058. let instance = getFnP(Game.GameModel, 'get_instance')
  7059. let player = Game.GameModel[instance]().A;
  7060. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  7061. new clanWarSelect(player).open();
  7062. }
  7063.  
  7064. /**
  7065. * Go to BrawlShop
  7066. *
  7067. * Переместиться в BrawlShop
  7068. */
  7069. this.goBrawlShop = () => {
  7070. const instance = getFnP(Game.GameModel, 'get_instance')
  7071. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7072. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7073. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7074. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7075.  
  7076. const player = Game.GameModel[instance]().A;
  7077. const shop = player[P_36][PSD_0][IM_0][1038][PSDE_4];
  7078. const shopPopup = new selfGame["game.mechanics.brawl.mediator.BrawlShopPopupMediator"](player, shop)
  7079. shopPopup.open(new selfGame["game.mediator.gui.popup.PopupStashEventParams"])
  7080. }
  7081.  
  7082. /**
  7083. * Returns all stores from game data
  7084. *
  7085. * Возвращает все магазины из данных игры
  7086. */
  7087. this.getShops = () => {
  7088. const instance = getFnP(Game.GameModel, 'get_instance')
  7089. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7090. const PSD_0 = getProtoFn(selfGame["game.model.user.shop.PlayerShopData"], 0);
  7091. const IM_0 = getProtoFn(selfGame["haxe.ds.IntMap"], 0);
  7092.  
  7093. const player = Game.GameModel[instance]().A;
  7094. return player[P_36][PSD_0][IM_0];
  7095. }
  7096.  
  7097. /**
  7098. * Returns the store from the game data by ID
  7099. *
  7100. * Возвращает магазин из данных игры по идетификатору
  7101. */
  7102. this.getShop = (id) => {
  7103. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7104. const shops = this.getShops();
  7105. const shop = shops[id]?.[PSDE_4];
  7106. return shop;
  7107. }
  7108. /**
  7109. * Moves to the store with the specified ID
  7110. *
  7111. * Перемещает к магазину с указанным идетификатором
  7112. */
  7113. this.goShopId = function (id) {
  7114. const shop = this.getShop(id);
  7115. if (!shop) {
  7116. return;
  7117. }
  7118. let event = new selfGame["game.mediator.gui.popup.PopupStashEventParams"];
  7119. let Game = selfGame['Game'];
  7120. let navigator = getF(Game, "get_navigator");
  7121. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 21);
  7122. let instance = getFnP(Game, 'get_instance');
  7123. Game[instance]()[navigator]()[navigate](shop, event);
  7124. }
  7125. /**
  7126. * Opens a list of non-standard stores
  7127. *
  7128. * Открывает список не стандартных магазинов
  7129. */
  7130. this.goCustomShops = async (p = 0) => {
  7131. /** Запрос данных нужных магазинов */
  7132. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  7133. const shops = lib.getData('shop');
  7134. for (const id in shops) {
  7135. const check = !shops[id].ident.includes('merchantPromo') &&
  7136. ![1, 4, 5, 6, 7, 8, 9, 10, 11, 1023, 1024].includes(+id);
  7137. if (check) {
  7138. calls.push({
  7139. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  7140. })
  7141. }
  7142. }
  7143. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  7144. const shopAll = result.shift();
  7145. const DS_32 = getFn(Game.DataStorage, 32)
  7146. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7147. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7148. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  7149. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  7150. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  7151. for (let shop of result) {
  7152. shopAll[shop.id] = shop;
  7153. // Снимаем все ограничения с магазинов
  7154. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  7155. shopLibData[SD_21] = 1;
  7156. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7157. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7158. teamLevel: 10
  7159. });
  7160. }
  7161. /** Скрываем все остальные магазины */
  7162. for (let id in shops) {
  7163. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7164. if (shopLibData[ident].includes('merchantPromo')) {
  7165. shopLibData[SD_21] = 0;
  7166. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7167. teamLevel: 999
  7168. });
  7169. }
  7170. }
  7171. const instance = getFnP(Game.GameModel, 'get_instance')
  7172. const GM_0 = getProtoFn(Game.GameModel, 0);
  7173. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7174. const player = Game.GameModel[instance]()[GM_0];
  7175. /** Пересоздаем объект с магазинами */
  7176. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7177. player[P_36].init(shopAll);
  7178. /** Даем магазинам новые названия */
  7179. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7180. const shopName = getFn(cheats.getShop(1), 14);
  7181. const currentShops = this.getShops();
  7182. let count = 0;
  7183. const start = 9 * p + 1;
  7184. const end = start + 8;
  7185. for (let id in currentShops) {
  7186. const shop = currentShops[id][PSDE_4];
  7187. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7188. /** Скрываем стандартные магазины */
  7189. shop[SD_21] = 0;
  7190. } else {
  7191. count++;
  7192. if (count < start || count > end) {
  7193. shop[SD_21] = 0;
  7194. continue;
  7195. }
  7196. shop[SD_21] = 1;
  7197. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  7198. shop[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7199. shop[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7200. teamLevel: 10
  7201. });
  7202. }
  7203. }
  7204. console.log(count, start, end)
  7205. /** Отправляемся в городскую лавку */
  7206. this.goShopId(1);
  7207. }
  7208. /**
  7209. * Opens a list of standard stores
  7210. *
  7211. * Открывает список стандартных магазинов
  7212. */
  7213. this.goDefaultShops = async () => {
  7214. const result = await Send({ calls: [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }] })
  7215. .then(e => e.results.map(n => n.result.response));
  7216. const shopAll = result.shift();
  7217. const shops = lib.getData('shop');
  7218. const DS_8 = getFn(Game.DataStorage, 8)
  7219. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  7220. /** Получаем объект валюты магазина для оторажения */
  7221. const coins = Game.DataStorage[DS_8][DSB_4](85);
  7222. coins.__proto__ = selfGame["game.data.storage.resource.ConsumableDescription"].prototype;
  7223. const DS_32 = getFn(Game.DataStorage, 32)
  7224. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7225. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7226. for (const id in shops) {
  7227. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7228. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7229. shopLibData[SD_21] = 1;
  7230. } else {
  7231. shopLibData[SD_21] = 0;
  7232. }
  7233. }
  7234. const instance = getFnP(Game.GameModel, 'get_instance')
  7235. const GM_0 = getProtoFn(Game.GameModel, 0);
  7236. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7237. const player = Game.GameModel[instance]()[GM_0];
  7238. /** Пересоздаем объект с магазинами */
  7239. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7240. player[P_36].init(shopAll);
  7241. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7242. const currentShops = this.getShops();
  7243. for (let id in currentShops) {
  7244. const shop = currentShops[id][PSDE_4];
  7245. if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7246. shop[SD_21] = 1;
  7247. } else {
  7248. shop[SD_21] = 0;
  7249. }
  7250. }
  7251. this.goShopId(1);
  7252. }
  7253. /**
  7254. * Opens a list of Secret Wealth stores
  7255. *
  7256. * Открывает список магазинов Тайное богатство
  7257. */
  7258. this.goSecretWealthShops = async () => {
  7259. /** Запрос данных нужных магазинов */
  7260. const calls = [{ name: "shopGetAll", args: {}, ident: "shopGetAll" }];
  7261. const shops = lib.getData('shop');
  7262. for (const id in shops) {
  7263. if (shops[id].ident.includes('merchantPromo') && shops[id].teamLevelToUnlock <= 130) {
  7264. calls.push({
  7265. name: "shopGet", args: { shopId: id }, ident: `shopGet_${id}`
  7266. })
  7267. }
  7268. }
  7269. const result = await Send({ calls }).then(e => e.results.map(n => n.result.response));
  7270. const shopAll = result.shift();
  7271. const DS_32 = getFn(Game.DataStorage, 32)
  7272. const SDS_5 = getProtoFn(selfGame["game.data.storage.shop.ShopDescriptionStorage"], 5)
  7273. const SD_21 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 21);
  7274. const SD_1 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 1);
  7275. const SD_9 = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 9);
  7276. const ident = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 11);
  7277. const specialCurrency = getProtoFn(selfGame["game.data.storage.shop.ShopDescription"], 15);
  7278. const DS_8 = getFn(Game.DataStorage, 8)
  7279. const DSB_4 = getProtoFn(selfGame["game.data.storage.DescriptionStorageBase"], 4)
  7280. /** Получаем объект валюты магазина для оторажения */
  7281. const coins = Game.DataStorage[DS_8][DSB_4](85);
  7282. coins.__proto__ = selfGame["game.data.storage.resource.CoinDescription"].prototype;
  7283. for (let shop of result) {
  7284. shopAll[shop.id] = shop;
  7285. /** Снимаем все ограничения с магазинов */
  7286. const shopLibData = Game.DataStorage[DS_32][SDS_5](shop.id)
  7287. if (shopLibData[ident].includes('merchantPromo')) {
  7288. shopLibData[SD_21] = 1;
  7289. shopLibData[SD_1] = new selfGame["game.model.user.requirement.Requirement"]
  7290. shopLibData[SD_9] = new selfGame["game.data.storage.level.LevelRequirement"]({
  7291. teamLevel: 10
  7292. });
  7293. }
  7294. }
  7295. /** Скрываем все остальные магазины */
  7296. for (let id in shops) {
  7297. const shopLibData = Game.DataStorage[DS_32][SDS_5](id)
  7298. if (!shopLibData[ident].includes('merchantPromo')) {
  7299. shopLibData[SD_21] = 0;
  7300. }
  7301. }
  7302. const instance = getFnP(Game.GameModel, 'get_instance')
  7303. const GM_0 = getProtoFn(Game.GameModel, 0);
  7304. const P_36 = getProtoFn(selfGame["game.model.user.Player"], 36);
  7305. const player = Game.GameModel[instance]()[GM_0];
  7306. /** Пересоздаем объект с магазинами */
  7307. player[P_36] = new selfGame["game.model.user.shop.PlayerShopData"](player);
  7308. player[P_36].init(shopAll);
  7309. /** Даем магазинам новые названия */
  7310. const PSDE_4 = getProtoFn(selfGame["game.model.user.shop.PlayerShopDataEntry"], 4);
  7311. const shopName = getFn(cheats.getShop(1), 14);
  7312. const currentShops = this.getShops();
  7313. for (let id in currentShops) {
  7314. const shop = currentShops[id][PSDE_4];
  7315. if (shop[ident].includes('merchantPromo')) {
  7316. shop[SD_21] = 1;
  7317. shop[specialCurrency] = coins;
  7318. shop[shopName] = cheats.translate("LIB_SHOP_NAME_" + id) + ' ' + id;
  7319. } else if ([1, 4, 5, 6, 8, 9, 10, 11].includes(+id)) {
  7320. /** Скрываем стандартные магазины */
  7321. shop[SD_21] = 0;
  7322. }
  7323. }
  7324. /** Отправляемся в городскую лавку */
  7325. this.goShopId(1);
  7326. }
  7327. /**
  7328. * Change island map
  7329. *
  7330. * Сменить карту острова
  7331. */
  7332. this.changeIslandMap = (mapId = 2) => {
  7333. const GameInst = getFnP(selfGame['Game'], 'get_instance');
  7334. const GM_0 = getProtoFn(Game.GameModel, 0);
  7335. const P_59 = getProtoFn(selfGame["game.model.user.Player"], 60);
  7336. const PSAD_31 = getProtoFn(selfGame['game.mechanics.season_adventure.model.PlayerSeasonAdventureData'], 31);
  7337. const Player = Game.GameModel[GameInst]()[GM_0];
  7338. Player[P_59][PSAD_31]({ id: mapId, seasonAdventure: { id: mapId, startDate: 1701914400, endDate: 1709690400, closed: false } });
  7339.  
  7340. const GN_15 = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 17)
  7341. const navigator = getF(selfGame['Game'], "get_navigator");
  7342. selfGame['Game'][GameInst]()[navigator]()[GN_15](new selfGame["game.mediator.gui.popup.PopupStashEventParams"]);
  7343. }
  7344.  
  7345. /**
  7346. * Game library availability tracker
  7347. *
  7348. * Отслеживание доступности игровой библиотеки
  7349. */
  7350. function checkLibLoad() {
  7351. timeout = setTimeout(() => {
  7352. if (Game.GameModel) {
  7353. changeLib();
  7354. } else {
  7355. checkLibLoad();
  7356. }
  7357. }, 100)
  7358. }
  7359.  
  7360. /**
  7361. * Game library data spoofing
  7362. *
  7363. * Подмена данных игровой библиотеки
  7364. */
  7365. function changeLib() {
  7366. console.log('lib connect');
  7367. const originalStartFunc = Game.GameModel.prototype.start;
  7368. Game.GameModel.prototype.start = function (a, b, c) {
  7369. self.libGame = b.raw;
  7370. try {
  7371. const levels = b.raw.seasonAdventure.level;
  7372. for (const id in levels) {
  7373. const level = levels[id];
  7374. level.clientData.graphics.fogged = level.clientData.graphics.visible
  7375. }
  7376. const adv = b.raw.seasonAdventure.list[1];
  7377. adv.clientData.asset = 'dialog_season_adventure_tiles';
  7378. } catch (e) {
  7379. console.warn(e);
  7380. }
  7381. originalStartFunc.call(this, a, b, c);
  7382. }
  7383. }
  7384.  
  7385. /**
  7386. * Returns the value of a language constant
  7387. *
  7388. * Возвращает значение языковой константы
  7389. * @param {*} langConst language constant // языковая константа
  7390. * @returns
  7391. */
  7392. this.translate = function (langConst) {
  7393. return Game.Translate.translate(langConst);
  7394. }
  7395.  
  7396. connectGame();
  7397. checkLibLoad();
  7398. }
  7399.  
  7400. /**
  7401. * Auto collection of gifts
  7402. *
  7403. * Автосбор подарков
  7404. */
  7405. function getAutoGifts() {
  7406. // c3ltYm9scyB0aGF0IG1lYW4gbm90aGluZw==
  7407. let valName = 'giftSendIds_' + userInfo.id;
  7408.  
  7409. if (!localStorage['clearGift' + userInfo.id]) {
  7410. localStorage[valName] = '';
  7411. localStorage['clearGift' + userInfo.id] = '+';
  7412. }
  7413.  
  7414. if (!localStorage[valName]) {
  7415. localStorage[valName] = '';
  7416. }
  7417.  
  7418. const giftsAPI = new ZingerYWebsiteAPI('getGifts.php', arguments);
  7419. /**
  7420. * Submit a request to receive gift codes
  7421. *
  7422. * Отправка запроса для получения кодов подарков
  7423. */
  7424. giftsAPI.request().then((data) => {
  7425. let freebieCheckCalls = {
  7426. calls: [],
  7427. };
  7428. data.forEach((giftId, n) => {
  7429. if (localStorage[valName].includes(giftId)) return;
  7430. freebieCheckCalls.calls.push({
  7431. name: 'registration',
  7432. args: {
  7433. user: { referrer: {} },
  7434. giftId,
  7435. },
  7436. context: {
  7437. actionTs: Math.floor(performance.now()),
  7438. cookie: window?.NXAppInfo?.session_id || null,
  7439. },
  7440. ident: giftId,
  7441. });
  7442. });
  7443. if (!freebieCheckCalls.calls.length) {
  7444. return;
  7445. }
  7446. send(JSON.stringify(freebieCheckCalls), (e) => {
  7447. let countGetGifts = 0;
  7448. const gifts = [];
  7449. for (check of e.results) {
  7450. gifts.push(check.ident);
  7451. if (check.result.response != null) {
  7452. countGetGifts++;
  7453. }
  7454. }
  7455. const saveGifts = localStorage[valName].split(';');
  7456. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  7457. console.log(`${I18N('GIFTS')}: ${countGetGifts}`);
  7458. });
  7459. });
  7460. }
  7461.  
  7462. /**
  7463. * To fill the kills in the Forge of Souls
  7464. *
  7465. * Набить килов в горниле душ
  7466. */
  7467. async function bossRatingEvent() {
  7468. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  7469. if (!topGet || !topGet.results[0].result.response[0]) {
  7470. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7471. return;
  7472. }
  7473. const replayId = topGet.results[0].result.response[0].userData.replayId;
  7474. const result = await Send(JSON.stringify({
  7475. calls: [
  7476. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  7477. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  7478. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  7479. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  7480. ]
  7481. }));
  7482. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  7483. if (!bossEventInfo) {
  7484. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7485. return;
  7486. }
  7487. const usedHeroes = bossEventInfo.progress.usedHeroes;
  7488. const party = Object.values(result.results[0].result.response.replay.attackers);
  7489. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  7490. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  7491. const calls = [];
  7492. /**
  7493. * First pack
  7494. *
  7495. * Первая пачка
  7496. */
  7497. const args = {
  7498. heroes: [],
  7499. favor: {}
  7500. }
  7501. for (let hero of party) {
  7502. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  7503. args.pet = hero.id;
  7504. continue;
  7505. }
  7506. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  7507. continue;
  7508. }
  7509. args.heroes.push(hero.id);
  7510. if (hero.favorPetId) {
  7511. args.favor[hero.id] = hero.favorPetId;
  7512. }
  7513. }
  7514. if (args.heroes.length) {
  7515. calls.push({
  7516. name: "bossRatingEvent_startBattle",
  7517. args,
  7518. ident: "body_0"
  7519. });
  7520. }
  7521. /**
  7522. * Other packs
  7523. *
  7524. * Другие пачки
  7525. */
  7526. let heroes = [];
  7527. let count = 1;
  7528. while (heroId = availableHeroes.pop()) {
  7529. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  7530. continue;
  7531. }
  7532. heroes.push(heroId);
  7533. if (heroes.length == 5) {
  7534. calls.push({
  7535. name: "bossRatingEvent_startBattle",
  7536. args: {
  7537. heroes: [...heroes],
  7538. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  7539. },
  7540. ident: "body_" + count
  7541. });
  7542. heroes = [];
  7543. count++;
  7544. }
  7545. }
  7546.  
  7547. if (!calls.length) {
  7548. setProgress(`${I18N('NO_HEROES')}`, true);
  7549. return;
  7550. }
  7551.  
  7552. const resultBattles = await Send(JSON.stringify({ calls }));
  7553. console.log(resultBattles);
  7554. rewardBossRatingEvent();
  7555. }
  7556.  
  7557. /**
  7558. * Collecting Rewards from the Forge of Souls
  7559. *
  7560. * Сбор награды из Горнила Душ
  7561. */
  7562. function rewardBossRatingEvent() {
  7563. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7564. send(rewardBossRatingCall, function (data) {
  7565. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  7566. if (!bossEventInfo) {
  7567. setProgress(`${I18N('EVENT')} ${I18N('NOT_AVAILABLE')}`, true);
  7568. return;
  7569. }
  7570.  
  7571. let farmedChests = bossEventInfo.progress.farmedChests;
  7572. let score = bossEventInfo.progress.score;
  7573. setProgress(`${I18N('DAMAGE_AMOUNT')}: ${score}`);
  7574. let revard = bossEventInfo.reward;
  7575.  
  7576. let getRewardCall = {
  7577. calls: []
  7578. }
  7579.  
  7580. let count = 0;
  7581. for (let i = 1; i < 10; i++) {
  7582. if (farmedChests.includes(i)) {
  7583. continue;
  7584. }
  7585. if (score < revard[i].score) {
  7586. break;
  7587. }
  7588. getRewardCall.calls.push({
  7589. name: "bossRatingEvent_getReward",
  7590. args: {
  7591. rewardId: i
  7592. },
  7593. ident: "body_" + i
  7594. });
  7595. count++;
  7596. }
  7597. if (!count) {
  7598. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7599. return;
  7600. }
  7601.  
  7602. send(JSON.stringify(getRewardCall), e => {
  7603. console.log(e);
  7604. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7605. });
  7606. });
  7607. }
  7608.  
  7609. /**
  7610. * Collect Easter eggs and event rewards
  7611. *
  7612. * Собрать пасхалки и награды событий
  7613. */
  7614. function offerFarmAllReward() {
  7615. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  7616. return Send(offerGetAllCall).then((data) => {
  7617. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  7618. if (!offerGetAll.length) {
  7619. setProgress(`${I18N('NOTHING_TO_COLLECT')}`, true);
  7620. return;
  7621. }
  7622.  
  7623. const calls = [];
  7624. for (let reward of offerGetAll) {
  7625. calls.push({
  7626. name: "offerFarmReward",
  7627. args: {
  7628. offerId: reward.id
  7629. },
  7630. ident: "offerFarmReward_" + reward.id
  7631. });
  7632. }
  7633.  
  7634. return Send(JSON.stringify({ calls })).then(e => {
  7635. console.log(e);
  7636. setProgress(`${I18N('COLLECTED')} ${e?.results?.length} ${I18N('REWARD')}`, true);
  7637. });
  7638. });
  7639. }
  7640.  
  7641. /**
  7642. * Assemble Outland
  7643. *
  7644. * Собрать запределье
  7645. */
  7646. function getOutland() {
  7647. return new Promise(function (resolve, reject) {
  7648. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  7649. let bosses = e.results[0].result.response;
  7650.  
  7651. let bossRaidOpenChestCall = {
  7652. calls: []
  7653. };
  7654.  
  7655. for (let boss of bosses) {
  7656. if (boss.mayRaid) {
  7657. bossRaidOpenChestCall.calls.push({
  7658. name: "bossRaid",
  7659. args: {
  7660. bossId: boss.id
  7661. },
  7662. ident: "bossRaid_" + boss.id
  7663. });
  7664. bossRaidOpenChestCall.calls.push({
  7665. name: "bossOpenChest",
  7666. args: {
  7667. bossId: boss.id,
  7668. amount: 1,
  7669. starmoney: 0
  7670. },
  7671. ident: "bossOpenChest_" + boss.id
  7672. });
  7673. } else if (boss.chestId == 1) {
  7674. bossRaidOpenChestCall.calls.push({
  7675. name: "bossOpenChest",
  7676. args: {
  7677. bossId: boss.id,
  7678. amount: 1,
  7679. starmoney: 0
  7680. },
  7681. ident: "bossOpenChest_" + boss.id
  7682. });
  7683. }
  7684. }
  7685.  
  7686. if (!bossRaidOpenChestCall.calls.length) {
  7687. setProgress(`${I18N('OUTLAND')} ${I18N('NOTHING_TO_COLLECT')}`, true);
  7688. resolve();
  7689. return;
  7690. }
  7691.  
  7692. send(JSON.stringify(bossRaidOpenChestCall), e => {
  7693. setProgress(`${I18N('OUTLAND')} ${I18N('COLLECTED')}`, true);
  7694. resolve();
  7695. });
  7696. });
  7697. });
  7698. }
  7699.  
  7700. /**
  7701. * Collect all rewards
  7702. *
  7703. * Собрать все награды
  7704. */
  7705. function questAllFarm() {
  7706. return new Promise(function (resolve, reject) {
  7707. let questGetAllCall = {
  7708. calls: [{
  7709. name: "questGetAll",
  7710. args: {},
  7711. ident: "body"
  7712. }]
  7713. }
  7714. send(JSON.stringify(questGetAllCall), function (data) {
  7715. let questGetAll = data.results[0].result.response;
  7716. const questAllFarmCall = {
  7717. calls: []
  7718. }
  7719. let number = 0;
  7720. for (let quest of questGetAll) {
  7721. if (quest.id < 1e6 && quest.state == 2) {
  7722. questAllFarmCall.calls.push({
  7723. name: "questFarm",
  7724. args: {
  7725. questId: quest.id
  7726. },
  7727. ident: `group_${number}_body`
  7728. });
  7729. number++;
  7730. }
  7731. }
  7732.  
  7733. if (!questAllFarmCall.calls.length) {
  7734. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7735. resolve();
  7736. return;
  7737. }
  7738.  
  7739. send(JSON.stringify(questAllFarmCall), function (res) {
  7740. console.log(res);
  7741. setProgress(`${I18N('COLLECTED')} ${number} ${I18N('REWARD')}`, true);
  7742. resolve();
  7743. });
  7744. });
  7745. })
  7746. }
  7747.  
  7748. /**
  7749. * Mission auto repeat
  7750. *
  7751. * Автоповтор миссии
  7752. * isStopSendMission = false;
  7753. * isSendsMission = true;
  7754. **/
  7755. this.sendsMission = async function (param) {
  7756. if (isStopSendMission) {
  7757. isSendsMission = false;
  7758. console.log(I18N('STOPPED'));
  7759. setProgress('');
  7760. await popup.confirm(`${I18N('STOPPED')}<br>${I18N('REPETITIONS')}: ${param.count}`, [{
  7761. msg: 'Ok',
  7762. result: true
  7763. }, ])
  7764. return;
  7765. }
  7766. lastMissionBattleStart = Date.now();
  7767. let missionStartCall = {
  7768. "calls": [{
  7769. "name": "missionStart",
  7770. "args": lastMissionStart,
  7771. "ident": "body"
  7772. }]
  7773. }
  7774. /**
  7775. * Mission Request
  7776. *
  7777. * Запрос на выполнение мисcии
  7778. */
  7779. SendRequest(JSON.stringify(missionStartCall), async e => {
  7780. if (e['error']) {
  7781. isSendsMission = false;
  7782. console.log(e['error']);
  7783. setProgress('');
  7784. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7785. await popup.confirm(msg, [
  7786. {msg: 'Ok', result: true},
  7787. ])
  7788. return;
  7789. }
  7790. /**
  7791. * Mission data calculation
  7792. *
  7793. * Расчет данных мисcии
  7794. */
  7795. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  7796. /** missionTimer */
  7797. let timer = getTimer(r.battleTime) + 5;
  7798. const period = Math.ceil((Date.now() - lastMissionBattleStart) / 1000);
  7799. if (period < timer) {
  7800. timer = timer - period;
  7801. await countdownTimer(timer, `${I18N('MISSIONS_PASSED')}: ${param.count}`);
  7802. }
  7803.  
  7804. let missionEndCall = {
  7805. "calls": [{
  7806. "name": "missionEnd",
  7807. "args": {
  7808. "id": param.id,
  7809. "result": r.result,
  7810. "progress": r.progress
  7811. },
  7812. "ident": "body"
  7813. }]
  7814. }
  7815. /**
  7816. * Mission Completion Request
  7817. *
  7818. * Запрос на завершение миссии
  7819. */
  7820. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  7821. if (e['error']) {
  7822. isSendsMission = false;
  7823. console.log(e['error']);
  7824. setProgress('');
  7825. let msg = e['error'].name + ' ' + e['error'].description + `<br>${I18N('REPETITIONS')}: ${param.count}`;
  7826. await popup.confirm(msg, [
  7827. {msg: 'Ok', result: true},
  7828. ])
  7829. return;
  7830. }
  7831. r = e.results[0].result.response;
  7832. if (r['error']) {
  7833. isSendsMission = false;
  7834. console.log(r['error']);
  7835. setProgress('');
  7836. await popup.confirm(`<br>${I18N('REPETITIONS')}: ${param.count}` + ' 3 ' + r['error'], [
  7837. {msg: 'Ok', result: true},
  7838. ])
  7839. return;
  7840. }
  7841.  
  7842. param.count++;
  7843. let RaidMission = getInput('countRaid');
  7844.  
  7845. if (RaidMission==param.count){
  7846. isStopSendMission = true;
  7847. console.log(RaidMission);
  7848. }
  7849. setProgress(`${I18N('MISSIONS_PASSED')}: ${param.count} (${I18N('STOP')})`, false, () => {
  7850. isStopSendMission = true;
  7851. });
  7852. setTimeout(sendsMission, 1, param);
  7853. });
  7854. })
  7855. });
  7856. }
  7857.  
  7858. /**
  7859. * Opening of russian dolls
  7860. *
  7861. * Открытие матрешек
  7862. */
  7863. async function openRussianDolls(libId, amount) {
  7864. let sum = 0;
  7865. let sumResult = [];
  7866.  
  7867. while (amount) {
  7868. sum += amount;
  7869. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`);
  7870. const calls = [{
  7871. name: "consumableUseLootBox",
  7872. args: { libId, amount },
  7873. ident: "body"
  7874. }];
  7875. const result = await Send(JSON.stringify({ calls })).then(e => e.results[0].result.response);
  7876. let newCount = 0;
  7877. for (let n of result) {
  7878. if (n?.consumable && n.consumable[libId]) {
  7879. newCount += n.consumable[libId]
  7880. }
  7881. }
  7882. sumResult = [...sumResult, ...result];
  7883. amount = newCount;
  7884. }
  7885.  
  7886. setProgress(`${I18N('TOTAL_OPEN')} ${sum}`, 5000);
  7887. return sumResult;
  7888. }
  7889.  
  7890. /**
  7891. * Collect all mail, except letters with energy and charges of the portal
  7892. *
  7893. * Собрать всю почту, кроме писем с энергией и зарядами портала
  7894. */
  7895. function mailGetAll() {
  7896. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  7897.  
  7898. return Send(getMailInfo).then(dataMail => {
  7899. const letters = dataMail.results[0].result.response.letters;
  7900. const letterIds = lettersFilter(letters);
  7901. if (!letterIds.length) {
  7902. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  7903. return;
  7904. }
  7905.  
  7906. const calls = [
  7907. { name: "mailFarm", args: { letterIds }, ident: "body" }
  7908. ];
  7909.  
  7910. return Send(JSON.stringify({ calls })).then(res => {
  7911. const lettersIds = res.results[0].result.response;
  7912. if (lettersIds) {
  7913. const countLetters = Object.keys(lettersIds).length;
  7914. setProgress(`${I18N('RECEIVED')} ${countLetters} ${I18N('LETTERS')}`, true);
  7915. }
  7916. });
  7917. });
  7918. }
  7919.  
  7920. /**
  7921. * Filters received emails
  7922. *
  7923. * Фильтрует получаемые письма
  7924. */
  7925. function lettersFilter(letters) {
  7926. const lettersIds = [];
  7927. for (let l in letters) {
  7928. letter = letters[l];
  7929. const reward = letter.reward;
  7930. if (!reward) {
  7931. continue;
  7932. }
  7933. /**
  7934. * Mail Collection Exceptions
  7935. *
  7936. * Исключения на сбор писем
  7937. */
  7938. const isFarmLetter = !(
  7939. /** Portals // сферы портала */
  7940. (reward?.refillable ? reward.refillable[45] : false) ||
  7941. /** Energy // энергия */
  7942. (reward?.stamina ? reward.stamina : false) ||
  7943. /** accelerating energy gain // ускорение набора энергии */
  7944. (reward?.buff ? true : false) ||
  7945. /** VIP Points // вип очки */
  7946. (reward?.vipPoints ? reward.vipPoints : false) ||
  7947. /** souls of heroes // душы героев */
  7948. (reward?.fragmentHero ? true : false) ||
  7949. /** heroes // герои */
  7950. (reward?.bundleHeroReward ? true : false)
  7951. );
  7952. if (isFarmLetter) {
  7953. lettersIds.push(~~letter.id);
  7954. continue;
  7955. }
  7956. /**
  7957. * Если до окончания годности письма менее 24 часов,
  7958. * то оно собирается не смотря на исключения
  7959. */
  7960. const availableUntil = +letter?.availableUntil;
  7961. if (availableUntil) {
  7962. const maxTimeLeft = 24 * 60 * 60 * 1000;
  7963. const timeLeft = (new Date(availableUntil * 1000) - new Date())
  7964. console.log('Time left:', timeLeft)
  7965. if (timeLeft < maxTimeLeft) {
  7966. lettersIds.push(~~letter.id);
  7967. continue;
  7968. }
  7969. }
  7970. }
  7971. return lettersIds;
  7972. }
  7973.  
  7974. /**
  7975. * Displaying information about the areas of the portal and attempts on the VG
  7976. *
  7977. * Отображение информации о сферах портала и попытках на ВГ
  7978. */
  7979. async function justInfo() {
  7980. return new Promise(async (resolve, reject) => {
  7981. const calls = [{
  7982. name: "userGetInfo",
  7983. args: {},
  7984. ident: "userGetInfo"
  7985. },
  7986. {
  7987. name: "clanWarGetInfo",
  7988. args: {},
  7989. ident: "clanWarGetInfo"
  7990. },
  7991. {
  7992. name: "titanArenaGetStatus",
  7993. args: {},
  7994. ident: "titanArenaGetStatus"
  7995. }];
  7996. const result = await Send(JSON.stringify({ calls }));
  7997. const infos = result.results;
  7998. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  7999. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  8000. const arePointsMax = infos[1].result.response?.arePointsMax;
  8001. const titansLevel = +(infos[2].result.response?.tier ?? 0);
  8002. const titansStatus = infos[2].result.response?.status; //peace_time || battle
  8003.  
  8004. const sanctuaryButton = buttons['goToSanctuary'].button;
  8005. const clanWarButton = buttons['goToClanWar'].button;
  8006. const titansArenaButton = buttons['testTitanArena'].button;
  8007.  
  8008. /*if (portalSphere.amount) {
  8009. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  8010. sanctuaryButton.title = `${I18N('SANCTUARY_TITLE')}\n${portalSphere.amount} ${I18N('PORTALS')}`;
  8011. } else {*/
  8012. sanctuaryButton.style.color = '';
  8013. sanctuaryButton.title = I18N('SANCTUARY_TITLE');
  8014. //}
  8015. /*if (clanWarMyTries && !arePointsMax) {
  8016. clanWarButton.style.color = 'red';
  8017. clanWarButton.title = `${I18N('GUILD_WAR_TITLE')}\n${clanWarMyTries}${I18N('ATTEMPTS')}`;
  8018. } else {*/
  8019. clanWarButton.style.color = '';
  8020. clanWarButton.title = I18N('GUILD_WAR_TITLE');
  8021. //}
  8022.  
  8023. /*if (titansLevel < 7 && titansStatus == 'battle') {
  8024. const partColor = Math.floor(125 * titansLevel / 7);
  8025. titansArenaButton.style.color = `rgb(255,${partColor},${partColor})`;
  8026. titansArenaButton.title = `${I18N('TITAN_ARENA_TITLE')}\n${titansLevel} ${I18N('LEVEL')}`;
  8027. } else {*/
  8028. titansArenaButton.style.color = '';
  8029. titansArenaButton.title = I18N('TITAN_ARENA_TITLE');
  8030. //}
  8031. //тест убрал подсветку красным в меню
  8032. const imgPortal =
  8033. 'data:image/gif;base64,R0lGODlhLwAvAHAAACH5BAEAAP8ALAAAAAAvAC8AhwAAABkQWgjF3krO3ghSjAhSzinF3u+tGWvO3s5rGSmE5gha7+/OWghSrWvmnClShCmUlAiE5u+MGe/W3mvvWmspUmvvGSnOWinOnCnOGWsZjErvnAiUlErvWmsIUkrvGQjOWgjOnAjOGUoZjM6MGe/OIWvv5q1KGSnv5mulGe/vWs7v3ozv3kqEGYxKGWuEWmtSKUrv3mNaCEpKUs7OWiml5ggxWmMpEAgZpRlaCO/35q1rGRkxKWtarSkZrRljKSkZhAjv3msIGRk6CEparQhjWq3v3kql3ozOGe/vnM6tGYytWu9rGWuEGYzO3kqE3gil5s6MWq3vnGvFnM7vWoxrGc5KGYyMWs6tWq2MGYzOnO+tWmvFWkqlWoxrWgAZhEqEWq2tWoytnIyt3krFnGul3mulWmulnEIpUkqlGUqlnK3OnK2MWs7OnClSrSmUte+tnGvFGYytGYzvWs5rWowpGa3O3u/OnErFWoyMnGuE3muEnEqEnIyMGYzOWs7OGe9r3u9rWq3vWq1rWq1r3invWimlWu+t3q0pWq2t3u8pWu8p3q0p3invnCnvGe/vGa2tGa3vGa2tnK0pGe9rnK1rnCmlGe8pGe8pnK0pnGsZrSkp3msp3s7vGYzvnM7vnIzvGc6tnM5r3oxr3gilWs6t3owpWs4pWs4p3owp3s5rnIxrnAilGc4pGc4pnIwpnAgp3kop3s7O3u9KGe+MWoxKWoyM3kIIUgiUte+MnErFGc5KWowIGe9K3u9KWq3OWq1KWq1K3gjvWimEWu+M3q0IWq2M3u8IWu8I3q0I3gjvnAjvGa3OGa2MnK0IGe9KnK1KnCmEGe8IGe8InK0InEoZrSkI3msI3s6MnM5K3oxK3giEWs6M3owIWs4IWs4I3owI3s5KnIxKnAiEGc4IGc4InIwInAgI3koI3kJaCAgQKUIpEGtKUkJSKUIIECla7ylazmtahGta70pa70pahGtazkpazmtrWiExUkprUiljWikQKRkQCAAQCAAACAAAAAj/AP8JHEiwoMGDCBMqXMiwocODJlBIRBHDxMOLBmMEkSjAgICPE2Mw/OUH4z8TGz+agBIBCsuWUAQE0WLwzkAkKZZcnAilhk+fA1bUiEC0ZZABJOD8IyHhwJYDkpakafJQ4kooR5yw0LFihQ4WJhAMKCoARRYSTJgkUOInBZK2DiX2rGHEiI67eFcYATtAAVEoKEiQSFBFDs4UKbg0lGgAigIEeCNzrWvCxIChEcoy3dGiSoITTRQvnCLRrxOveI2McbKahevKJmooiKkFy4Gzg5tMMaMwitwIj/PqGPCugL0CT47ANhEjQg3Atg9IT5CiS4uEUcRIBH4EtREETuB9/xn/BUcBBbBXGGgpoPaBEid23EuXgvdBJhtQGFCwwA7eMgs0gEMDBJD3hR7KbRVbSwP8UcIWJNwjIRLXGZRAAhLVsIACR9y1whMNfNGAHgiUcUSBX8ADWwwKzCYADTSUcMA9ebwQmkFYMMFGhgu80x1XTxSAwxNdGWGCAiG6YQBzly3QkhYxlsDGP1cg4YBBaC0h1zsLPGHXCkfA00AZeu11hALl1VBZXwW0RAaMDGDxTxNdTGEQExJoiUINXCpwmhFOKJCcVmCdOR56MezXJhRvwFlCC2lcWVAUEjBxRobw9HhEXUYekWBlsoVoQEWyFbAAFPRIQQMDJcDQhRhYSv+QZ1kGcAnPYya4BhZYlb1TQ4iI+tVmBPpIQQWrMORxkKwSsEFrDaa+8xgCy1mmgLSHxtDXAhtGMIOxDKjgAkLM7iAAYD4VJ+0RAyAgVl++ikfAESxy62QB365awrjLyprAcxEY4FOmXEp7LbctjlfAAE1yGwEBYBirAgP8GtTUARIMM1QBPrVYQAHF9dgiml/Mexl/3DbAwxnHMqBExQVdLAEMjRXQgHOyydaibPCgqEDH3JrawDosUDExCTATZJuMJ0AAxRNXtLFFPD+P/DB58AC9wH4N4BMxDRPvkPRAbLx3AAlVMLBFCXeQgIaIKJKHQ9X8+forAetMsaoKB7j/MAhCL5j9VFNPJYBGiCGW18CtsvWIs5j7gLEGqyV81gxC6ZBQQgkSMEUCLQckMMLHNhcAD3B+8TdyA0PPACWrB8SH0BItyHAAAwdE4YILTSUww8cELwAyt7D4JSberkd5wA4neIFQE020sMPmJZBwAi0SJMBOA6WTXgAsDYDPOj7r3KNFy5WfkEBCKbTQBQzTM+By5wm4YAPr+LM+IIE27LPOFWswmgqqZ4UEXCEhLUjBGWbgAs3JD2OfWcc68GEDArCOAASwAfnWUYUwtIEKSVCBCiSgPuclpAlImMI9YNDAzeFuMEwQ2w3W4Q530PAGLthBFNqwghCKMAoF3MEB/xNihvr8Ix4sdCCrJja47CVAMFjAwid6eJcQWi8BO4jHQl6AGFjdwwUnOMF75CfCMpoxCTpAoxoZMBgs3qMh7ZODQFYYxgSMsQThCpcK0BiZJNxBCZ7zwhsbYqO3wCoe7AjjCaxAggNUcY94mcDa3qMECWSBHYN0CBfj0IQliEFCMFjkIulAAisUkBZYyB4USxAFCZnkH1xsgltSYCMYyACMpizghS7kOTZIKJMmeYEZzCCH6iCmBS1IRzpkcEsXVMGZMMgHJvfwyoLsYQ9nmMIUuDAFPIAhH8pUZjLbcY89rKKaC9nDFeLxy3vkYwbJTMcL0InOeOSjBVShJz2pqQvPfvrznwANKEMCAgA7';
  8034.  
  8035. setProgress('<img src="' + imgPortal + '" style="height: 25px;position: relative;top: 5px;"> ' + `${portalSphere.amount} </br> ${I18N('GUILD_WAR')}: ${clanWarMyTries}`, true);
  8036. resolve();
  8037. });
  8038. }
  8039. // тест сделать все
  8040. /** Отправить подарки мое*/
  8041. function testclanSendDailyGifts() {
  8042.  
  8043. send('{"calls":[{"name":"clanSendDailyGifts","args":{},"ident":"clanSendDailyGifts"}]}', e => {
  8044. setProgress('Награды собраны', true);});
  8045. }
  8046. /** Открой сферу артефактов титанов*/
  8047. function testtitanArtifactChestOpen() {
  8048. send('{"calls":[{"name":"titanArtifactChestOpen","args":{"amount":1,"free":true},"ident":"body"}]}',
  8049. isWeCanDo => {
  8050. return info['inventoryGet']?.consumable[55] > 0
  8051. //setProgress('Награды собраны', true);
  8052. });
  8053. }
  8054. /** Воспользуйся призывом питомцев 1 раз*/
  8055. function testpet_chestOpen() {
  8056. send('{"calls":[{"name":"pet_chestOpen","args":{"amount":1,"paid":false},"ident":"pet_chestOpen"}]}',
  8057. isWeCanDo => {
  8058. return info['inventoryGet']?.consumable[90] > 0
  8059. //setProgress('Награды собраны', true);
  8060. });
  8061. }
  8062.  
  8063. async function getDailyBonus() {
  8064. const dailyBonusInfo = await Send(JSON.stringify({
  8065. calls: [{
  8066. name: "dailyBonusGetInfo",
  8067. args: {},
  8068. ident: "body"
  8069. }]
  8070. })).then(e => e.results[0].result.response);
  8071. const { availableToday, availableVip, currentDay } = dailyBonusInfo;
  8072.  
  8073. if (!availableToday) {
  8074. console.log('Уже собрано');
  8075. return;
  8076. }
  8077.  
  8078. const currentVipPoints = +userInfo.vipPoints;
  8079. const dailyBonusStat = lib.getData('dailyBonusStatic');
  8080. const vipInfo = lib.getData('level').vip;
  8081. let currentVipLevel = 0;
  8082. for (let i in vipInfo) {
  8083. vipLvl = vipInfo[i];
  8084. if (currentVipPoints >= vipLvl.vipPoints) {
  8085. currentVipLevel = vipLvl.level;
  8086. }
  8087. }
  8088. const vipLevelDouble = dailyBonusStat[`${currentDay}_0_0`].vipLevelDouble;
  8089.  
  8090. const calls = [{
  8091. name: "dailyBonusFarm",
  8092. args: {
  8093. vip: availableVip && currentVipLevel >= vipLevelDouble ? 1 : 0
  8094. },
  8095. ident: "body"
  8096. }];
  8097.  
  8098. const result = await Send(JSON.stringify({ calls }));
  8099. if (result.error) {
  8100. console.error(result.error);
  8101. return;
  8102. }
  8103.  
  8104. const reward = result.results[0].result.response;
  8105. const type = Object.keys(reward).pop();
  8106. const itemId = Object.keys(reward[type]).pop();
  8107. const count = reward[type][itemId];
  8108. const itemName = cheats.translate(`LIB_${type.toUpperCase()}_NAME_${itemId}`);
  8109.  
  8110. console.log(`Ежедневная награда: Получено ${count} ${itemName}`, reward);
  8111. }
  8112.  
  8113. async function farmStamina(lootBoxId = 148) {
  8114. const lootBox = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"}]}')
  8115. .then(e => e.results[0].result.response.consumable[148]);
  8116.  
  8117. /** Добавить другие ящики */
  8118. /**
  8119. * 144 - медная шкатулка
  8120. * 145 - бронзовая шкатулка
  8121. * 148 - платиновая шкатулка
  8122. */
  8123. if (!lootBox) {
  8124. setProgress(I18N('NO_BOXES'), true);
  8125. return;
  8126. }
  8127.  
  8128. let maxFarmEnergy = getSaveVal('maxFarmEnergy', 100);
  8129. const result = await popup.confirm(I18N('OPEN_LOOTBOX', { lootBox }), [
  8130. { result: false, isClose: true },
  8131. { msg: I18N('BTN_YES'), result: true },
  8132. { msg: I18N('STAMINA'), isInput: true, default: maxFarmEnergy },
  8133. ]);
  8134.  
  8135. if (!+result) {
  8136. return;
  8137. }
  8138.  
  8139. if ((typeof result) !== 'boolean' && Number.parseInt(result)) {
  8140. maxFarmEnergy = +result;
  8141. setSaveVal('maxFarmEnergy', maxFarmEnergy);
  8142. } else {
  8143. maxFarmEnergy = 0;
  8144. }
  8145.  
  8146. let collectEnergy = 0;
  8147. for (let count = lootBox; count > 0; count--) {
  8148. const result = await Send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":148,"amount":1},"ident":"body"}]}')
  8149. .then(e => e.results[0].result.response[0]);
  8150. if ('stamina' in result) {
  8151. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox} ${I18N('STAMINA')} +${result.stamina}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8152. console.log(`${ I18N('STAMINA') } + ${ result.stamina }`);
  8153. if (!maxFarmEnergy) {
  8154. return;
  8155. }
  8156. collectEnergy += +result.stamina;
  8157. if (collectEnergy >= maxFarmEnergy) {
  8158. console.log(`${I18N('STAMINA')} + ${ collectEnergy }`);
  8159. setProgress(`${I18N('STAMINA')} + ${ collectEnergy }`, false);
  8160. return;
  8161. }
  8162. } else {
  8163. setProgress(`${I18N('OPEN')}: ${lootBox - count}/${lootBox}<br>${I18N('STAMINA')}: ${collectEnergy}`, false);
  8164. console.log(result);
  8165. }
  8166. }
  8167.  
  8168. setProgress(I18N('BOXES_OVER'), true);
  8169. }
  8170.  
  8171. async function fillActive() {
  8172. const data = await Send(JSON.stringify({
  8173. calls: [{
  8174. name: "questGetAll",
  8175. args: {},
  8176. ident: "questGetAll"
  8177. }, {
  8178. name: "inventoryGet",
  8179. args: {},
  8180. ident: "inventoryGet"
  8181. }, {
  8182. name: "clanGetInfo",
  8183. args: {},
  8184. ident: "clanGetInfo"
  8185. }
  8186. ]
  8187. })).then(e => e.results.map(n => n.result.response));
  8188.  
  8189. const quests = data[0];
  8190. const inv = data[1];
  8191. const stat = data[2].stat;
  8192. const maxActive = 2000 - stat.todayItemsActivity;
  8193. if (maxActive <= 0) {
  8194. setProgress(I18N('NO_MORE_ACTIVITY'), true);
  8195. return;
  8196. }
  8197.  
  8198. let countGetActive = 0;
  8199. const quest = quests.find(e => e.id > 10046 && e.id < 10051);
  8200. if (quest) {
  8201. countGetActive = 1750 - quest.progress;
  8202. }
  8203.  
  8204. if (countGetActive <= 0) {
  8205. countGetActive = maxActive;
  8206. }
  8207. console.log(countGetActive);
  8208.  
  8209. countGetActive = +(await popup.confirm(I18N('EXCHANGE_ITEMS', { maxActive }), [
  8210. { result: false, isClose: true },
  8211. { msg: I18N('GET_ACTIVITY'), isInput: true, default: countGetActive.toString() },
  8212. ]));
  8213.  
  8214. if (!countGetActive) {
  8215. return;
  8216. }
  8217.  
  8218. if (countGetActive > maxActive) {
  8219. countGetActive = maxActive;
  8220. }
  8221.  
  8222. const items = lib.getData('inventoryItem');
  8223.  
  8224. let itemsInfo = [];
  8225. for (let type of ['gear', 'scroll']) {
  8226. for (let i in inv[type]) {
  8227. const v = items[type][i]?.enchantValue || 0;
  8228. itemsInfo.push({
  8229. id: i,
  8230. count: inv[type][i],
  8231. v,
  8232. type
  8233. })
  8234. }
  8235. const invType = 'fragment' + type.toLowerCase().charAt(0).toUpperCase() + type.slice(1);
  8236. for (let i in inv[invType]) {
  8237. const v = items[type][i]?.fragmentEnchantValue || 0;
  8238. itemsInfo.push({
  8239. id: i,
  8240. count: inv[invType][i],
  8241. v,
  8242. type: invType
  8243. })
  8244. }
  8245. }
  8246. itemsInfo = itemsInfo.filter(e => e.v < 4 && e.count > 200);
  8247. itemsInfo = itemsInfo.sort((a, b) => b.count - a.count);
  8248. console.log(itemsInfo);
  8249. const activeItem = itemsInfo.shift();
  8250. console.log(activeItem);
  8251. const countItem = Math.ceil(countGetActive / activeItem.v);
  8252. if (countItem > activeItem.count) {
  8253. setProgress(I18N('NOT_ENOUGH_ITEMS'), true);
  8254. console.log(activeItem);
  8255. return;
  8256. }
  8257.  
  8258. await Send(JSON.stringify({
  8259. calls: [{
  8260. name: "clanItemsForActivity",
  8261. args: {
  8262. items: {
  8263. [activeItem.type]: {
  8264. [activeItem.id]: countItem
  8265. }
  8266. }
  8267. },
  8268. ident: "body"
  8269. }]
  8270. })).then(e => {
  8271. /** TODO: Вывести потраченые предметы */
  8272. console.log(e);
  8273. setProgress(`${I18N('ACTIVITY_RECEIVED')}: ` + e.results[0].result.response, true);
  8274. });
  8275. }
  8276.  
  8277. async function buyHeroFragments() {
  8278. const result = await Send('{"calls":[{"name":"inventoryGet","args":{},"ident":"inventoryGet"},{"name":"shopGetAll","args":{},"ident":"shopGetAll"}]}')
  8279. .then(e => e.results.map(n => n.result.response));
  8280. const inv = result[0];
  8281. const shops = Object.values(result[1]).filter(shop => [4, 5, 6, 8, 9, 10, 17].includes(shop.id));
  8282. const calls = [];
  8283.  
  8284. for (let shop of shops) {
  8285. const slots = Object.values(shop.slots);
  8286. for (const slot of slots) {
  8287. /* Уже куплено */
  8288. if (slot.bought) {
  8289. continue;
  8290. }
  8291. /* Не душа героя */
  8292. if (!('fragmentHero' in slot.reward)) {
  8293. continue;
  8294. }
  8295. const coin = Object.keys(slot.cost).pop();
  8296. const coinId = Object.keys(slot.cost[coin]).pop();
  8297. const stock = inv[coin][coinId] || 0;
  8298. /* Не хватает на покупку */
  8299. if (slot.cost[coin][coinId] > stock) {
  8300. continue;
  8301. }
  8302. inv[coin][coinId] -= slot.cost[coin][coinId];
  8303. calls.push({
  8304. name: "shopBuy",
  8305. args: {
  8306. shopId: shop.id,
  8307. slot: slot.id,
  8308. cost: slot.cost,
  8309. reward: slot.reward,
  8310. },
  8311. ident: `shopBuy_${shop.id}_${slot.id}`,
  8312. })
  8313. }
  8314. }
  8315.  
  8316. if (!calls.length) {
  8317. setProgress(I18N('NO_PURCHASABLE_HERO_SOULS'), true);
  8318. return;
  8319. }
  8320.  
  8321. const bought = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8322. if (!bought) {
  8323. console.log('что-то пошло не так')
  8324. return;
  8325. }
  8326.  
  8327. let countHeroSouls = 0;
  8328. for (const buy of bought) {
  8329. countHeroSouls += +Object.values(Object.values(buy).pop()).pop();
  8330. }
  8331. console.log(countHeroSouls, bought, calls);
  8332. setProgress(I18N('PURCHASED_HERO_SOULS', { countHeroSouls }), true);
  8333. }
  8334.  
  8335. /** Открыть платные сундуки в Запределье за 90 */
  8336. async function bossOpenChestPay() {
  8337. const callsNames = ['userGetInfo', 'bossGetAll', 'specialOffer_getAll', 'getTime'];
  8338. const info = await Send({ calls: callsNames.map((name) => ({ name, args: {}, ident: name })) }).then((e) =>
  8339. e.results.map((n) => n.result.response)
  8340. );
  8341. const user = info[0];
  8342. const boses = info[1];
  8343. const offers = info[2];
  8344. const time = info[3];
  8345. const discountOffer = offers.find((e) => e.offerType == 'costReplaceOutlandChest');
  8346. let discount = 1;
  8347. if (discountOffer && discountOffer.endTime > time) {
  8348. discount = 1 - discountOffer.offerData.outlandChest.discountPercent / 100;
  8349. }
  8350. cost9chests = 540 * discount;
  8351. cost18chests = 1740 * discount;
  8352. costFirstChest = 90 * discount;
  8353. costSecondChest = 200 * discount;
  8354. const currentStarMoney = user.starMoney;
  8355. if (currentStarMoney < cost9chests) {
  8356. setProgress('Недостаточно изюма, нужно ' + cost9chests + ' у Вас ' + currentStarMoney, true);
  8357. return;
  8358. }
  8359. const imgEmerald =
  8360. "<img style='position: relative;top: 3px;' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAXCAYAAAD+4+QTAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAY8SURBVEhLpVV5bFVlFv/d7a19W3tfN1pKabGFAm3Rlg4toAWRiH+AioiaqAkaE42NycRR0ZnomJnJYHAJERGNyx/GJYoboo2igKVSMUUKreW1pRvUvr7XvvXe9+7qeW1nGJaJycwvObnny/fl/L7zO+c7l8EV0LAKzA+H83lAFAC/BeDJN2gnc5yd/WaQ8Q0NCCnAANkU+ZfjIpKqJWBOd4EDbHagueBPb1tWuesi9Rqn86zJZDbAMTp4xoSFzMaa4FVe6fra3bbzQbYN6A8Cmrz0qoBx8gzMmaj/QfKHWyxs+4e1DiC78M9v5TTn1RtbVH+kMWlJCCad100VOmQiUWFnNLg4HW42QeYEl3KnIiP5Bzu/dr27o0UistD48k2d8rF9Sib9GZKaejAnOmrs2/6e3VR3q7idF41GWVA41uQQ1RMY00ZJrChcrAYvx8HHaSjil8LLilCY98BORylBKlWQHhjzfvfFnuTfPn1O+xFolzM7s5nMI80rSl7qib8ykRNcWyaUosBWgnN6BL3pHuRwucjmnBTUCjfHwElkNiaNPHYr0mYCKnMeE/r3OC2NQiZZheHsfQ9Vu1uAM+eBIX2W5Nqsh/ewtxlrhl75NtUviDpwq+s+NOXWwWFhKKCd6iCQVByV2qSb0wEo5PvhY9YikGrH3uAdiBtBDIdVVAvlyfjBOffuesTcDxySqD3mUxaOPLZ6aktAOS/kqHaYigN7gnsxMGnDAuEuiPw6ymIt3MwaZFFQB7MeTmYjPLSWjTTCioQ5XCOMJIPeoInD/SNOviy6heLmALkckRTyf3xLbtQ8k6sdOodcxoocMoXU9JoFdF8VESMMiWRJmykyedqXTInaQJnOTtYDcJtZ+DXkRSrOou1cCoHx4LptL0nLgYU8kWhwlFgrNV2wFnEmVAr+w9gUzkwQic2DoNmLYe0QgkYXIuYg4uYYosYQJs1fMGkEpqWzUVucDh9E37gCIWFgvY9FcbniEipii6hbwZVilP0kXB/jysrrPLqU3yDG0JzXhA3OjWgsXo8UG6XbR6AxScqJjJHo/gmY0+9FIOn80I0UkukQFohJNFZmwV/uhosX2j59KPuF8JgS5CI3wHB90RUdKL12pMs7Z3VvfH6WyOajPt+Deb7FRDCBmNmNpNmPhHEWCW0IMXUQaTVEtVPhseYTZRCBeB86h8+hY0yDodsHfny+4NETB7JOLN74TXqmu1Yu4ixHuj3ii0/eaatx7RgY/NYKtR2tm+6B7lbwTGg3bDQ06MLTcsoJettR4DqaC8+u/gfe6HwZOzuGQU8JDR5f1B2+6uHWp8RPSjfsj5/dDyMzfIAj3bqSK8bGW579ECPWXRViHTijDK2BPojcPCxkbXCZflh1H5ISkCCSWJxI8jcjmErhnaHh6fdzdbZTd0aKd7Q+5T/gqj6VyBBkwmfG0QySkkHDJq19dDrgvP3GQq/Pt6h/8mesLqqFz+6DRq0qWkR4uGzEYhrGJBktNdvQGfoJH490YwmNuwKt+LWvWubtAk6GlPHhfw/LCyQz0BXEZOaoLcDf1lAt2z1z5nIhlIsL0Csfo90sWDkHXDYXaq2VWFZShffOfoQc0qOIzT9wbGvpXxOYGgG6SdwLuJSE6mPT1ZNdUdM9fyi8YlnTEiHLc423GBPaFBSVQcrQqcMYrJrbjElVRUf8FIq57K4z/8x7rL9f7ymsb0vHz83GmsXlJJSlsXKhxn3w+YSyrC48vKB0zVbLYqHCUYEe5SekaRYznBuLvU1olwbBmvr4r/v4RzteN4761x+Wxg9dGPH/wkzhL8WRHkMvKo7j/sc/Swfir7ZT/WTYSapc6LwFhc4qSKwLEYHXoz/bnzv8dOw7+4ojyYkvLyfI4MokhNToSKZwYf+6u3e39P3y8XH6AeY5yxHiBcx11OA8rZO9qTdaNx9/n9KPyUdnOulKuFyui6GHAAkHpEDBptqauaKtcMySRBW3HH2Do1+9WbP9GXocVGj5okJfit8jATY06Dh+MBIyiwZrrylb4XXneO1BV9df7n/tMb0/0J17O9LJU7Nn/x+UrKvOyOq58dXtNz0Q2Luz+cUnrqe1q+qmyv8q9/+EypuXZrK2kdEwgW3R5pW/r8I0gN8AVk6uP7Y929oAAAAASUVORK5CYII='>";
  8361. if (currentStarMoney < cost9chests) {
  8362. setProgress(I18N('NOT_ENOUGH_EMERALDS_540', { currentStarMoney, imgEmerald }), true);
  8363. return;
  8364. }
  8365. const buttons = [{ result: false, isClose: true }];
  8366. if (currentStarMoney >= cost9chests) {
  8367. buttons.push({
  8368. msg: I18N('BUY_OUTLAND_BTN', { count: 9, countEmerald: cost9chests, imgEmerald }),
  8369. result: [costFirstChest, costFirstChest, 0],
  8370. });
  8371. }
  8372. if (currentStarMoney >= cost18chests) {
  8373. buttons.push({
  8374. msg: I18N('BUY_OUTLAND_BTN', { count: 18, countEmerald: cost18chests, imgEmerald }),
  8375. result: [costFirstChest, costFirstChest, 0, costSecondChest, costSecondChest, 0],
  8376. });
  8377. }
  8378. const answer = await popup.confirm(`<div style="margin-bottom: 15px;">${I18N('BUY_OUTLAND')}</div>`, buttons);
  8379. if (!answer) {
  8380. return;
  8381. }
  8382. const callBoss = [];
  8383. let n = 0;
  8384. for (let boss of boses) {
  8385. const bossId = boss.id;
  8386. if (boss.chestNum != 2) {
  8387. continue;
  8388. }
  8389. const calls = [];
  8390. for (const starmoney of answer) {
  8391. calls.push({
  8392. name: 'bossOpenChest',
  8393. args: {
  8394. amount: 1,
  8395. bossId,
  8396. starmoney,
  8397. },
  8398. ident: 'bossOpenChest_' + ++n,
  8399. });
  8400. }
  8401. callBoss.push(calls);
  8402. }
  8403. if (!callBoss.length) {
  8404. setProgress(I18N('CHESTS_NOT_AVAILABLE'), true);
  8405. return;
  8406. }
  8407. let count = 0;
  8408. let errors = 0;
  8409. for (const calls of callBoss) {
  8410. const result = await Send({ calls });
  8411. console.log(result);
  8412. if (result?.results) {
  8413. count += result.results.length;
  8414. } else {
  8415. errors++;
  8416. }
  8417. }
  8418. setProgress(`${I18N('OUTLAND_CHESTS_RECEIVED')}: ${count}`, true);
  8419. }
  8420.  
  8421. async function autoRaidAdventure() {
  8422. const calls = [
  8423. {
  8424. name: "userGetInfo",
  8425. args: {},
  8426. ident: "userGetInfo"
  8427. },
  8428. {
  8429. name: "adventure_raidGetInfo",
  8430. args: {},
  8431. ident: "adventure_raidGetInfo"
  8432. }
  8433. ];
  8434. const result = await Send(JSON.stringify({ calls }))
  8435. .then(e => e.results.map(n => n.result.response));
  8436.  
  8437. const portalSphere = result[0].refillable.find(n => n.id == 45);
  8438. const adventureRaid = Object.entries(result[1].raid).filter(e => e[1]).pop()
  8439. const adventureId = adventureRaid ? adventureRaid[0] : 0;
  8440.  
  8441. if (!portalSphere.amount || !adventureId) {
  8442. setProgress(I18N('RAID_NOT_AVAILABLE'), true);
  8443. return;
  8444. }
  8445.  
  8446. const countRaid = +(await popup.confirm(I18N('RAID_ADVENTURE', { adventureId }), [
  8447. { result: false, isClose: true },
  8448. { msg: I18N('RAID'), isInput: true, default: portalSphere.amount },
  8449. ]));
  8450.  
  8451. if (!countRaid) {
  8452. return;
  8453. }
  8454.  
  8455. if (countRaid > portalSphere.amount) {
  8456. countRaid = portalSphere.amount;
  8457. }
  8458.  
  8459. const resultRaid = await Send(JSON.stringify({
  8460. calls: [...Array(countRaid)].map((e, i) => ({
  8461. name: "adventure_raid",
  8462. args: {
  8463. adventureId
  8464. },
  8465. ident: `body_${i}`
  8466. }))
  8467. })).then(e => e.results.map(n => n.result.response));
  8468.  
  8469. if (!resultRaid.length) {
  8470. console.log(resultRaid);
  8471. setProgress(I18N('SOMETHING_WENT_WRONG'), true);
  8472. return;
  8473. }
  8474.  
  8475. console.log(resultRaid, adventureId, portalSphere.amount);
  8476. setProgress(I18N('ADVENTURE_COMPLETED', { adventureId, times: resultRaid.length }), true);
  8477. }
  8478.  
  8479. /** Вывести всю клановую статистику в консоль браузера */
  8480. async function clanStatistic() {
  8481. const copy = function (text) {
  8482. const copyTextarea = document.createElement("textarea");
  8483. copyTextarea.style.opacity = "0";
  8484. copyTextarea.textContent = text;
  8485. document.body.appendChild(copyTextarea);
  8486. copyTextarea.select();
  8487. document.execCommand("copy");
  8488. document.body.removeChild(copyTextarea);
  8489. delete copyTextarea;
  8490. }
  8491. const calls = [
  8492. { name: "clanGetInfo", args: {}, ident: "clanGetInfo" },
  8493. { name: "clanGetWeeklyStat", args: {}, ident: "clanGetWeeklyStat" },
  8494. { name: "clanGetLog", args: {}, ident: "clanGetLog" },
  8495. ];
  8496.  
  8497. const result = await Send(JSON.stringify({ calls }));
  8498.  
  8499. const dataClanInfo = result.results[0].result.response;
  8500. const dataClanStat = result.results[1].result.response;
  8501. const dataClanLog = result.results[2].result.response;
  8502.  
  8503. const membersStat = {};
  8504. for (let i = 0; i < dataClanStat.stat.length; i++) {
  8505. membersStat[dataClanStat.stat[i].id] = dataClanStat.stat[i];
  8506. }
  8507.  
  8508. const joinStat = {};
  8509. historyLog = dataClanLog.history;
  8510. for (let j in historyLog) {
  8511. his = historyLog[j];
  8512. if (his.event == 'join') {
  8513. joinStat[his.userId] = his.ctime;
  8514. }
  8515. }
  8516.  
  8517. const infoArr = [];
  8518. const members = dataClanInfo.clan.members;
  8519. for (let n in members) {
  8520. var member = [
  8521. n,
  8522. members[n].name,
  8523. members[n].level,
  8524. dataClanInfo.clan.warriors.includes(+n) ? 1 : 0,
  8525. (new Date(members[n].lastLoginTime * 1000)).toLocaleString().replace(',', ''),
  8526. joinStat[n] ? (new Date(joinStat[n] * 1000)).toLocaleString().replace(',', '') : '',
  8527. membersStat[n].activity.reverse().join('\t'),
  8528. membersStat[n].adventureStat.reverse().join('\t'),
  8529. membersStat[n].clanGifts.reverse().join('\t'),
  8530. membersStat[n].clanWarStat.reverse().join('\t'),
  8531. membersStat[n].dungeonActivity.reverse().join('\t'),
  8532. ];
  8533. infoArr.push(member);
  8534. }
  8535. const info = infoArr.sort((a, b) => (b[2] - a[2])).map((e) => e.join('\t')).join('\n');
  8536. console.log(info);
  8537. copy(info);
  8538. setProgress(I18N('CLAN_STAT_COPY'), true);
  8539. }
  8540.  
  8541. async function buyInStoreForGold() {
  8542. const result = await Send('{"calls":[{"name":"shopGetAll","args":{},"ident":"body"},{"name":"userGetInfo","args":{},"ident":"userGetInfo"}]}').then(e => e.results.map(n => n.result.response));
  8543. const shops = result[0];
  8544. const user = result[1];
  8545. let gold = user.gold;
  8546. const calls = [];
  8547. if (shops[17]) {
  8548. const slots = shops[17].slots;
  8549. for (let i = 1; i <= 2; i++) {
  8550. if (!slots[i].bought) {
  8551. const costGold = slots[i].cost.gold;
  8552. if ((gold - costGold) < 0) {
  8553. continue;
  8554. }
  8555. gold -= costGold;
  8556. calls.push({
  8557. name: "shopBuy",
  8558. args: {
  8559. shopId: 17,
  8560. slot: i,
  8561. cost: slots[i].cost,
  8562. reward: slots[i].reward,
  8563. },
  8564. ident: 'body_' + i,
  8565. })
  8566. }
  8567. }
  8568. }
  8569. const slots = shops[1].slots;
  8570. for (let i = 4; i <= 6; i++) {
  8571. if (!slots[i].bought && slots[i]?.cost?.gold) {
  8572. const costGold = slots[i].cost.gold;
  8573. if ((gold - costGold) < 0) {
  8574. continue;
  8575. }
  8576. gold -= costGold;
  8577. calls.push({
  8578. name: "shopBuy",
  8579. args: {
  8580. shopId: 1,
  8581. slot: i,
  8582. cost: slots[i].cost,
  8583. reward: slots[i].reward,
  8584. },
  8585. ident: 'body_' + i,
  8586. })
  8587. }
  8588. }
  8589.  
  8590. if (!calls.length) {
  8591. setProgress(I18N('NOTHING_BUY'), true);
  8592. return;
  8593. }
  8594.  
  8595. const resultBuy = await Send(JSON.stringify({ calls })).then(e => e.results.map(n => n.result.response));
  8596. console.log(resultBuy);
  8597. const countBuy = resultBuy.length;
  8598. setProgress(I18N('LOTS_BOUGHT', { countBuy }), true);
  8599. }
  8600.  
  8601. function rewardsAndMailFarm() {
  8602. return new Promise(function (resolve, reject) {
  8603. let questGetAllCall = {
  8604. calls: [{
  8605. name: "questGetAll",
  8606. args: {},
  8607. ident: "questGetAll"
  8608. }, {
  8609. name: "mailGetAll",
  8610. args: {},
  8611. ident: "mailGetAll"
  8612. }]
  8613. }
  8614. send(JSON.stringify(questGetAllCall), function (data) {
  8615. if (!data) return;
  8616. const questGetAll = data.results[0].result.response.filter((e) => e.state == 2);
  8617. const questBattlePass = lib.getData('quest').battlePass;
  8618. const questChainBPass = lib.getData('battlePass').questChain;
  8619. const listBattlePass = lib.getData('battlePass').list;
  8620.  
  8621. const questAllFarmCall = {
  8622. calls: [],
  8623. };
  8624. const questIds = [];
  8625. for (let quest of questGetAll) {
  8626. if (quest.id >= 2001e4) {
  8627. continue;
  8628. }
  8629. if (quest.id > 1e6 && quest.id < 2e7) {
  8630. const questInfo = questBattlePass[quest.id];
  8631. const chain = questChainBPass[questInfo.chain];
  8632. if (chain.requirement?.battlePassTicket) {
  8633. continue;
  8634. }
  8635. const battlePass = listBattlePass[chain.battlePass];
  8636. const startTime = battlePass.startCondition.time.value * 1e3
  8637. const endTime = new Date(startTime + battlePass.duration * 1e3);
  8638. if (startTime > Date.now() || endTime < Date.now()) {
  8639. continue;
  8640. }
  8641. }
  8642. if (quest.id >= 2e7) {
  8643. questIds.push(quest.id);
  8644. continue;
  8645. }
  8646. questAllFarmCall.calls.push({
  8647. name: 'questFarm',
  8648. args: {
  8649. questId: quest.id,
  8650. },
  8651. ident: `questFarm_${quest.id}`,
  8652. });
  8653. }
  8654.  
  8655. if (questIds.length) {
  8656. questAllFarmCall.calls.push({
  8657. name: 'quest_questsFarm',
  8658. args: { questIds },
  8659. ident: 'quest_questsFarm',
  8660. });
  8661. }
  8662.  
  8663. let letters = data?.results[1]?.result?.response?.letters;
  8664. letterIds = lettersFilter(letters);
  8665.  
  8666. if (letterIds.length) {
  8667. questAllFarmCall.calls.push({
  8668. name: 'mailFarm',
  8669. args: { letterIds },
  8670. ident: 'mailFarm',
  8671. });
  8672. }
  8673.  
  8674. if (!questAllFarmCall.calls.length) {
  8675. setProgress(I18N('NOTHING_TO_COLLECT'), true);
  8676. resolve();
  8677. return;
  8678. }
  8679.  
  8680. send(JSON.stringify(questAllFarmCall), async function (res) {
  8681. let countQuests = 0;
  8682. let countMail = 0;
  8683. let questsIds = [];
  8684. for (let call of res.results) {
  8685. if (call.ident.includes('questFarm')) {
  8686. countQuests++;
  8687. } else if (call.ident.includes('questsFarm')) {
  8688. countQuests += Object.keys(call.result.response).length;
  8689. } else if (call.ident.includes('mailFarm')) {
  8690. countMail = Object.keys(call.result.response).length;
  8691. }
  8692.  
  8693. const newQuests = call.result.newQuests;
  8694. if (newQuests) {
  8695. for (let quest of newQuests) {
  8696. if ((quest.id < 1e6 || (quest.id >= 2e7 && quest.id < 2001e4)) && quest.state == 2) {
  8697. questsIds.push(quest.id);
  8698. }
  8699. }
  8700. }
  8701. }
  8702. while (questsIds.length) {
  8703. const questIds = [];
  8704. const calls = [];
  8705. for (let questId of questsIds) {
  8706. if (questId < 1e6) {
  8707. calls.push({
  8708. name: 'questFarm',
  8709. args: {
  8710. questId,
  8711. },
  8712. ident: `questFarm_${questId}`,
  8713. });
  8714. countQuests++;
  8715. } else if (questId >= 2e7 && questId < 2001e4) {
  8716. questIds.push(questId);
  8717. countQuests++;
  8718. }
  8719. }
  8720. calls.push({
  8721. name: 'quest_questsFarm',
  8722. args: { questIds },
  8723. ident: 'body',
  8724. });
  8725. const results = await Send({ calls }).then((e) => e.results.map((e) => e.result));
  8726. questsIds = [];
  8727. for (const result of results) {
  8728. const newQuests = result.newQuests;
  8729. if (newQuests) {
  8730. for (let quest of newQuests) {
  8731. if (quest.state == 2) {
  8732. questsIds.push(quest.id);
  8733. }
  8734. }
  8735. }
  8736. }
  8737. }
  8738. setProgress(I18N('COLLECT_REWARDS_AND_MAIL', { countQuests, countMail }), true);
  8739. resolve();
  8740. });
  8741. });
  8742. })
  8743. }
  8744.  
  8745. class epicBrawl {
  8746. timeout = null;
  8747. time = null;
  8748.  
  8749. constructor() {
  8750. if (epicBrawl.inst) {
  8751. return epicBrawl.inst;
  8752. }
  8753. epicBrawl.inst = this;
  8754. return this;
  8755. }
  8756.  
  8757. runTimeout(func, timeDiff) {
  8758. const worker = new Worker(URL.createObjectURL(new Blob([`
  8759. self.onmessage = function(e) {
  8760. const timeDiff = e.data;
  8761.  
  8762. if (timeDiff > 0) {
  8763. setTimeout(() => {
  8764. self.postMessage(1);
  8765. self.close();
  8766. }, timeDiff);
  8767. }
  8768. };
  8769. `])));
  8770. worker.postMessage(timeDiff);
  8771. worker.onmessage = () => {
  8772. func();
  8773. };
  8774. return true;
  8775. }
  8776.  
  8777. timeDiff(date1, date2) {
  8778. const date1Obj = new Date(date1);
  8779. const date2Obj = new Date(date2);
  8780.  
  8781. const timeDiff = Math.abs(date2Obj - date1Obj);
  8782.  
  8783. const totalSeconds = timeDiff / 1000;
  8784. const minutes = Math.floor(totalSeconds / 60);
  8785. const seconds = Math.floor(totalSeconds % 60);
  8786.  
  8787. const formattedMinutes = String(minutes).padStart(2, '0');
  8788. const formattedSeconds = String(seconds).padStart(2, '0');
  8789.  
  8790. return `${formattedMinutes}:${formattedSeconds}`;
  8791. }
  8792.  
  8793. check() {
  8794. console.log(new Date(this.time))
  8795. if (Date.now() > this.time) {
  8796. this.timeout = null;
  8797. this.start()
  8798. return;
  8799. }
  8800. this.timeout = this.runTimeout(() => this.check(), 6e4);
  8801. return this.timeDiff(this.time, Date.now())
  8802. }
  8803.  
  8804. async start() {
  8805. if (this.timeout) {
  8806. const time = this.timeDiff(this.time, Date.now());
  8807. console.log(new Date(this.time))
  8808. setProgress(I18N('TIMER_ALREADY', { time }), false, hideProgress);
  8809. return;
  8810. }
  8811. setProgress(I18N('EPIC_BRAWL'), false, hideProgress);
  8812. 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));
  8813. const refill = teamInfo[2].refillable.find(n => n.id == 52)
  8814. this.time = (refill.lastRefill + 3600) * 1000
  8815. const attempts = refill.amount;
  8816. if (!attempts) {
  8817. console.log(new Date(this.time));
  8818. const time = this.check();
  8819. setProgress(I18N('NO_ATTEMPTS_TIMER_START', { time }), false, hideProgress);
  8820. return;
  8821. }
  8822.  
  8823. if (!teamInfo[0].epic_brawl) {
  8824. setProgress(I18N('NO_HEROES_PACK'), false, hideProgress);
  8825. return;
  8826. }
  8827.  
  8828. const args = {
  8829. heroes: teamInfo[0].epic_brawl.filter(e => e < 1000),
  8830. pet: teamInfo[0].epic_brawl.filter(e => e > 6000).pop(),
  8831. favor: teamInfo[1].epic_brawl,
  8832. }
  8833.  
  8834. let wins = 0;
  8835. let coins = 0;
  8836. let streak = { progress: 0, nextStage: 0 };
  8837. for (let i = attempts; i > 0; i--) {
  8838. const info = await Send(JSON.stringify({
  8839. calls: [
  8840. { name: "epicBrawl_getEnemy", args: {}, ident: "epicBrawl_getEnemy" }, { name: "epicBrawl_startBattle", args, ident: "epicBrawl_startBattle" }
  8841. ]
  8842. })).then(e => e.results.map(n => n.result.response));
  8843.  
  8844. const { progress, result } = await Calc(info[1].battle);
  8845. 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));
  8846.  
  8847. const resultInfo = endResult[0].result;
  8848. streak = endResult[1];
  8849.  
  8850. wins += resultInfo.win;
  8851. coins += resultInfo.reward ? resultInfo.reward.coin[39] : 0;
  8852.  
  8853. console.log(endResult[0].result)
  8854. if (endResult[1].progress == endResult[1].nextStage) {
  8855. const farm = await Send('{"calls":[{"name":"epicBrawl_farmWinStreak","args":{},"ident":"body"}]}').then(e => e.results[0].result.response);
  8856. coins += farm.coin[39];
  8857. }
  8858.  
  8859. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8860. i, wins, attempts, coins,
  8861. progress: streak.progress,
  8862. nextStage: streak.nextStage,
  8863. end: '',
  8864. }), false, hideProgress);
  8865. }
  8866.  
  8867. console.log(new Date(this.time));
  8868. const time = this.check();
  8869. setProgress(I18N('EPIC_BRAWL_RESULT', {
  8870. wins, attempts, coins,
  8871. i: '',
  8872. progress: streak.progress,
  8873. nextStage: streak.nextStage,
  8874. end: I18N('ATTEMPT_ENDED', { time }),
  8875. }), false, hideProgress);
  8876. }
  8877. }
  8878. /* тест остановка подземки*/
  8879. function stopDungeon(e) {
  8880. stopDung = true;
  8881. }
  8882.  
  8883. function countdownTimer(seconds, message) {
  8884. message = message || I18N('TIMER');
  8885. const stopTimer = Date.now() + seconds * 1e3
  8886. return new Promise(resolve => {
  8887. const interval = setInterval(async () => {
  8888. const now = Date.now();
  8889. setProgress(`${message} ${((stopTimer - now) / 1000).toFixed(2)}`, false);
  8890. if (now > stopTimer) {
  8891. clearInterval(interval);
  8892. setProgress('', 1);
  8893. resolve();
  8894. }
  8895. }, 100);
  8896. });
  8897. }
  8898.  
  8899. /** Набить килов в горниле душк */
  8900. async function bossRatingEventSouls() {
  8901. const data = await Send({
  8902. calls: [
  8903. { name: "heroGetAll", args: {}, ident: "teamGetAll" },
  8904. { name: "offerGetAll", args: {}, ident: "offerGetAll" },
  8905. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  8906. ]
  8907. });
  8908. const bossEventInfo = data.results[1].result.response.find(e => e.offerType == "bossEvent");
  8909. if (!bossEventInfo) {
  8910. setProgress('Эвент завершен', true);
  8911. return;
  8912. }
  8913.  
  8914. if (bossEventInfo.progress.score > 250) {
  8915. setProgress('Уже убито больше 250 врагов');
  8916. rewardBossRatingEventSouls();
  8917. return;
  8918. }
  8919. const availablePets = Object.values(data.results[2].result.response).map(e => e.id);
  8920. const heroGetAllList = data.results[0].result.response;
  8921. const usedHeroes = bossEventInfo.progress.usedHeroes;
  8922. const heroList = [];
  8923.  
  8924. for (let heroId in heroGetAllList) {
  8925. let hero = heroGetAllList[heroId];
  8926. if (usedHeroes.includes(hero.id)) {
  8927. continue;
  8928. }
  8929. heroList.push(hero.id);
  8930. }
  8931.  
  8932. if (!heroList.length) {
  8933. setProgress('Нет героев', true);
  8934. return;
  8935. }
  8936.  
  8937. const pet = availablePets.includes(6005) ? 6005 : availablePets[Math.floor(Math.random() * availablePets.length)];
  8938. const petLib = lib.getData('pet');
  8939. let count = 1;
  8940.  
  8941. for (const heroId of heroList) {
  8942. const args = {
  8943. heroes: [heroId],
  8944. pet
  8945. }
  8946. /** Поиск питомца для героя */
  8947. for (const petId of availablePets) {
  8948. if (petLib[petId].favorHeroes.includes(heroId)) {
  8949. args.favor = {
  8950. [heroId]: petId
  8951. }
  8952. break;
  8953. }
  8954. }
  8955.  
  8956. const calls = [{
  8957. name: "bossRatingEvent_startBattle",
  8958. args,
  8959. ident: "body"
  8960. }, {
  8961. name: "offerGetAll",
  8962. args: {},
  8963. ident: "offerGetAll"
  8964. }];
  8965.  
  8966. const res = await Send({ calls });
  8967. count++;
  8968.  
  8969. if ('error' in res) {
  8970. console.error(res.error);
  8971. setProgress('Перезагрузите игру и попробуйте позже', true);
  8972. return;
  8973. }
  8974.  
  8975. const eventInfo = res.results[1].result.response.find(e => e.offerType == "bossEvent");
  8976. if (eventInfo.progress.score > 250) {
  8977. break;
  8978. }
  8979. setProgress('Количество убитых врагов: ' + eventInfo.progress.score + '<br>Использовано ' + count + ' героев');
  8980. }
  8981.  
  8982. rewardBossRatingEventSouls();
  8983. }
  8984. /** Сбор награды из Горнила Душ */
  8985. async function rewardBossRatingEventSouls() {
  8986. const data = await Send({
  8987. calls: [
  8988. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  8989. ]
  8990. });
  8991.  
  8992. const bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  8993. if (!bossEventInfo) {
  8994. setProgress('Эвент завершен', true);
  8995. return;
  8996. }
  8997.  
  8998. const farmedChests = bossEventInfo.progress.farmedChests;
  8999. const score = bossEventInfo.progress.score;
  9000. // setProgress('Количество убитых врагов: ' + score);
  9001. const revard = bossEventInfo.reward;
  9002. const calls = [];
  9003.  
  9004. let count = 0;
  9005. for (let i = 1; i < 10; i++) {
  9006. if (farmedChests.includes(i)) {
  9007. continue;
  9008. }
  9009. if (score < revard[i].score) {
  9010. break;
  9011. }
  9012. calls.push({
  9013. name: "bossRatingEvent_getReward",
  9014. args: {
  9015. rewardId: i
  9016. },
  9017. ident: "body_" + i
  9018. });
  9019. count++;
  9020. }
  9021. if (!count) {
  9022. setProgress('Нечего собирать', true);
  9023. return;
  9024. }
  9025.  
  9026. Send({ calls }).then(e => {
  9027. console.log(e);
  9028. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  9029. })
  9030. }
  9031. /**
  9032. * Spin the Seer
  9033. *
  9034. * Покрутить провидца
  9035. */
  9036. async function rollAscension() {
  9037. const refillable = await Send({calls:[
  9038. {
  9039. name:"userGetInfo",
  9040. args:{},
  9041. ident:"userGetInfo"
  9042. }
  9043. ]}).then(e => e.results[0].result.response.refillable);
  9044. const i47 = refillable.find(i => i.id == 47);
  9045. if (i47?.amount) {
  9046. await Send({ calls: [{ name: "ascensionChest_open", args: { paid: false, amount: 1 }, ident: "body" }] });
  9047. setProgress(I18N('DONE'), true);
  9048. } else {
  9049. setProgress(I18N('NOT_ENOUGH_AP'), true);
  9050. }
  9051. }
  9052.  
  9053. /**
  9054. * Collect gifts for the New Year
  9055. *
  9056. * Собрать подарки на новый год
  9057. */
  9058. function getGiftNewYear() {
  9059. Send({ calls: [{ name: "newYearGiftGet", args: { type: 0 }, ident: "body" }] }).then(e => {
  9060. const gifts = e.results[0].result.response.gifts;
  9061. const calls = gifts.filter(e => e.opened == 0).map(e => ({
  9062. name: "newYearGiftOpen",
  9063. args: {
  9064. giftId: e.id
  9065. },
  9066. ident: `body_${e.id}`
  9067. }));
  9068. if (!calls.length) {
  9069. setProgress(I18N('NY_NO_GIFTS'), 5000);
  9070. return;
  9071. }
  9072. Send({ calls }).then(e => {
  9073. console.log(e.results)
  9074. const msg = I18N('NY_GIFTS_COLLECTED', { count: e.results.length });
  9075. console.log(msg);
  9076. setProgress(msg, 5000);
  9077. });
  9078. })
  9079. }
  9080.  
  9081. async function updateArtifacts() {
  9082. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9083. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9084. { result: false, isClose: true }
  9085. ]);
  9086. if (!count) {
  9087. return;
  9088. }
  9089. const quest = new questRun;
  9090. await quest.autoInit();
  9091. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9092. const inventory = quest.questInfo['inventoryGet'];
  9093. const calls = [];
  9094. for (let i = count; i > 0; i--) {
  9095. const upArtifact = quest.getUpgradeArtifact();
  9096. if (!upArtifact.heroId) {
  9097. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9098. { msg: I18N('YES'), result: true },
  9099. { result: false, isClose: true }
  9100. ])) {
  9101. break;
  9102. } else {
  9103. return;
  9104. }
  9105. }
  9106. const hero = heroes.find(e => e.id == upArtifact.heroId);
  9107. hero.artifacts[upArtifact.slotId].level++;
  9108. inventory[upArtifact.costCurrency][upArtifact.costId] -= upArtifact.costValue;
  9109. calls.push({
  9110. name: "heroArtifactLevelUp",
  9111. args: {
  9112. heroId: upArtifact.heroId,
  9113. slotId: upArtifact.slotId
  9114. },
  9115. ident: `heroArtifactLevelUp_${i}`
  9116. });
  9117. }
  9118.  
  9119. if (!calls.length) {
  9120. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9121. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9122. return;
  9123. }
  9124.  
  9125. await Send(JSON.stringify({ calls })).then(e => {
  9126. if ('error' in e) {
  9127. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9128. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9129. } else {
  9130. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9131. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9132. }
  9133. });
  9134. }
  9135.  
  9136. window.sign = a => {
  9137. const i = this['\x78\x79\x7a'];
  9138. 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'))
  9139. }
  9140.  
  9141. async function updateSkins() {
  9142. const count = +await popup.confirm(I18N('SET_NUMBER_LEVELS'), [
  9143. { msg: I18N('BTN_GO'), isInput: true, default: 10 },
  9144. { result: false, isClose: true }
  9145. ]);
  9146. if (!count) {
  9147. return;
  9148. }
  9149.  
  9150. const quest = new questRun;
  9151. await quest.autoInit();
  9152. const heroes = Object.values(quest.questInfo['heroGetAll']);
  9153. const inventory = quest.questInfo['inventoryGet'];
  9154. const calls = [];
  9155. for (let i = count; i > 0; i--) {
  9156. const upSkin = quest.getUpgradeSkin();
  9157. if (!upSkin.heroId) {
  9158. if (await popup.confirm(I18N('POSSIBLE_IMPROVE_LEVELS', { count: calls.length }), [
  9159. { msg: I18N('YES'), result: true },
  9160. { result: false, isClose: true }
  9161. ])) {
  9162. break;
  9163. } else {
  9164. return;
  9165. }
  9166. }
  9167. const hero = heroes.find(e => e.id == upSkin.heroId);
  9168. hero.skins[upSkin.skinId]++;
  9169. inventory[upSkin.costCurrency][upSkin.costCurrencyId] -= upSkin.cost;
  9170. calls.push({
  9171. name: "heroSkinUpgrade",
  9172. args: {
  9173. heroId: upSkin.heroId,
  9174. skinId: upSkin.skinId
  9175. },
  9176. ident: `heroSkinUpgrade_${i}`
  9177. })
  9178. }
  9179.  
  9180. if (!calls.length) {
  9181. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9182. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9183. return;
  9184. }
  9185.  
  9186. await Send(JSON.stringify({ calls })).then(e => {
  9187. if ('error' in e) {
  9188. console.log(I18N('NOT_ENOUGH_RESOURECES'));
  9189. setProgress(I18N('NOT_ENOUGH_RESOURECES'), false);
  9190. } else {
  9191. console.log(I18N('IMPROVED_LEVELS', { count: e.results.length }));
  9192. setProgress(I18N('IMPROVED_LEVELS', { count: e.results.length }), false);
  9193. }
  9194. });
  9195. }
  9196.  
  9197. function getQuestionInfo(img, nameOnly = false) {
  9198. const libHeroes = Object.values(lib.data.hero);
  9199. const parts = img.split(':');
  9200. const id = parts[1];
  9201. switch (parts[0]) {
  9202. case 'titanArtifact_id':
  9203. return cheats.translate("LIB_TITAN_ARTIFACT_NAME_" + id);
  9204. case 'titan':
  9205. return cheats.translate("LIB_HERO_NAME_" + id);
  9206. case 'skill':
  9207. return cheats.translate("LIB_SKILL_" + id);
  9208. case 'inventoryItem_gear':
  9209. return cheats.translate("LIB_GEAR_NAME_" + id);
  9210. case 'inventoryItem_coin':
  9211. return cheats.translate("LIB_COIN_NAME_" + id);
  9212. case 'artifact':
  9213. if (nameOnly) {
  9214. return cheats.translate("LIB_ARTIFACT_NAME_" + id);
  9215. }
  9216. heroes = libHeroes.filter(h => h.id < 100 && h.artifacts.includes(+id));
  9217. return {
  9218. /** Как называется этот артефакт? */
  9219. name: cheats.translate("LIB_ARTIFACT_NAME_" + id),
  9220. /** Какому герою принадлежит этот артефакт? */
  9221. heroes: heroes.map(h => cheats.translate("LIB_HERO_NAME_" + h.id))
  9222. };
  9223. case 'hero':
  9224. if (nameOnly) {
  9225. return cheats.translate("LIB_HERO_NAME_" + id);
  9226. }
  9227. artifacts = lib.data.hero[id].artifacts;
  9228. return {
  9229. /** Как зовут этого героя? */
  9230. name: cheats.translate("LIB_HERO_NAME_" + id),
  9231. /** Какой артефакт принадлежит этому герою? */
  9232. artifact: artifacts.map(a => cheats.translate("LIB_ARTIFACT_NAME_" + a))
  9233. };
  9234. }
  9235. }
  9236.  
  9237. function hintQuest(quest) {
  9238. const result = {};
  9239. if (quest?.questionIcon) {
  9240. const info = getQuestionInfo(quest.questionIcon);
  9241. if (info?.heroes) {
  9242. /** Какому герою принадлежит этот артефакт? */
  9243. result.answer = quest.answers.filter(e => info.heroes.includes(e.answerText.slice(1)));
  9244. }
  9245. if (info?.artifact) {
  9246. /** Какой артефакт принадлежит этому герою? */
  9247. result.answer = quest.answers.filter(e => info.artifact.includes(e.answerText.slice(1)));
  9248. }
  9249. if (typeof info == 'string') {
  9250. result.info = { name: info };
  9251. } else {
  9252. result.info = info;
  9253. }
  9254. }
  9255.  
  9256. if (quest.answers[0]?.answerIcon) {
  9257. result.answer = quest.answers.filter(e => quest.question.includes(getQuestionInfo(e.answerIcon, true)))
  9258. }
  9259.  
  9260. if ((!result?.answer || !result.answer.length) && !result.info?.name) {
  9261. return false;
  9262. }
  9263.  
  9264. let resultText = '';
  9265. if (result?.info) {
  9266. resultText += I18N('PICTURE') + result.info.name;
  9267. }
  9268. console.log(result);
  9269. if (result?.answer && result.answer.length) {
  9270. resultText += I18N('ANSWER') + result.answer[0].id + (!result.answer[0].answerIcon ? ' - ' + result.answer[0].answerText : '');
  9271. }
  9272.  
  9273. return resultText;
  9274. }
  9275.  
  9276. async function farmBattlePass() {
  9277. const battlePasses = await Send({
  9278. calls: [
  9279. { name: 'battlePass_getInfo', args: {}, ident: 'getInfo' },
  9280. { name: 'battlePass_getSpecial', args: {}, ident: 'getSpecial' },
  9281. ],
  9282. }).then((e) => [e.results[0].result.response.battlePass, ...Object.values(e.results[1].result.response)]);
  9283. const calls = [];
  9284. let first = true;
  9285. for (const battlePass of battlePasses) {
  9286. const id = battlePass.id;
  9287. const bPassExp = battlePass.exp;
  9288. const bPassRewardsLvls = Object.keys(battlePass.rewards);
  9289. const bPassLevels = Object.values(lib.data.battlePass.level).filter((e) => e.battlePass === id);
  9290. for (let lvl of bPassLevels) {
  9291. if (bPassExp < lvl.experience) {
  9292. continue;
  9293. }
  9294. if (bPassRewardsLvls.includes(lvl.level.toString())) {
  9295. continue;
  9296. }
  9297. const reward = lvl.freeReward;
  9298. /** Исключения на сбор наград */
  9299. const isFarmReward = !(
  9300. (
  9301. (reward?.buff ? true : false) || // ускорение набора энергии
  9302. (reward?.fragmentHero ? true : false) || // душы героев
  9303. (reward?.bundleHeroReward ? true : false) // герои
  9304. )
  9305. );
  9306. if (isFarmReward) {
  9307. const args = {
  9308. level: lvl.level,
  9309. free: true,
  9310. };
  9311. if (!first) {
  9312. args.id = id;
  9313. }
  9314. calls.push({
  9315. name: 'battlePass_farmReward',
  9316. args,
  9317. ident: 'battlePass_farmReward_' + lvl.level + '_' + id,
  9318. });
  9319. }
  9320. }
  9321. first = false;
  9322. }
  9323. const results = await Send(JSON.stringify({ calls })).then((e) => e.results);
  9324. setProgress(I18N('SEASON_REWARD_COLLECTED', {count: results.length}), true);
  9325. }
  9326. async function sellHeroSoulsForGold() {
  9327. let { fragmentHero, heroes } = await Send({
  9328. calls: [
  9329. { name: 'inventoryGet', args: {}, ident: 'inventoryGet' },
  9330. { name: 'heroGetAll', args: {}, ident: 'heroGetAll' },
  9331. ],
  9332. })
  9333. .then((e) => e.results.map((r) => r.result.response))
  9334. .then((e) => ({ fragmentHero: e[0].fragmentHero, heroes: e[1] }));
  9335. const calls = [];
  9336. for (let i in fragmentHero) {
  9337. if (heroes[i] && heroes[i].star == 6) {
  9338. calls.push({
  9339. name: 'inventorySell',
  9340. args: {
  9341. type: 'hero',
  9342. libId: i,
  9343. amount: fragmentHero[i],
  9344. fragment: true,
  9345. },
  9346. ident: 'inventorySell_' + i,
  9347. });
  9348. }
  9349. }
  9350. if (!calls.length) {
  9351. console.log(0);
  9352. return 0;
  9353. }
  9354. const rewards = await Send({ calls }).then((e) => e.results.map((r) => r.result?.response?.gold || 0));
  9355. const gold = rewards.reduce((e, a) => e + a, 0);
  9356. setProgress(I18N('GOLD_RECEIVED', { gold }), true);
  9357. }
  9358.  
  9359. /**
  9360. * Attack of the minions of Asgard
  9361. *
  9362. * Атака прислужников Асгарда
  9363. */
  9364. function testRaidNodes() {
  9365. return new Promise((resolve, reject) => {
  9366. const tower = new executeRaidNodes(resolve, reject);
  9367. tower.start();
  9368. });
  9369. }
  9370.  
  9371. /**
  9372. * Attack of the minions of Asgard
  9373. *
  9374. * Атака прислужников Асгарда
  9375. */
  9376. function executeRaidNodes(resolve, reject) {
  9377. let raidData = {
  9378. teams: [],
  9379. favor: {},
  9380. nodes: [],
  9381. attempts: 0,
  9382. countExecuteBattles: 0,
  9383. cancelBattle: 0,
  9384. }
  9385.  
  9386. callsExecuteRaidNodes = {
  9387. calls: [{
  9388. name: "clanRaid_getInfo",
  9389. args: {},
  9390. ident: "clanRaid_getInfo"
  9391. }, {
  9392. name: "teamGetAll",
  9393. args: {},
  9394. ident: "teamGetAll"
  9395. }, {
  9396. name: "teamGetFavor",
  9397. args: {},
  9398. ident: "teamGetFavor"
  9399. }]
  9400. }
  9401.  
  9402. this.start = function () {
  9403. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  9404. }
  9405.  
  9406. async function startRaidNodes(data) {
  9407. res = data.results;
  9408. clanRaidInfo = res[0].result.response;
  9409. teamGetAll = res[1].result.response;
  9410. teamGetFavor = res[2].result.response;
  9411.  
  9412. let index = 0;
  9413. let isNotFullPack = false;
  9414. for (let team of teamGetAll.clanRaid_nodes) {
  9415. if (team.length < 6) {
  9416. isNotFullPack = true;
  9417. }
  9418. raidData.teams.push({
  9419. data: {},
  9420. heroes: team.filter(id => id < 6000),
  9421. pet: team.filter(id => id >= 6000).pop(),
  9422. battleIndex: index++
  9423. });
  9424. }
  9425. raidData.favor = teamGetFavor.clanRaid_nodes;
  9426.  
  9427. if (isNotFullPack) {
  9428. if (await popup.confirm(I18N('MINIONS_WARNING'), [
  9429. { msg: I18N('BTN_NO'), result: true },
  9430. { msg: I18N('BTN_YES'), result: false },
  9431. ])) {
  9432. endRaidNodes('isNotFullPack');
  9433. return;
  9434. }
  9435. }
  9436.  
  9437. raidData.nodes = clanRaidInfo.nodes;
  9438. raidData.attempts = clanRaidInfo.attempts;
  9439. isCancalBattle = false;
  9440.  
  9441. checkNodes();
  9442. }
  9443.  
  9444. function getAttackNode() {
  9445. for (let nodeId in raidData.nodes) {
  9446. let node = raidData.nodes[nodeId];
  9447. let points = 0
  9448. for (team of node.teams) {
  9449. points += team.points;
  9450. }
  9451. let now = Date.now() / 1000;
  9452. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  9453. let countTeam = node.teams.length;
  9454. delete raidData.nodes[nodeId];
  9455. return {
  9456. nodeId,
  9457. countTeam
  9458. };
  9459. }
  9460. }
  9461. return null;
  9462. }
  9463.  
  9464. function checkNodes() {
  9465. setProgress(`${I18N('REMAINING_ATTEMPTS')}: ${raidData.attempts}`);
  9466. let nodeInfo = getAttackNode();
  9467. if (nodeInfo && raidData.attempts) {
  9468. startNodeBattles(nodeInfo);
  9469. return;
  9470. }
  9471.  
  9472. endRaidNodes('EndRaidNodes');
  9473. }
  9474.  
  9475. function startNodeBattles(nodeInfo) {
  9476. let {nodeId, countTeam} = nodeInfo;
  9477. let teams = raidData.teams.slice(0, countTeam);
  9478. let heroes = raidData.teams.map(e => e.heroes).flat();
  9479. let favor = {...raidData.favor};
  9480. for (let heroId in favor) {
  9481. if (!heroes.includes(+heroId)) {
  9482. delete favor[heroId];
  9483. }
  9484. }
  9485.  
  9486. let calls = [{
  9487. name: "clanRaid_startNodeBattles",
  9488. args: {
  9489. nodeId,
  9490. teams,
  9491. favor
  9492. },
  9493. ident: "body"
  9494. }];
  9495.  
  9496. send(JSON.stringify({calls}), resultNodeBattles);
  9497. }
  9498.  
  9499. function resultNodeBattles(e) {
  9500. if (e['error']) {
  9501. endRaidNodes('nodeBattlesError', e['error']);
  9502. return;
  9503. }
  9504.  
  9505. console.log(e);
  9506. let battles = e.results[0].result.response.battles;
  9507. let promises = [];
  9508. let battleIndex = 0;
  9509. for (let battle of battles) {
  9510. battle.battleIndex = battleIndex++;
  9511. promises.push(calcBattleResult(battle));
  9512. }
  9513.  
  9514. Promise.all(promises)
  9515. .then(results => {
  9516. const endResults = {};
  9517. let isAllWin = true;
  9518. for (let r of results) {
  9519. isAllWin &&= r.result.win;
  9520. }
  9521. if (!isAllWin) {
  9522. cancelEndNodeBattle(results[0]);
  9523. return;
  9524. }
  9525. raidData.countExecuteBattles = results.length;
  9526. let timeout = 500;
  9527. for (let r of results) {
  9528. setTimeout(endNodeBattle, timeout, r);
  9529. timeout += 500;
  9530. }
  9531. });
  9532. }
  9533. /**
  9534. * Returns the battle calculation promise
  9535. *
  9536. * Возвращает промис расчета боя
  9537. */
  9538. function calcBattleResult(battleData) {
  9539. return new Promise(function (resolve, reject) {
  9540. BattleCalc(battleData, "get_clanPvp", resolve);
  9541. });
  9542. }
  9543. /**
  9544. * Cancels the fight
  9545. *
  9546. * Отменяет бой
  9547. */
  9548. function cancelEndNodeBattle(r) {
  9549. const fixBattle = function (heroes) {
  9550. for (const ids in heroes) {
  9551. hero = heroes[ids];
  9552. hero.energy = random(1, 999);
  9553. if (hero.hp > 0) {
  9554. hero.hp = random(1, hero.hp);
  9555. }
  9556. }
  9557. }
  9558. fixBattle(r.progress[0].attackers.heroes);
  9559. fixBattle(r.progress[0].defenders.heroes);
  9560. endNodeBattle(r);
  9561. }
  9562. /**
  9563. * Ends the fight
  9564. *
  9565. * Завершает бой
  9566. */
  9567. function endNodeBattle(r) {
  9568. let nodeId = r.battleData.result.nodeId;
  9569. let battleIndex = r.battleData.battleIndex;
  9570. let calls = [{
  9571. name: "clanRaid_endNodeBattle",
  9572. args: {
  9573. nodeId,
  9574. battleIndex,
  9575. result: r.result,
  9576. progress: r.progress
  9577. },
  9578. ident: "body"
  9579. }]
  9580.  
  9581. SendRequest(JSON.stringify({calls}), battleResult);
  9582. }
  9583. /**
  9584. * Processing the results of the battle
  9585. *
  9586. * Обработка результатов боя
  9587. */
  9588. function battleResult(e) {
  9589. if (e['error']) {
  9590. endRaidNodes('missionEndError', e['error']);
  9591. return;
  9592. }
  9593. r = e.results[0].result.response;
  9594. if (r['error']) {
  9595. if (r.reason == "invalidBattle") {
  9596. raidData.cancelBattle++;
  9597. checkNodes();
  9598. } else {
  9599. endRaidNodes('missionEndError', e['error']);
  9600. }
  9601. return;
  9602. }
  9603.  
  9604. if (!(--raidData.countExecuteBattles)) {
  9605. raidData.attempts--;
  9606. checkNodes();
  9607. }
  9608. }
  9609. /**
  9610. * Completing a task
  9611. *
  9612. * Завершение задачи
  9613. */
  9614. function endRaidNodes(reason, info) {
  9615. isCancalBattle = true;
  9616. let textCancel = raidData.cancelBattle ? ` ${I18N('BATTLES_CANCELED')}: ${raidData.cancelBattle}` : '';
  9617. setProgress(`${I18N('MINION_RAID')} ${I18N('COMPLETED')}! ${textCancel}`, true);
  9618. console.log(reason, info);
  9619. resolve();
  9620. }
  9621. }
  9622.  
  9623. /**
  9624. * Asgard Boss Attack Replay
  9625. *
  9626. * Повтор атаки босса Асгарда
  9627. */
  9628. function testBossBattle() {
  9629. return new Promise((resolve, reject) => {
  9630. const bossBattle = new executeBossBattle(resolve, reject);
  9631. bossBattle.start(lastBossBattle);
  9632. });
  9633. }
  9634.  
  9635. /**
  9636. * Asgard Boss Attack Replay
  9637. *
  9638. * Повтор атаки босса Асгарда
  9639. */
  9640. function executeBossBattle(resolve, reject) {
  9641. this.start = function (battleInfo) {
  9642. preCalcBattle(battleInfo);
  9643. }
  9644.  
  9645. function getBattleInfo(battle) {
  9646. return new Promise(function (resolve) {
  9647. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9648. BattleCalc(battle, getBattleType(battle.type), e => {
  9649. let extra = e.progress[0].defenders.heroes[1].extra;
  9650. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  9651. });
  9652. });
  9653. }
  9654.  
  9655. function preCalcBattle(battle) {
  9656. let actions = [];
  9657. const countTestBattle = getInput('countTestBattle');
  9658. for (let i = 0; i < countTestBattle; i++) {
  9659. actions.push(getBattleInfo(battle, true));
  9660. }
  9661. Promise.all(actions)
  9662. .then(resultPreCalcBattle);
  9663. }
  9664.  
  9665. async function resultPreCalcBattle(damages) {
  9666. let maxDamage = 0;
  9667. let minDamage = 1e10;
  9668. let avgDamage = 0;
  9669. for (let damage of damages) {
  9670. avgDamage += damage
  9671. if (damage > maxDamage) {
  9672. maxDamage = damage;
  9673. }
  9674. if (damage < minDamage) {
  9675. minDamage = damage;
  9676. }
  9677. }
  9678. avgDamage /= damages.length;
  9679. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  9680.  
  9681. await popup.confirm(
  9682. `${I18N('ROUND_STAT')} ${damages.length} ${I18N('BATTLE')}:` +
  9683. `<br>${I18N('MINIMUM')}: ` + minDamage.toLocaleString() +
  9684. `<br>${I18N('MAXIMUM')}: ` + maxDamage.toLocaleString() +
  9685. `<br>${I18N('AVERAGE')}: ` + avgDamage.toLocaleString()
  9686. , [
  9687. { msg: I18N('BTN_OK'), result: 0},
  9688. ])
  9689. endBossBattle(I18N('BTN_CANCEL'));
  9690. }
  9691.  
  9692. /**
  9693. * Completing a task
  9694. *
  9695. * Завершение задачи
  9696. */
  9697. function endBossBattle(reason, info) {
  9698. console.log(reason, info);
  9699. resolve();
  9700. }
  9701. }
  9702.  
  9703. /**
  9704. * Auto-repeat attack
  9705. *
  9706. * Автоповтор атаки
  9707. */
  9708. function testAutoBattle() {
  9709. return new Promise((resolve, reject) => {
  9710. const bossBattle = new executeAutoBattle(resolve, reject);
  9711. bossBattle.start(lastBattleArg, lastBattleInfo);
  9712. });
  9713. }
  9714.  
  9715. /**
  9716. * Auto-repeat attack
  9717. *
  9718. * Автоповтор атаки
  9719. */
  9720. function executeAutoBattle(resolve, reject) {
  9721. let battleArg = {};
  9722. let countBattle = 0;
  9723. let countError = 0;
  9724. let findCoeff = 0;
  9725. let dataNotEeceived = 0;
  9726. let stopAutoBattle = false;
  9727. 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>';
  9728. 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>';
  9729. 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>';
  9730.  
  9731. this.start = function (battleArgs, battleInfo) {
  9732. battleArg = battleArgs;
  9733. preCalcBattle(battleInfo);
  9734. }
  9735. /**
  9736. * Returns a promise for combat recalculation
  9737. *
  9738. * Возвращает промис для прерасчета боя
  9739. */
  9740. function getBattleInfo(battle) {
  9741. return new Promise(function (resolve) {
  9742. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  9743. Calc(battle).then(e => {
  9744. e.coeff = calcCoeff(e, 'defenders');
  9745. resolve(e);
  9746. });
  9747. });
  9748. }
  9749. /**
  9750. * Battle recalculation
  9751. *
  9752. * Прерасчет боя
  9753. */
  9754. function preCalcBattle(battle) {
  9755. let actions = [];
  9756. const countTestBattle = getInput('countTestBattle');
  9757. for (let i = 0; i < countTestBattle; i++) {
  9758. actions.push(getBattleInfo(battle));
  9759. }
  9760. Promise.all(actions)
  9761. .then(resultPreCalcBattle);
  9762. }
  9763. /**
  9764. * Processing the results of the battle recalculation
  9765. *
  9766. * Обработка результатов прерасчета боя
  9767. */
  9768. async function resultPreCalcBattle(results) {
  9769. let countWin = results.reduce((s, w) => w.result.win + s, 0);
  9770. setProgress(`${I18N('CHANCE_TO_WIN')} ${Math.floor(countWin / results.length * 100)}% (${results.length})`, false, hideProgress);
  9771. if (countWin > 0) {
  9772. isCancalBattle = false;
  9773. startBattle();
  9774. return;
  9775. }
  9776.  
  9777. let minCoeff = 100;
  9778. let maxCoeff = -100;
  9779. let avgCoeff = 0;
  9780. results.forEach(e => {
  9781. if (e.coeff < minCoeff) minCoeff = e.coeff;
  9782. if (e.coeff > maxCoeff) maxCoeff = e.coeff;
  9783. avgCoeff += e.coeff;
  9784. });
  9785. avgCoeff /= results.length;
  9786.  
  9787. if (nameFuncStartBattle == 'invasion_bossStart' ||
  9788. nameFuncStartBattle == 'bossAttack') {
  9789. const result = await popup.confirm(
  9790. I18N('BOSS_VICTORY_IMPOSSIBLE', { battles: results.length }), [
  9791. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  9792. { msg: I18N('BTN_DO_IT'), result: true },
  9793. ])
  9794. if (result) {
  9795. isCancalBattle = false;
  9796. startBattle();
  9797. return;
  9798. }
  9799. setProgress(I18N('NOT_THIS_TIME'), true);
  9800. endAutoBattle('invasion_bossStart');
  9801. return;
  9802. }
  9803.  
  9804. const result = await popup.confirm(
  9805. I18N('VICTORY_IMPOSSIBLE') +
  9806. `<br>${I18N('ROUND_STAT')} ${results.length} ${I18N('BATTLE')}:` +
  9807. `<br>${I18N('MINIMUM')}: ` + minCoeff.toLocaleString() +
  9808. `<br>${I18N('MAXIMUM')}: ` + maxCoeff.toLocaleString() +
  9809. `<br>${I18N('AVERAGE')}: ` + avgCoeff.toLocaleString() +
  9810. `<br>${I18N('FIND_COEFF')} ` + avgCoeff.toLocaleString(), [
  9811. { msg: I18N('BTN_CANCEL'), result: 0, isCancel: true },
  9812. { msg: I18N('BTN_GO'), isInput: true, default: Math.round(avgCoeff * 1000) / 1000 },
  9813. ])
  9814. if (result) {
  9815. findCoeff = result;
  9816. isCancalBattle = false;
  9817. startBattle();
  9818. return;
  9819. }
  9820. setProgress(I18N('NOT_THIS_TIME'), true);
  9821. endAutoBattle(I18N('NOT_THIS_TIME'));
  9822. }
  9823.  
  9824. /**
  9825. * Calculation of the combat result coefficient
  9826. *
  9827. * Расчет коэфициента результата боя
  9828. */
  9829. function calcCoeff(result, packType) {
  9830. let beforeSumFactor = 0;
  9831. const beforePack = result.battleData[packType][0];
  9832. for (let heroId in beforePack) {
  9833. const hero = beforePack[heroId];
  9834. const state = hero.state;
  9835. let factor = 1;
  9836. if (state) {
  9837. const hp = state.hp / state.maxHp;
  9838. const energy = state.energy / 1e3;
  9839. factor = hp + energy / 20;
  9840. }
  9841. beforeSumFactor += factor;
  9842. }
  9843.  
  9844. let afterSumFactor = 0;
  9845. const afterPack = result.progress[0][packType].heroes;
  9846. for (let heroId in afterPack) {
  9847. const hero = afterPack[heroId];
  9848. const stateHp = beforePack[heroId]?.state?.hp || beforePack[heroId]?.stats?.hp;
  9849. const hp = hero.hp / stateHp;
  9850. const energy = hero.energy / 1e3;
  9851. const factor = hp + energy / 20;
  9852. afterSumFactor += factor;
  9853. }
  9854. const resultCoeff = -(afterSumFactor - beforeSumFactor);
  9855. return Math.round(resultCoeff * 1000) / 1000;
  9856. }
  9857. /**
  9858. * Start battle
  9859. *
  9860. * Начало боя
  9861. */
  9862. function startBattle() {
  9863. countBattle++;
  9864. const countMaxBattle = getInput('countAutoBattle');
  9865. // setProgress(countBattle + '/' + countMaxBattle);
  9866. if (countBattle > countMaxBattle) {
  9867. setProgress(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`, true);
  9868. endAutoBattle(`${I18N('RETRY_LIMIT_EXCEEDED')}: ${countMaxBattle}`)
  9869. return;
  9870. }
  9871. if (stopAutoBattle) {
  9872. setProgress(I18N('STOPPED'), true);
  9873. endAutoBattle('STOPPED');
  9874. return;
  9875. }
  9876. send({calls: [{
  9877. name: nameFuncStartBattle,
  9878. args: battleArg,
  9879. ident: "body"
  9880. }]}, calcResultBattle);
  9881. }
  9882. /**
  9883. * Battle calculation
  9884. *
  9885. * Расчет боя
  9886. */
  9887. async function calcResultBattle(e) {
  9888. if ('error' in e) {
  9889. if (e.error.description === 'too many tries') {
  9890. invasionTimer += 100;
  9891. countBattle--;
  9892. countError++;
  9893. console.log(`Errors: ${countError}`, e.error);
  9894. startBattle();
  9895. return;
  9896. }
  9897. const result = await popup.confirm(I18N('ERROR_DURING_THE_BATTLE') + '<br>' + e.error.description, [
  9898. { msg: I18N('BTN_OK'), result: false },
  9899. { msg: I18N('RELOAD_GAME'), result: true },
  9900. ]);
  9901. endAutoBattle('Error', e.error);
  9902. if (result) {
  9903. location.reload();
  9904. }
  9905. return;
  9906. }
  9907. let battle = e.results[0].result.response.battle
  9908. if (nameFuncStartBattle == 'towerStartBattle' ||
  9909. nameFuncStartBattle == 'bossAttack' ||
  9910. nameFuncStartBattle == 'invasion_bossStart') {
  9911. battle = e.results[0].result.response;
  9912. }
  9913. lastBattleInfo = battle;
  9914. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  9915. }
  9916. /**
  9917. * Processing the results of the battle
  9918. *
  9919. * Обработка результатов боя
  9920. */
  9921. async function resultBattle(e) {
  9922. const isWin = e.result.win;
  9923. if (isWin) {
  9924. endBattle(e, false);
  9925. return;
  9926. } else if (isChecked('tryFixIt')) {
  9927. const cloneBattle = structuredClone(e.battleData);
  9928. const bFix = new WinFixBattle(cloneBattle);
  9929. const endTime = Date.now() + 6e4;
  9930. const result = await bFix.start(endTime, Infinity);
  9931. console.log(result);
  9932. if (result.value) {
  9933. endBattle(result, false);
  9934. return;
  9935. }
  9936. }
  9937. const countMaxBattle = getInput('countAutoBattle');
  9938. if (findCoeff) {
  9939. const coeff = calcCoeff(e, 'defenders');
  9940. setProgress(`${countBattle}/${countMaxBattle}, ${coeff}`);
  9941. if (coeff > findCoeff) {
  9942. endBattle(e, false);
  9943. return;
  9944. }
  9945. } else {
  9946. if (nameFuncStartBattle == 'invasion_bossStart') {
  9947. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  9948. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  9949. setProgress(`${svgBoss} ${bossLvl} ${svgJustice} ${justice} <br>${svgAttempt} ${countBattle}/${countMaxBattle}`, false, () => {
  9950. stopAutoBattle = true;
  9951. });
  9952. await new Promise((resolve) => setTimeout(resolve, 5000));
  9953. } else {
  9954. setProgress(`${countBattle}/${countMaxBattle}`);
  9955. }
  9956. }
  9957. if (nameFuncStartBattle == 'towerStartBattle' ||
  9958. nameFuncStartBattle == 'bossAttack' ||
  9959. nameFuncStartBattle == 'invasion_bossStart') {
  9960. startBattle();
  9961. return;
  9962. }
  9963. cancelEndBattle(e);
  9964. }
  9965. /**
  9966. * Cancel fight
  9967. *
  9968. * Отмена боя
  9969. */
  9970. function cancelEndBattle(r) {
  9971. const fixBattle = function (heroes) {
  9972. for (const ids in heroes) {
  9973. hero = heroes[ids];
  9974. hero.energy = random(1, 999);
  9975. if (hero.hp > 0) {
  9976. hero.hp = random(1, hero.hp);
  9977. }
  9978. }
  9979. }
  9980. fixBattle(r.progress[0].attackers.heroes);
  9981. fixBattle(r.progress[0].defenders.heroes);
  9982. endBattle(r, true);
  9983. }
  9984. /**
  9985. * End of the fight
  9986. *
  9987. * Завершение боя */
  9988. function endBattle(battleResult, isCancal) {
  9989. let calls = [{
  9990. name: nameFuncEndBattle,
  9991. args: {
  9992. result: battleResult.result,
  9993. progress: battleResult.progress
  9994. },
  9995. ident: "body"
  9996. }];
  9997.  
  9998. if (nameFuncStartBattle == 'invasion_bossStart') {
  9999. calls[0].args.id = lastBattleArg.id;
  10000. }
  10001.  
  10002. send(JSON.stringify({
  10003. calls
  10004. }), async e => {
  10005. console.log(e);
  10006. if (isCancal) {
  10007. startBattle();
  10008. return;
  10009. }
  10010.  
  10011. setProgress(`${I18N('SUCCESS')}!`, 5000)
  10012. if (nameFuncStartBattle == 'invasion_bossStart' ||
  10013. nameFuncStartBattle == 'bossAttack') {
  10014. const countMaxBattle = getInput('countAutoBattle');
  10015. const bossLvl = lastBattleInfo.typeId >= 130 ? lastBattleInfo.typeId : '';
  10016. const justice = lastBattleInfo?.effects?.attackers?.percentInOutDamageMod_any_99_100_300_99_1000 || 0;
  10017. const result = await popup.confirm(
  10018. I18N('BOSS_HAS_BEEN_DEF_TEXT', {
  10019. bossLvl: `${svgBoss} ${bossLvl} ${svgJustice} ${justice}`,
  10020. countBattle: svgAttempt + ' ' + countBattle,
  10021. countMaxBattle,}),
  10022. [
  10023. { msg: I18N('BTN_OK'), result: 0 },
  10024. { msg: I18N('MAKE_A_SYNC'), result: 1 },
  10025. { msg: I18N('RELOAD_GAME'), result: 2 },
  10026. ]);
  10027. if (result) {
  10028. if (result == 1) {
  10029. cheats.refreshGame();
  10030. }
  10031. if (result == 2) {
  10032. location.reload();
  10033. }
  10034. }
  10035.  
  10036. }
  10037. endAutoBattle(`${I18N('SUCCESS')}!`)
  10038. });
  10039. }
  10040. /**
  10041. * Completing a task
  10042. *
  10043. * Завершение задачи
  10044. */
  10045. function endAutoBattle(reason, info) {
  10046. isCancalBattle = true;
  10047. console.log(reason, info);
  10048. resolve();
  10049. }
  10050. }
  10051.  
  10052. class FixBattle {
  10053. constructor(battle, isTimeout = true) {
  10054. this.battle = structuredClone(battle);
  10055. this.isTimeout = isTimeout;
  10056. }
  10057. timeout(callback, timeout) {
  10058. if (this.isTimeout) {
  10059. this.worker.postMessage(timeout);
  10060. this.worker.onmessage = callback;
  10061. } else {
  10062. callback();
  10063. }
  10064. }
  10065. randTimer() {
  10066. const min = 1.3;
  10067. const max = 10.3;
  10068. return Math.random() * (max - min + 1) + min;
  10069. }
  10070. setAvgTime(startTime) {
  10071. this.fixTime += Date.now() - startTime;
  10072. this.avgTime = this.fixTime / this.count;
  10073. }
  10074. init() {
  10075. this.fixTime = 0;
  10076. this.lastTimer = 0;
  10077. this.index = 0;
  10078. this.lastBossDamage = 0;
  10079. this.bestResult = {
  10080. count: 0,
  10081. timer: 0,
  10082. value: 0,
  10083. result: null,
  10084. progress: null,
  10085. };
  10086. this.lastBattleResult = {
  10087. win: false,
  10088. };
  10089. this.worker = new Worker(
  10090. URL.createObjectURL(
  10091. new Blob([
  10092. `self.onmessage = function(e) {
  10093. const timeout = e.data;
  10094. setTimeout(() => {
  10095. self.postMessage(1);
  10096. }, timeout);
  10097. };`,
  10098. ])
  10099. )
  10100. );
  10101. }
  10102. async start(endTime = Date.now() + 6e4, maxCount = 100) {
  10103. this.endTime = endTime;
  10104. this.maxCount = maxCount;
  10105. this.init();
  10106. return await new Promise((resolve) => {
  10107. this.resolve = resolve;
  10108. this.count = 0;
  10109. this.loop();
  10110. });
  10111. }
  10112. endFix() {
  10113. this.bestResult.maxCount = this.count;
  10114. this.worker.terminate();
  10115. this.resolve(this.bestResult);
  10116. }
  10117. async loop() {
  10118. const start = Date.now();
  10119. if (this.isEndLoop()) {
  10120. this.endFix();
  10121. return;
  10122. }
  10123. this.count++;
  10124. try {
  10125. this.lastResult = await Calc(this.battle);
  10126. } catch (e) {
  10127. this.updateProgressTimer(this.index++);
  10128. this.timeout(this.loop.bind(this), 0);
  10129. return;
  10130. }
  10131. const { progress, result } = this.lastResult;
  10132. this.lastBattleResult = result;
  10133. this.lastBattleProgress = progress;
  10134. this.setAvgTime(start);
  10135. this.checkResult();
  10136. this.showResult();
  10137. this.updateProgressTimer();
  10138. this.timeout(this.loop.bind(this), 0);
  10139. }
  10140. isEndLoop() {
  10141. return this.count >= this.maxCount || this.endTime < Date.now();
  10142. }
  10143. updateProgressTimer(index = 0) {
  10144. this.lastTimer = this.randTimer();
  10145. this.battle.progress = [{ attackers: { input: ['auto', 0, 0, 'auto', index, this.lastTimer] } }];
  10146. }
  10147. showResult() {
  10148. console.log(
  10149. this.count,
  10150. this.avgTime.toFixed(2),
  10151. (this.endTime - Date.now()) / 1000,
  10152. this.lastTimer.toFixed(2),
  10153. this.lastBossDamage.toLocaleString(),
  10154. this.bestResult.value.toLocaleString()
  10155. );
  10156. }
  10157. checkResult() {
  10158. const { damageTaken, damageTakenNextLevel } = this.lastBattleProgress[0].defenders.heroes[1].extra;
  10159. this.lastBossDamage = damageTaken + damageTakenNextLevel;
  10160. if (this.lastBossDamage > this.bestResult.value) {
  10161. this.bestResult = {
  10162. count: this.count,
  10163. timer: this.lastTimer,
  10164. value: this.lastBossDamage,
  10165. result: structuredClone(this.lastBattleResult),
  10166. progress: structuredClone(this.lastBattleProgress),
  10167. };
  10168. }
  10169. }
  10170. }
  10171. class WinFixBattle extends FixBattle {
  10172. checkResult() {
  10173. if (this.lastBattleResult.win) {
  10174. this.bestResult = {
  10175. count: this.count,
  10176. timer: this.lastTimer,
  10177. value: this.lastBattleResult.stars,
  10178. result: structuredClone(this.lastBattleResult),
  10179. progress: structuredClone(this.lastBattleProgress),
  10180. battleTimer: this.lastResult.battleTimer,
  10181. };
  10182. }
  10183. }
  10184. isEndLoop() {
  10185. return super.isEndLoop() || this.lastBattleResult.win;
  10186. }
  10187. showResult() {
  10188. console.log(this.count, this.avgTime.toFixed(2), (this.endTime - Date.now()) / 1000, this.lastResult.battleTime, this.lastTimer);
  10189. const endTime = ((this.endTime - Date.now()) / 1000).toFixed(2);
  10190. const avgTime = this.avgTime.toFixed(2);
  10191. const msg = `${this.count}/${this.maxCount}<br/>${endTime}s<br/>${avgTime}ms`;
  10192. setProgress(msg, false, this.stopFix.bind(this));
  10193. }
  10194. stopFix() {
  10195. this.endTime = 0;
  10196. }
  10197. }
  10198.  
  10199. function testDailyQuests() {
  10200. return new Promise((resolve, reject) => {
  10201. const quests = new dailyQuests(resolve, reject);
  10202. quests.init(questsInfo);
  10203. quests.start();
  10204. });
  10205. }
  10206.  
  10207. /**
  10208. * Automatic completion of daily quests
  10209. *
  10210. * Автоматическое выполнение ежедневных квестов
  10211. */
  10212. class dailyQuests {
  10213. /**
  10214. * Send(' {"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}').then(e => console.log(e))
  10215. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10216. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10217. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  10218. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10219. * Send(' {"calls":[{"name":"bossGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  10220. */
  10221. callsList = [
  10222. "userGetInfo",
  10223. "heroGetAll",
  10224. "titanGetAll",
  10225. "inventoryGet",
  10226. "questGetAll",
  10227. "bossGetAll",
  10228. ]
  10229.  
  10230. dataQuests = {
  10231. 10001: {
  10232. description: 'Улучши умения героев 3 раза', // ++++++++++++++++
  10233. doItCall: () => {
  10234. const upgradeSkills = this.getUpgradeSkills();
  10235. return upgradeSkills.map(({ heroId, skill }, index) => ({ name: "heroUpgradeSkill", args: { heroId, skill }, "ident": `heroUpgradeSkill_${index}` }));
  10236. },
  10237. isWeCanDo: () => {
  10238. const upgradeSkills = this.getUpgradeSkills();
  10239. let sumGold = 0;
  10240. for (const skill of upgradeSkills) {
  10241. sumGold += this.skillCost(skill.value);
  10242. if (!skill.heroId) {
  10243. return false;
  10244. }
  10245. }
  10246. return this.questInfo['userGetInfo'].gold > sumGold;
  10247. },
  10248. },
  10249. 10002: {
  10250. description: 'Пройди 10 миссий', // --------------
  10251. isWeCanDo: () => false,
  10252. },
  10253. 10003: {
  10254. description: 'Пройди 3 героические миссии', // --------------
  10255. isWeCanDo: () => false,
  10256. },
  10257. 10004: {
  10258. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  10259. isWeCanDo: () => false,
  10260. },
  10261. 10006: {
  10262. description: 'Используй обмен изумрудов 1 раз', // ++++++++++++++++
  10263. doItCall: () => [{
  10264. name: "refillableAlchemyUse",
  10265. args: { multi: false },
  10266. ident: "refillableAlchemyUse"
  10267. }],
  10268. isWeCanDo: () => {
  10269. const starMoney = this.questInfo['userGetInfo'].starMoney;
  10270. return starMoney >= 20;
  10271. },
  10272. },
  10273. 10007: {
  10274. description: 'Соверши 1 призыв в Атриуме Душ', // ++++++++++++++++
  10275. doItCall: () => [{ name: "gacha_open", args: { ident: "heroGacha", free: true, pack: false }, ident: "gacha_open" }],
  10276. isWeCanDo: () => {
  10277. const soulCrystal = this.questInfo['inventoryGet'].coin[38];
  10278. return soulCrystal > 0;
  10279. },
  10280. },
  10281. /*10016: {
  10282. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  10283. doItCall: () => [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  10284. isWeCanDo: () => true,
  10285. },*/
  10286. 10018: {
  10287. description: 'Используй зелье опыта', // ++++++++++++++++
  10288. doItCall: () => {
  10289. const expHero = this.getExpHero();
  10290. return [{
  10291. name: "consumableUseHeroXp",
  10292. args: {
  10293. heroId: expHero.heroId,
  10294. libId: expHero.libId,
  10295. amount: 1
  10296. },
  10297. ident: "consumableUseHeroXp"
  10298. }];
  10299. },
  10300. isWeCanDo: () => {
  10301. const expHero = this.getExpHero();
  10302. return expHero.heroId && expHero.libId;
  10303. },
  10304. },
  10305. 10019: {
  10306. description: 'Открой 1 сундук в Башне',
  10307. doItFunc: testTower,
  10308. isWeCanDo: () => false,
  10309. },
  10310. 10020: {
  10311. description: 'Открой 3 сундука в Запределье', // Готово
  10312. doItCall: () => {
  10313. return this.getOutlandChest();
  10314. },
  10315. isWeCanDo: () => {
  10316. const outlandChest = this.getOutlandChest();
  10317. return outlandChest.length > 0;
  10318. },
  10319. },
  10320. 10021: {
  10321. description: 'Собери 75 Титанита в Подземелье Гильдии',
  10322. isWeCanDo: () => false,
  10323. },
  10324. 10022: {
  10325. description: 'Собери 150 Титанита в Подземелье Гильдии',
  10326. doItFunc: testDungeon,
  10327. isWeCanDo: () => false,
  10328. },
  10329. 10023: {
  10330. description: 'Прокачай Дар Стихий на 1 уровень', // Готово
  10331. doItCall: () => {
  10332. const heroId = this.getHeroIdTitanGift();
  10333. return [
  10334. { name: "heroTitanGiftLevelUp", args: { heroId }, ident: "heroTitanGiftLevelUp" },
  10335. { name: "heroTitanGiftDrop", args: { heroId }, ident: "heroTitanGiftDrop" }
  10336. ]
  10337. },
  10338. isWeCanDo: () => {
  10339. const heroId = this.getHeroIdTitanGift();
  10340. return heroId;
  10341. },
  10342. },
  10343. 10024: {
  10344. description: 'Повысь уровень любого артефакта один раз', // Готово
  10345. doItCall: () => {
  10346. const upArtifact = this.getUpgradeArtifact();
  10347. return [
  10348. {
  10349. name: "heroArtifactLevelUp",
  10350. args: {
  10351. heroId: upArtifact.heroId,
  10352. slotId: upArtifact.slotId
  10353. },
  10354. ident: `heroArtifactLevelUp`
  10355. }
  10356. ];
  10357. },
  10358. isWeCanDo: () => {
  10359. const upgradeArtifact = this.getUpgradeArtifact();
  10360. return upgradeArtifact.heroId;
  10361. },
  10362. },
  10363. 10025: {
  10364. description: 'Начни 1 Экспедицию',
  10365. doItFunc: checkExpedition,
  10366. isWeCanDo: () => false,
  10367. },
  10368. 10026: {
  10369. description: 'Начни 4 Экспедиции', // --------------
  10370. doItFunc: checkExpedition,
  10371. isWeCanDo: () => false,
  10372. },
  10373. 10027: {
  10374. description: 'Победи в 1 бою Турнира Стихий',
  10375. doItFunc: testTitanArena,
  10376. isWeCanDo: () => false,
  10377. },
  10378. 10028: {
  10379. description: 'Повысь уровень любого артефакта титанов', // Готово
  10380. doItCall: () => {
  10381. const upTitanArtifact = this.getUpgradeTitanArtifact();
  10382. return [
  10383. {
  10384. name: "titanArtifactLevelUp",
  10385. args: {
  10386. titanId: upTitanArtifact.titanId,
  10387. slotId: upTitanArtifact.slotId
  10388. },
  10389. ident: `titanArtifactLevelUp`
  10390. }
  10391. ];
  10392. },
  10393. isWeCanDo: () => {
  10394. const upgradeTitanArtifact = this.getUpgradeTitanArtifact();
  10395. return upgradeTitanArtifact.titanId;
  10396. },
  10397. },
  10398. 10029: {
  10399. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  10400. doItCall: () => [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  10401. isWeCanDo: () => {
  10402. return this.questInfo['inventoryGet']?.consumable[55] > 0
  10403. },
  10404. },
  10405. 10030: {
  10406. description: 'Улучши облик любого героя 1 раз', // Готово
  10407. doItCall: () => {
  10408. const upSkin = this.getUpgradeSkin();
  10409. return [
  10410. {
  10411. name: "heroSkinUpgrade",
  10412. args: {
  10413. heroId: upSkin.heroId,
  10414. skinId: upSkin.skinId
  10415. },
  10416. ident: `heroSkinUpgrade`
  10417. }
  10418. ];
  10419. },
  10420. isWeCanDo: () => {
  10421. const upgradeSkin = this.getUpgradeSkin();
  10422. return upgradeSkin.heroId;
  10423. },
  10424. },
  10425. 10031: {
  10426. description: 'Победи в 6 боях Турнира Стихий', // --------------
  10427. doItFunc: testTitanArena,
  10428. isWeCanDo: () => false,
  10429. },
  10430. 10043: {
  10431. description: 'Начни или присоеденись к Приключению', // --------------
  10432. isWeCanDo: () => false,
  10433. },
  10434. 10044: {
  10435. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  10436. doItCall: () => [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  10437. isWeCanDo: () => {
  10438. return this.questInfo['inventoryGet']?.consumable[90] > 0
  10439. },
  10440. },
  10441. 10046: {
  10442. /**
  10443. * TODO: Watch Adventure
  10444. * TODO: Смотреть приключение
  10445. */
  10446. description: 'Открой 3 сундука в Приключениях',
  10447. isWeCanDo: () => false,
  10448. },
  10449. 10047: {
  10450. description: 'Набери 150 очков активности в Гильдии', // Готово
  10451. doItCall: () => {
  10452. const enchantRune = this.getEnchantRune();
  10453. return [
  10454. {
  10455. name: "heroEnchantRune",
  10456. args: {
  10457. heroId: enchantRune.heroId,
  10458. tier: enchantRune.tier,
  10459. items: {
  10460. consumable: { [enchantRune.itemId]: 1 }
  10461. }
  10462. },
  10463. ident: `heroEnchantRune`
  10464. }
  10465. ];
  10466. },
  10467. isWeCanDo: () => {
  10468. const userInfo = this.questInfo['userGetInfo'];
  10469. const enchantRune = this.getEnchantRune();
  10470. return enchantRune.heroId && userInfo.gold > 1e3;
  10471. },
  10472. },
  10473. };
  10474.  
  10475. constructor(resolve, reject, questInfo) {
  10476. this.resolve = resolve;
  10477. this.reject = reject;
  10478. }
  10479.  
  10480. init(questInfo) {
  10481. this.questInfo = questInfo;
  10482. this.isAuto = false;
  10483. }
  10484.  
  10485. async autoInit(isAuto) {
  10486. this.isAuto = isAuto || false;
  10487. const quests = {};
  10488. const calls = this.callsList.map(name => ({
  10489. name, args: {}, ident: name
  10490. }))
  10491. const result = await Send(JSON.stringify({ calls })).then(e => e.results);
  10492. for (const call of result) {
  10493. quests[call.ident] = call.result.response;
  10494. }
  10495. this.questInfo = quests;
  10496. }
  10497.  
  10498. async start() {
  10499. const weCanDo = [];
  10500. const selectedActions = getSaveVal('selectedActions', {});
  10501. for (let quest of this.questInfo['questGetAll']) {
  10502. if (quest.id in this.dataQuests && quest.state == 1) {
  10503. if (!selectedActions[quest.id]) {
  10504. selectedActions[quest.id] = {
  10505. checked: false
  10506. }
  10507. }
  10508.  
  10509. const isWeCanDo = this.dataQuests[quest.id].isWeCanDo;
  10510. if (!isWeCanDo.call(this)) {
  10511. continue;
  10512. }
  10513.  
  10514. weCanDo.push({
  10515. name: quest.id,
  10516. label: I18N(`QUEST_${quest.id}`),
  10517. checked: selectedActions[quest.id].checked
  10518. });
  10519. }
  10520. }
  10521.  
  10522. if (!weCanDo.length) {
  10523. this.end(I18N('NOTHING_TO_DO'));
  10524. return;
  10525. }
  10526.  
  10527. console.log(weCanDo);
  10528. let taskList = [];
  10529. if (this.isAuto) {
  10530. taskList = weCanDo;
  10531. } else {
  10532. const answer = await popup.confirm(`${I18N('YOU_CAN_COMPLETE') }:`, [
  10533. { msg: I18N('BTN_DO_IT'), result: true },
  10534. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  10535. ], weCanDo);
  10536. if (!answer) {
  10537. this.end('');
  10538. return;
  10539. }
  10540. taskList = popup.getCheckBoxes();
  10541. taskList.forEach(e => {
  10542. selectedActions[e.name].checked = e.checked;
  10543. });
  10544. setSaveVal('selectedActions', selectedActions);
  10545. }
  10546.  
  10547. const calls = [];
  10548. let countChecked = 0;
  10549. for (const task of taskList) {
  10550. if (task.checked) {
  10551. countChecked++;
  10552. const quest = this.dataQuests[task.name]
  10553. console.log(quest.description);
  10554.  
  10555. if (quest.doItCall) {
  10556. const doItCall = quest.doItCall.call(this);
  10557. calls.push(...doItCall);
  10558. }
  10559. }
  10560. }
  10561.  
  10562. if (!countChecked) {
  10563. this.end(I18N('NOT_QUEST_COMPLETED'));
  10564. return;
  10565. }
  10566.  
  10567. const result = await Send(JSON.stringify({ calls }));
  10568. if (result.error) {
  10569. console.error(result.error, result.error.call)
  10570. }
  10571. this.end(`${I18N('COMPLETED_QUESTS')}: ${countChecked}`);
  10572. }
  10573.  
  10574. errorHandling(error) {
  10575. //console.error(error);
  10576. let errorInfo = error.toString() + '\n';
  10577. try {
  10578. const errorStack = error.stack.split('\n');
  10579. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  10580. errorInfo += errorStack.slice(0, endStack).join('\n');
  10581. } catch (e) {
  10582. errorInfo += error.stack;
  10583. }
  10584. copyText(errorInfo);
  10585. }
  10586.  
  10587. skillCost(lvl) {
  10588. return 573 * lvl ** 0.9 + lvl ** 2.379;
  10589. }
  10590.  
  10591. getUpgradeSkills() {
  10592. const heroes = Object.values(this.questInfo['heroGetAll']);
  10593. const upgradeSkills = [
  10594. { heroId: 0, slotId: 0, value: 130 },
  10595. { heroId: 0, slotId: 0, value: 130 },
  10596. { heroId: 0, slotId: 0, value: 130 },
  10597. ];
  10598. const skillLib = lib.getData('skill');
  10599. /**
  10600. * color - 1 (белый) открывает 1 навык
  10601. * color - 2 (зеленый) открывает 2 навык
  10602. * color - 4 (синий) открывает 3 навык
  10603. * color - 7 (фиолетовый) открывает 4 навык
  10604. */
  10605. const colors = [1, 2, 4, 7];
  10606. for (const hero of heroes) {
  10607. const level = hero.level;
  10608. const color = hero.color;
  10609. for (let skillId in hero.skills) {
  10610. const tier = skillLib[skillId].tier;
  10611. const sVal = hero.skills[skillId];
  10612. if (color < colors[tier] || tier < 1 || tier > 4) {
  10613. continue;
  10614. }
  10615. for (let upSkill of upgradeSkills) {
  10616. if (sVal < upSkill.value && sVal < level) {
  10617. upSkill.value = sVal;
  10618. upSkill.heroId = hero.id;
  10619. upSkill.skill = tier;
  10620. break;
  10621. }
  10622. }
  10623. }
  10624. }
  10625. return upgradeSkills;
  10626. }
  10627.  
  10628. getUpgradeArtifact() {
  10629. const heroes = Object.values(this.questInfo['heroGetAll']);
  10630. const inventory = this.questInfo['inventoryGet'];
  10631. const upArt = { heroId: 0, slotId: 0, level: 100 };
  10632.  
  10633. const heroLib = lib.getData('hero');
  10634. const artifactLib = lib.getData('artifact');
  10635.  
  10636. for (const hero of heroes) {
  10637. const heroInfo = heroLib[hero.id];
  10638. const level = hero.level
  10639. if (level < 20) {
  10640. continue;
  10641. }
  10642.  
  10643. for (let slotId in hero.artifacts) {
  10644. const art = hero.artifacts[slotId];
  10645. /* Текущая звезданость арта */
  10646. const star = art.star;
  10647. if (!star) {
  10648. continue;
  10649. }
  10650. /* Текущий уровень арта */
  10651. const level = art.level;
  10652. if (level >= 100) {
  10653. continue;
  10654. }
  10655. /* Идентификатор арта в библиотеке */
  10656. const artifactId = heroInfo.artifacts[slotId];
  10657. const artInfo = artifactLib.id[artifactId];
  10658. const costNextLevel = artifactLib.type[artInfo.type].levels[level + 1].cost;
  10659.  
  10660. const costCurrency = Object.keys(costNextLevel).pop();
  10661. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  10662. const costId = costValues[0];
  10663. const costValue = +costValues[1];
  10664.  
  10665. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10666. if (level < upArt.level && inventory[costCurrency][costId] >= costValue) {
  10667. upArt.level = level;
  10668. upArt.heroId = hero.id;
  10669. upArt.slotId = slotId;
  10670. upArt.costCurrency = costCurrency;
  10671. upArt.costId = costId;
  10672. upArt.costValue = costValue;
  10673. }
  10674. }
  10675. }
  10676. return upArt;
  10677. }
  10678.  
  10679. getUpgradeSkin() {
  10680. const heroes = Object.values(this.questInfo['heroGetAll']);
  10681. const inventory = this.questInfo['inventoryGet'];
  10682. const upSkin = { heroId: 0, skinId: 0, level: 60, cost: 1500 };
  10683.  
  10684. const skinLib = lib.getData('skin');
  10685.  
  10686. for (const hero of heroes) {
  10687. const level = hero.level
  10688. if (level < 20) {
  10689. continue;
  10690. }
  10691.  
  10692. for (let skinId in hero.skins) {
  10693. /* Текущий уровень скина */
  10694. const level = hero.skins[skinId];
  10695. if (level >= 60) {
  10696. continue;
  10697. }
  10698. /* Идентификатор скина в библиотеке */
  10699. const skinInfo = skinLib[skinId];
  10700. if (!skinInfo.statData.levels?.[level + 1]) {
  10701. continue;
  10702. }
  10703. const costNextLevel = skinInfo.statData.levels[level + 1].cost;
  10704.  
  10705. const costCurrency = Object.keys(costNextLevel).pop();
  10706. const costCurrencyId = Object.keys(costNextLevel[costCurrency]).pop();
  10707. const costValue = +costNextLevel[costCurrency][costCurrencyId];
  10708.  
  10709. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10710. if (level < upSkin.level &&
  10711. costValue < upSkin.cost &&
  10712. inventory[costCurrency][costCurrencyId] >= costValue) {
  10713. upSkin.cost = costValue;
  10714. upSkin.level = level;
  10715. upSkin.heroId = hero.id;
  10716. upSkin.skinId = skinId;
  10717. upSkin.costCurrency = costCurrency;
  10718. upSkin.costCurrencyId = costCurrencyId;
  10719. }
  10720. }
  10721. }
  10722. return upSkin;
  10723. }
  10724.  
  10725. getUpgradeTitanArtifact() {
  10726. const titans = Object.values(this.questInfo['titanGetAll']);
  10727. const inventory = this.questInfo['inventoryGet'];
  10728. const userInfo = this.questInfo['userGetInfo'];
  10729. const upArt = { titanId: 0, slotId: 0, level: 120 };
  10730.  
  10731. const titanLib = lib.getData('titan');
  10732. const artTitanLib = lib.getData('titanArtifact');
  10733.  
  10734. for (const titan of titans) {
  10735. const titanInfo = titanLib[titan.id];
  10736. // const level = titan.level
  10737. // if (level < 20) {
  10738. // continue;
  10739. // }
  10740.  
  10741. for (let slotId in titan.artifacts) {
  10742. const art = titan.artifacts[slotId];
  10743. /* Текущая звезданость арта */
  10744. const star = art.star;
  10745. if (!star) {
  10746. continue;
  10747. }
  10748. /* Текущий уровень арта */
  10749. const level = art.level;
  10750. if (level >= 120) {
  10751. continue;
  10752. }
  10753. /* Идентификатор арта в библиотеке */
  10754. const artifactId = titanInfo.artifacts[slotId];
  10755. const artInfo = artTitanLib.id[artifactId];
  10756. const costNextLevel = artTitanLib.type[artInfo.type].levels[level + 1].cost;
  10757.  
  10758. const costCurrency = Object.keys(costNextLevel).pop();
  10759. let costValue = 0;
  10760. let currentValue = 0;
  10761. if (costCurrency == 'gold') {
  10762. costValue = costNextLevel[costCurrency];
  10763. currentValue = userInfo.gold;
  10764. } else {
  10765. const costValues = Object.entries(costNextLevel[costCurrency]).pop();
  10766. const costId = costValues[0];
  10767. costValue = +costValues[1];
  10768. currentValue = inventory[costCurrency][costId];
  10769. }
  10770.  
  10771. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10772. if (level < upArt.level && currentValue >= costValue) {
  10773. upArt.level = level;
  10774. upArt.titanId = titan.id;
  10775. upArt.slotId = slotId;
  10776. break;
  10777. }
  10778. }
  10779. }
  10780. return upArt;
  10781. }
  10782.  
  10783. getEnchantRune() {
  10784. const heroes = Object.values(this.questInfo['heroGetAll']);
  10785. const inventory = this.questInfo['inventoryGet'];
  10786. const enchRune = { heroId: 0, tier: 0, exp: 43750, itemId: 0 };
  10787. for (let i = 1; i <= 4; i++) {
  10788. if (inventory.consumable[i] > 0) {
  10789. enchRune.itemId = i;
  10790. break;
  10791. }
  10792. return enchRune;
  10793. }
  10794.  
  10795. const runeLib = lib.getData('rune');
  10796. const runeLvls = Object.values(runeLib.level);
  10797. /**
  10798. * color - 4 (синий) открывает 1 и 2 символ
  10799. * color - 7 (фиолетовый) открывает 3 символ
  10800. * color - 8 (фиолетовый +1) открывает 4 символ
  10801. * color - 9 (фиолетовый +2) открывает 5 символ
  10802. */
  10803. // TODO: кажется надо учесть уровень команды
  10804. const colors = [4, 4, 7, 8, 9];
  10805. for (const hero of heroes) {
  10806. const color = hero.color;
  10807.  
  10808.  
  10809. for (let runeTier in hero.runes) {
  10810. /* Проверка на доступность руны */
  10811. if (color < colors[runeTier]) {
  10812. continue;
  10813. }
  10814. /* Текущий опыт руны */
  10815. const exp = hero.runes[runeTier];
  10816. if (exp >= 43750) {
  10817. continue;
  10818. }
  10819.  
  10820. let level = 0;
  10821. if (exp) {
  10822. for (let lvl of runeLvls) {
  10823. if (exp >= lvl.enchantValue) {
  10824. level = lvl.level;
  10825. } else {
  10826. break;
  10827. }
  10828. }
  10829. }
  10830. /** Уровень героя необходимый для уровня руны */
  10831. const heroLevel = runeLib.level[level].heroLevel;
  10832. if (hero.level < heroLevel) {
  10833. continue;
  10834. }
  10835.  
  10836. /** TODO: Возможно стоит искать самый высокий уровень который можно качнуть? */
  10837. if (exp < enchRune.exp) {
  10838. enchRune.exp = exp;
  10839. enchRune.heroId = hero.id;
  10840. enchRune.tier = runeTier;
  10841. break;
  10842. }
  10843. }
  10844. }
  10845. return enchRune;
  10846. }
  10847.  
  10848. getOutlandChest() {
  10849. const bosses = this.questInfo['bossGetAll'];
  10850.  
  10851. const calls = [];
  10852.  
  10853. for (let boss of bosses) {
  10854. if (boss.mayRaid) {
  10855. calls.push({
  10856. name: "bossRaid",
  10857. args: {
  10858. bossId: boss.id
  10859. },
  10860. ident: "bossRaid_" + boss.id
  10861. });
  10862. calls.push({
  10863. name: "bossOpenChest",
  10864. args: {
  10865. bossId: boss.id,
  10866. amount: 1,
  10867. starmoney: 0
  10868. },
  10869. ident: "bossOpenChest_" + boss.id
  10870. });
  10871. } else if (boss.chestId == 1) {
  10872. calls.push({
  10873. name: "bossOpenChest",
  10874. args: {
  10875. bossId: boss.id,
  10876. amount: 1,
  10877. starmoney: 0
  10878. },
  10879. ident: "bossOpenChest_" + boss.id
  10880. });
  10881. }
  10882. }
  10883.  
  10884. return calls;
  10885. }
  10886.  
  10887. getExpHero() {
  10888. const heroes = Object.values(this.questInfo['heroGetAll']);
  10889. const inventory = this.questInfo['inventoryGet'];
  10890. const expHero = { heroId: 0, exp: 3625195, libId: 0 };
  10891. /** зелья опыта (consumable 9, 10, 11, 12) */
  10892. for (let i = 9; i <= 12; i++) {
  10893. if (inventory.consumable[i]) {
  10894. expHero.libId = i;
  10895. break;
  10896. }
  10897. }
  10898.  
  10899. for (const hero of heroes) {
  10900. const exp = hero.xp;
  10901. if (exp < expHero.exp) {
  10902. expHero.heroId = hero.id;
  10903. }
  10904. }
  10905. return expHero;
  10906. }
  10907.  
  10908. getHeroIdTitanGift() {
  10909. const heroes = Object.values(this.questInfo['heroGetAll']);
  10910. const inventory = this.questInfo['inventoryGet'];
  10911. const user = this.questInfo['userGetInfo'];
  10912. const titanGiftLib = lib.getData('titanGift');
  10913. /** Искры */
  10914. const titanGift = inventory.consumable[24];
  10915. let heroId = 0;
  10916. let minLevel = 30;
  10917.  
  10918. if (titanGift < 250 || user.gold < 7000) {
  10919. return 0;
  10920. }
  10921.  
  10922. for (const hero of heroes) {
  10923. if (hero.titanGiftLevel >= 30) {
  10924. continue;
  10925. }
  10926.  
  10927. if (!hero.titanGiftLevel) {
  10928. return hero.id;
  10929. }
  10930.  
  10931. const cost = titanGiftLib[hero.titanGiftLevel].cost;
  10932. if (minLevel > hero.titanGiftLevel &&
  10933. titanGift >= cost.consumable[24] &&
  10934. user.gold >= cost.gold
  10935. ) {
  10936. minLevel = hero.titanGiftLevel;
  10937. heroId = hero.id;
  10938. }
  10939. }
  10940.  
  10941. return heroId;
  10942. }
  10943.  
  10944. end(status) {
  10945. setProgress(status, true);
  10946. this.resolve();
  10947. }
  10948. }
  10949.  
  10950. this.questRun = dailyQuests;
  10951.  
  10952. function testDoYourBest() {
  10953. return new Promise((resolve, reject) => {
  10954. const doIt = new doYourBest(resolve, reject);
  10955. doIt.start();
  10956. });
  10957. }
  10958.  
  10959. /**
  10960. * Do everything button
  10961. *
  10962. * Кнопка сделать все
  10963. */
  10964. class doYourBest {
  10965.  
  10966. funcList = [
  10967. //собрать запределье
  10968. {
  10969. name: 'getOutland',
  10970. label: I18N('ASSEMBLE_OUTLAND'),
  10971. checked: false
  10972. },
  10973. //пройти башню
  10974. {
  10975. name: 'testTower',
  10976. label: I18N('PASS_THE_TOWER'),
  10977. checked: false
  10978. },
  10979. //экспедиции
  10980. {
  10981. name: 'checkExpedition',
  10982. label: I18N('CHECK_EXPEDITIONS'),
  10983. checked: false
  10984. },
  10985. //турнир стихий
  10986. {
  10987. name: 'testTitanArena',
  10988. label: I18N('COMPLETE_TOE'),
  10989. checked: false
  10990. },
  10991. //собрать почту
  10992. {
  10993. name: 'mailGetAll',
  10994. label: I18N('COLLECT_MAIL'),
  10995. checked: false
  10996. },
  10997. //Собрать всякую херню
  10998. {
  10999. name: 'collectAllStuff',
  11000. label: I18N('COLLECT_MISC'),
  11001. title: I18N('COLLECT_MISC_TITLE'),
  11002. checked: false
  11003. },
  11004. //ежедневная награда
  11005. {
  11006. name: 'getDailyBonus',
  11007. label: I18N('DAILY_BONUS'),
  11008. checked: false
  11009. },
  11010. //ежедневные квесты удалить наверно есть в настройках
  11011. {
  11012. name: 'dailyQuests',
  11013. label: I18N('DO_DAILY_QUESTS'),
  11014. checked: false
  11015. },
  11016. //Провидец
  11017. {
  11018. name: 'rollAscension',
  11019. label: I18N('SEER_TITLE'),
  11020. checked: false
  11021. },
  11022. //собрать награды за квесты
  11023. {
  11024. name: 'questAllFarm',
  11025. label: I18N('COLLECT_QUEST_REWARDS'),
  11026. checked: false
  11027. },
  11028. // тест отправь подарки согильдийцам
  11029. {
  11030. name: 'testclanSendDailyGifts',
  11031. label: I18N('QUEST_10016'),
  11032. checked: false
  11033. },
  11034. //собрать новогодние подарки
  11035. /*{
  11036. name: 'getGiftNewYear',
  11037. label: I18N('NY_GIFTS'),
  11038. checked: false
  11039. },*/
  11040. // тест сферу титанов
  11041. /*{
  11042. name: 'testtitanArtifactChestOpen',
  11043. label: I18N('QUEST_10029'),
  11044. checked: false
  11045. },
  11046. // тест призыв петов
  11047. {
  11048. name: 'testpet_chestOpen',
  11049. label: I18N('QUEST_10044'),
  11050. checked: false
  11051. },*/
  11052. //пройти подземелье обычное
  11053. {
  11054. name: 'testDungeon',
  11055. label: I18N('COMPLETE_DUNGEON'),
  11056. checked: false
  11057. },
  11058. //пройти подземелье для фуловых титанов
  11059. {
  11060. name: 'DungeonFull',
  11061. label: I18N('COMPLETE_DUNGEON_FULL'),
  11062. checked: false
  11063. },
  11064. //синхронизация
  11065. {
  11066. name: 'synchronization',
  11067. label: I18N('MAKE_A_SYNC'),
  11068. checked: false
  11069. },
  11070. //перезагрузка
  11071. {
  11072. name: 'reloadGame',
  11073. label: I18N('RELOAD_GAME'),
  11074. checked: false
  11075. },
  11076. ];
  11077.  
  11078. functions = {
  11079. getOutland,//собрать запределье
  11080. testTower,//прохождение башни
  11081. checkExpedition,//автоэкспедиции
  11082. testTitanArena,//Автопрохождение Турнира Стихий
  11083. mailGetAll,//Собрать всю почту, кроме писем с энергией и зарядами портала
  11084. //Собрать пасхалки, камни облика, ключи, монеты арены и Хрусталь души
  11085. collectAllStuff: async () => {
  11086. await offerFarmAllReward();
  11087. 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"}]}');
  11088. },
  11089. //Выполнять ежедневные квесты
  11090. dailyQuests: async function () {
  11091. const quests = new dailyQuests(() => { }, () => { });
  11092. await quests.autoInit(true);
  11093. await quests.start();
  11094. },
  11095. rollAscension,//провидец
  11096. getDailyBonus,//ежедневная награда
  11097. questAllFarm,//Собрать все награды за задания
  11098. testclanSendDailyGifts, //отправить подарки
  11099. getGiftNewYear,//собрать новогодние подарки
  11100. testtitanArtifactChestOpen, //открой сферу титанов
  11101. testpet_chestOpen, //Воспользуйся призывом питомцев 1 раз
  11102. testDungeon,//подземка обычная
  11103. DungeonFull,//подземка для фуловых титанов
  11104. synchronization: async () => {
  11105. cheats.refreshGame();
  11106. },
  11107. reloadGame: async () => {
  11108. location.reload();
  11109. },
  11110. }
  11111.  
  11112. constructor(resolve, reject, questInfo) {
  11113. this.resolve = resolve;
  11114. this.reject = reject;
  11115. this.questInfo = questInfo
  11116. }
  11117.  
  11118. async start() {
  11119. const selectedDoIt = getSaveVal('selectedDoIt', {});
  11120.  
  11121. this.funcList.forEach(task => {
  11122. if (!selectedDoIt[task.name]) {
  11123. selectedDoIt[task.name] = {
  11124. checked: task.checked
  11125. }
  11126. } else {
  11127. task.checked = selectedDoIt[task.name].checked
  11128. }
  11129. });
  11130.  
  11131. const answer = await popup.confirm(I18N('RUN_FUNCTION'), [
  11132. { msg: I18N('BTN_CANCEL'), result: false, isCancel: true },
  11133. { msg: I18N('BTN_GO'), result: true },
  11134. ], this.funcList);
  11135.  
  11136. if (!answer) {
  11137. this.end('');
  11138. return;
  11139. }
  11140.  
  11141. const taskList = popup.getCheckBoxes();
  11142. taskList.forEach(task => {
  11143. selectedDoIt[task.name].checked = task.checked;
  11144. });
  11145. setSaveVal('selectedDoIt', selectedDoIt);
  11146. for (const task of popup.getCheckBoxes()) {
  11147. if (task.checked) {
  11148. try {
  11149. setProgress(`${task.label} <br>${I18N('PERFORMED')}!`);
  11150. await this.functions[task.name]();
  11151. setProgress(`${task.label} <br>${I18N('DONE')}!`);
  11152. } catch (error) {
  11153. if (await popup.confirm(`${I18N('ERRORS_OCCURRES')}:<br> ${task.label} <br>${I18N('COPY_ERROR')}?`, [
  11154. { msg: I18N('BTN_NO'), result: false },
  11155. { msg: I18N('BTN_YES'), result: true },
  11156. ])) {
  11157. this.errorHandling(error);
  11158. }
  11159. }
  11160. }
  11161. }
  11162. setTimeout((msg) => {
  11163. this.end(msg);
  11164. }, 2000, I18N('ALL_TASK_COMPLETED'));
  11165. return;
  11166. }
  11167.  
  11168. errorHandling(error) {
  11169. //console.error(error);
  11170. let errorInfo = error.toString() + '\n';
  11171. try {
  11172. const errorStack = error.stack.split('\n');
  11173. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  11174. errorInfo += errorStack.slice(0, endStack).join('\n');
  11175. } catch (e) {
  11176. errorInfo += error.stack;
  11177. }
  11178. copyText(errorInfo);
  11179. }
  11180.  
  11181. end(status) {
  11182. setProgress(status, true);
  11183. this.resolve();
  11184. }
  11185. }
  11186.  
  11187. /**
  11188. * Passing the adventure along the specified route
  11189. *
  11190. * Прохождение приключения по указанному маршруту
  11191. */
  11192. function testAdventure(type) {
  11193. return new Promise((resolve, reject) => {
  11194. const bossBattle = new executeAdventure(resolve, reject);
  11195. bossBattle.start(type);
  11196. });
  11197. }
  11198.  
  11199. //Буря
  11200. function testAdventure2(solo) {
  11201. return new Promise((resolve, reject) => {
  11202. const bossBattle = new executeAdventure2(resolve, reject);
  11203. bossBattle.start(solo);
  11204. });
  11205. }
  11206.  
  11207. /**
  11208. * Passing the adventure along the specified route
  11209. *
  11210. * Прохождение приключения по указанному маршруту
  11211. */
  11212. class executeAdventure {
  11213.  
  11214. type = 'default';
  11215.  
  11216. actions = {
  11217. default: {
  11218. getInfo: "adventure_getInfo",
  11219. startBattle: 'adventure_turnStartBattle',
  11220. endBattle: 'adventure_endBattle',
  11221. collectBuff: 'adventure_turnCollectBuff'
  11222. },
  11223. solo: {
  11224. getInfo: "adventureSolo_getInfo",
  11225. startBattle: 'adventureSolo_turnStartBattle',
  11226. endBattle: 'adventureSolo_endBattle',
  11227. collectBuff: 'adventureSolo_turnCollectBuff'
  11228. }
  11229. }
  11230.  
  11231. terminatеReason = I18N('UNKNOWN');
  11232. callAdventureInfo = {
  11233. name: "adventure_getInfo",
  11234. args: {},
  11235. ident: "adventure_getInfo"
  11236. }
  11237. callTeamGetAll = {
  11238. name: "teamGetAll",
  11239. args: {},
  11240. ident: "teamGetAll"
  11241. }
  11242. callTeamGetFavor = {
  11243. name: "teamGetFavor",
  11244. args: {},
  11245. ident: "teamGetFavor"
  11246. }
  11247. //тест прикла
  11248. defaultWays = {
  11249. //Галахад, 1-я
  11250. "adv_strongford_2pl_easy": {
  11251. first: '1,2,3,5,6',
  11252. second: '1,2,4,7,6',
  11253. third: '1,2,3,5,6'
  11254. },
  11255. //Джинджер, 2-я
  11256. "adv_valley_3pl_easy": {
  11257. first: '1,2,5,8,9,11',
  11258. second: '1,3,6,9,11',
  11259. third: '1,4,7,10,9,11'
  11260. },
  11261. //Орион, 3-я
  11262. "adv_ghirwil_3pl_easy": {
  11263. first: '1,5,6,9,11',
  11264. second: '1,4,12,13,11',
  11265. third: '1,2,3,7,10,11'
  11266. },
  11267. //Тесак, 4-я
  11268. "adv_angels_3pl_easy_fire": {
  11269. first: '1,2,4,7,18,8,12,19,22,23',
  11270. second: '1,3,6,11,17,10,16,21,22,23',
  11271. third: '1,5,24,25,9,14,15,20,22,23'
  11272. },
  11273. //Галахад, 5-я
  11274. "adv_strongford_3pl_normal_2": {
  11275. first: '1,2,7,8,12,16,23,26,25,21,24',
  11276. second: '1,4,6,10,11,15,22,15,19,18,24',
  11277. third: '1,5,9,10,14,17,20,27,25,21,24'
  11278. },
  11279. //Джинджер, 6-я
  11280. "adv_valley_3pl_normal": {
  11281. first: '1,2,4,7,10,13,16,19,24,22,25',
  11282. second: '1,3,6,9,12,15,18,21,26,23,25',
  11283. third: '1,5,7,8,11,14,17,20,22,25'
  11284. },
  11285. //Орион, 7-я
  11286. "adv_ghirwil_3pl_normal_2": {
  11287. first: '1,11,10,11,12,15,12,11,21,25,27',
  11288. second: '1,7,3,4,3,6,13,19,20,24,27',
  11289. third: '1,8,5,9,16,23,22,26,27'
  11290. },
  11291. //Тесак, 8-я
  11292. "adv_angels_3pl_normal": {
  11293. first: '1,3,4,8,7,9,10,13,17,16,20,22,23,31,32',
  11294. second: '1,3,5,7,8,11,14,18,20,22,24,27,30,26,32',
  11295. third: '1,3,2,6,7,9,11,15,19,20,22,21,28,29,25'
  11296. },
  11297. //Галахад, 9-я
  11298. "adv_strongford_3pl_hard_2": {
  11299. first: '1,2,6,10,15,7,16,17,23,22,27,32,35,37,40,45',
  11300. second: '1,3,8,12,11,18,19,28,34,33,38,41,43,46,45',
  11301. third: '1,2,5,9,14,20,26,21,30,36,39,42,44,45'
  11302. },
  11303. //Джинджер, 10-я
  11304. "adv_valley_3pl_hard": {
  11305. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  11306. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  11307. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  11308. },
  11309. //Орион, 11-я
  11310. "adv_ghirwil_3pl_hard": {
  11311. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  11312. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  11313. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  11314. },
  11315. //Тесак, 12-я
  11316. "adv_angels_3pl_hard": {
  11317. first: '1,2,8,11,7,4,7,16,23,32,33,25,34,29,35,36',
  11318. second: '1,3,9,13,10,6,10,22,31,30,21,30,15,28,20,27',
  11319. third: '1,5,12,14,24,17,24,25,26,18,19,20,27'
  11320. },
  11321. //Тесак, 13-я
  11322. "adv_angels_3pl_hell": {
  11323. first: '1,2,4,6,16,23,33,34,25,32,29,28,20,27',
  11324. second: '1,7,11,17,24,14,26,18,19,20,27,20,12,8',
  11325. third: '1,9,3,5,10,22,31,36,31,30,15,28,29,30,21,13'
  11326. },
  11327. //Галахад, 13-я
  11328. "adv_strongford_3pl_hell": {
  11329. first: '1,2,5,11,14,20,26,21,30,35,38,41,43,44',
  11330. second: '1,2,6,12,15,7,16,17,23,22,27,42,34,36,39,44',
  11331. third: '1,3,8,9,13,18,19,28,0,33,37,40,32,45,44'
  11332. },
  11333. //Орион, 13-я
  11334. "adv_ghirwil_3pl_hell": {
  11335. first: '1,2,3,6,8,12,11,15,21,27,36,34,33,35,37',
  11336. second: '1,2,4,6,9,13,18,17,16,22,28,29,30,31,25,19',
  11337. third: '1,2,5,6,10,13,14,20,26,32,38,41,40,39,37'
  11338. },
  11339. //Джинджер, 13-я
  11340. "adv_valley_3pl_hell": {
  11341. first: '1,3,2,6,11,17,25,30,35,34,29,24,21,17,12,7',
  11342. second: '1,4,8,13,18,22,26,31,36,40,45,44,43,38,33,28',
  11343. third: '1,5,9,14,19,23,27,32,37,42,48,51,50,49,46,52'
  11344. }
  11345. }
  11346. callStartBattle = {
  11347. name: "adventure_turnStartBattle",
  11348. args: {},
  11349. ident: "body"
  11350. }
  11351. callEndBattle = {
  11352. name: "adventure_endBattle",
  11353. args: {
  11354. result: {},
  11355. progress: {},
  11356. },
  11357. ident: "body"
  11358. }
  11359. callCollectBuff = {
  11360. name: "adventure_turnCollectBuff",
  11361. args: {},
  11362. ident: "body"
  11363. }
  11364.  
  11365. constructor(resolve, reject) {
  11366. this.resolve = resolve;
  11367. this.reject = reject;
  11368. }
  11369.  
  11370. async start(type) {
  11371. //this.type = type || this.type;
  11372. //this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11373. const data = await Send(JSON.stringify({
  11374. calls: [
  11375. this.callAdventureInfo,
  11376. this.callTeamGetAll,
  11377. this.callTeamGetFavor
  11378. ]
  11379. }));
  11380. //тест прикла1
  11381. this.path = await this.getPath(data.results[0].result.response.mapIdent);
  11382. if (!this.path) {
  11383. this.end();
  11384. return;
  11385. }
  11386. return this.checkAdventureInfo(data.results);
  11387. }
  11388.  
  11389. async getPath(mapId) {
  11390. //const oldVal = getSaveVal('adventurePath', '');
  11391. //const keyPath = `adventurePath:${this.mapIdent}`;
  11392. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11393. {
  11394. msg: I18N('START_ADVENTURE'),
  11395. placeholder: '1,2,3,4,5,6',
  11396. isInput: true,
  11397. //default: getSaveVal(keyPath, oldVal)
  11398. default: getSaveVal('adventurePath', '')
  11399. },
  11400. {
  11401. msg: ' Начать по пути №1! ',
  11402. placeholder: '1,2,3',
  11403. isInput: true,
  11404. default: this.defaultWays[mapId]?.first
  11405. },
  11406. {
  11407. msg: ' Начать по пути №2! ',
  11408. placeholder: '1,2,3',
  11409. isInput: true,
  11410. default: this.defaultWays[mapId]?.second
  11411. },
  11412. {
  11413. msg: ' Начать по пути №3! ',
  11414. placeholder: '1,2,3',
  11415. isInput: true,
  11416. default: this.defaultWays[mapId]?.third
  11417. },
  11418. {
  11419. msg: I18N('BTN_CANCEL'),
  11420. result: false,
  11421. isCancel: true
  11422. },
  11423. ]);
  11424. if (!answer) {
  11425. this.terminatеReason = I18N('BTN_CANCELED');
  11426. return false;
  11427. }
  11428.  
  11429. let path = answer.split(',');
  11430. if (path.length < 2) {
  11431. path = answer.split('-');
  11432. }
  11433. if (path.length < 2) {
  11434. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11435. return false;
  11436. }
  11437.  
  11438. for (let p in path) {
  11439. path[p] = +path[p].trim()
  11440. if (Number.isNaN(path[p])) {
  11441. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11442. return false;
  11443. }
  11444. }
  11445.  
  11446. /*if (!this.checkPath(path)) {
  11447. return false;
  11448. }*/
  11449. //setSaveVal(keyPath, answer);
  11450. setSaveVal('adventurePath', answer);
  11451. return path;
  11452. }
  11453. /*
  11454. checkPath(path) {
  11455. for (let i = 0; i < path.length - 1; i++) {
  11456. const currentPoint = path[i];
  11457. const nextPoint = path[i + 1];
  11458.  
  11459. const isValidPath = this.paths.some(p =>
  11460. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  11461. (p.from_id === nextPoint && p.to_id === currentPoint)
  11462. );
  11463.  
  11464. if (!isValidPath) {
  11465. this.terminatеReason = I18N('INCORRECT_WAY', {
  11466. from: currentPoint,
  11467. to: nextPoint,
  11468. });
  11469. return false;
  11470. }
  11471. }
  11472.  
  11473. return true;
  11474. }
  11475. */
  11476. async checkAdventureInfo(data) {
  11477. this.advInfo = data[0].result.response;
  11478. if (!this.advInfo) {
  11479. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  11480. return this.end();
  11481. }
  11482. const heroesTeam = data[1].result.response.adventure_hero;
  11483. const favor = data[2]?.result.response.adventure_hero;
  11484. const heroes = heroesTeam.slice(0, 5);
  11485. const pet = heroesTeam[5];
  11486. this.args = {
  11487. pet,
  11488. heroes,
  11489. favor,
  11490. path: [],
  11491. broadcast: false
  11492. }
  11493. const advUserInfo = this.advInfo.users[userInfo.id];
  11494. this.turnsLeft = advUserInfo.turnsLeft;
  11495. this.currentNode = advUserInfo.currentNode;
  11496. this.nodes = this.advInfo.nodes;
  11497. //this.paths = this.advInfo.paths;
  11498. //this.mapIdent = this.advInfo.mapIdent;
  11499.  
  11500. /*this.path = await this.getPath();
  11501. if (!this.path) {
  11502. return this.end();
  11503. }*/
  11504.  
  11505. if (this.currentNode == 1 && this.path[0] != 1) {
  11506. this.path.unshift(1);
  11507. }
  11508.  
  11509. return this.loop();
  11510. }
  11511.  
  11512. async loop() {
  11513. const position = this.path.indexOf(+this.currentNode);
  11514. if (!(~position)) {
  11515. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  11516. return this.end();
  11517. }
  11518. this.path = this.path.slice(position);
  11519. if ((this.path.length - 1) > this.turnsLeft &&
  11520. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  11521. { msg: I18N('YES_CONTINUE'), result: false },
  11522. { msg: I18N('BTN_NO'), result: true },
  11523. ])) {
  11524. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  11525. return this.end();
  11526. }
  11527. const toPath = [];
  11528. for (const nodeId of this.path) {
  11529. if (!this.turnsLeft) {
  11530. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  11531. return this.end();
  11532. }
  11533. toPath.push(nodeId);
  11534. console.log(toPath);
  11535. if (toPath.length > 1) {
  11536. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  11537. }
  11538. if (nodeId == this.currentNode) {
  11539. continue;
  11540. }
  11541.  
  11542. const nodeInfo = this.getNodeInfo(nodeId);
  11543. if (nodeInfo.type == 'TYPE_COMBAT') {
  11544. if (nodeInfo.state == 'empty') {
  11545. this.turnsLeft--;
  11546. continue;
  11547. }
  11548.  
  11549. /**
  11550. * Disable regular battle cancellation
  11551. *
  11552. * Отключаем штатную отменую боя
  11553. */
  11554. isCancalBattle = false;
  11555. if (await this.battle(toPath)) {
  11556. this.turnsLeft--;
  11557. toPath.splice(0, toPath.indexOf(nodeId));
  11558. nodeInfo.state = 'empty';
  11559. isCancalBattle = true;
  11560. continue;
  11561. }
  11562. isCancalBattle = true;
  11563. return this.end()
  11564. }
  11565.  
  11566. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11567. const buff = this.checkBuff(nodeInfo);
  11568. if (buff == null) {
  11569. continue;
  11570. }
  11571.  
  11572. if (await this.collectBuff(buff, toPath)) {
  11573. this.turnsLeft--;
  11574. toPath.splice(0, toPath.indexOf(nodeId));
  11575. continue;
  11576. }
  11577. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11578. return this.end();
  11579. }
  11580. }
  11581. this.terminatеReason = I18N('SUCCESS');
  11582. return this.end();
  11583. }
  11584.  
  11585. /**
  11586. * Carrying out a fight
  11587. *
  11588. * Проведение боя
  11589. */
  11590. async battle(path, preCalc = true) {
  11591. const data = await this.startBattle(path);
  11592. try {
  11593. const battle = data.results[0].result.response.battle;
  11594. const result = await Calc(battle);
  11595. if (result.result.win) {
  11596. const info = await this.endBattle(result);
  11597. if (info.results[0].result.response?.error) {
  11598. this.terminatеReason = I18N('BATTLE_END_ERROR');
  11599. return false;
  11600. }
  11601. } else {
  11602. await this.cancelBattle(result);
  11603.  
  11604. if (preCalc && await this.preCalcBattle(battle)) {
  11605. path = path.slice(-2);
  11606. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  11607. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  11608. const result = await this.battle(path, false);
  11609. if (result) {
  11610. setProgress(I18N('VICTORY'));
  11611. return true;
  11612. }
  11613. }
  11614. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  11615. return false;
  11616. }
  11617. return false;
  11618. }
  11619. } catch (error) {
  11620. console.error(error);
  11621. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  11622. { msg: I18N('BTN_NO'), result: false },
  11623. { msg: I18N('BTN_YES'), result: true },
  11624. ])) {
  11625. this.errorHandling(error, data);
  11626. }
  11627. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  11628. return false;
  11629. }
  11630. return true;
  11631. }
  11632.  
  11633. /**
  11634. * Recalculate battles
  11635. *
  11636. * Прерасчтет битвы
  11637. */
  11638. async preCalcBattle(battle) {
  11639. const countTestBattle = getInput('countTestBattle');
  11640. for (let i = 0; i < countTestBattle; i++) {
  11641. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  11642. const result = await Calc(battle);
  11643. if (result.result.win) {
  11644. console.log(i, countTestBattle);
  11645. return true;
  11646. }
  11647. }
  11648. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  11649. return false;
  11650. }
  11651.  
  11652. /**
  11653. * Starts a fight
  11654. *
  11655. * Начинает бой
  11656. */
  11657. startBattle(path) {
  11658. this.args.path = path;
  11659. this.callStartBattle.name = this.actions[this.type].startBattle;
  11660. this.callStartBattle.args = this.args
  11661. const calls = [this.callStartBattle];
  11662. return Send(JSON.stringify({ calls }));
  11663. }
  11664.  
  11665. cancelBattle(battle) {
  11666. const fixBattle = function (heroes) {
  11667. for (const ids in heroes) {
  11668. const hero = heroes[ids];
  11669. hero.energy = random(1, 999);
  11670. if (hero.hp > 0) {
  11671. hero.hp = random(1, hero.hp);
  11672. }
  11673. }
  11674. }
  11675. fixBattle(battle.progress[0].attackers.heroes);
  11676. fixBattle(battle.progress[0].defenders.heroes);
  11677. return this.endBattle(battle);
  11678. }
  11679.  
  11680. /**
  11681. * Ends the fight
  11682. *
  11683. * Заканчивает бой
  11684. */
  11685. endBattle(battle) {
  11686. this.callEndBattle.name = this.actions[this.type].endBattle;
  11687. this.callEndBattle.args.result = battle.result
  11688. this.callEndBattle.args.progress = battle.progress
  11689. const calls = [this.callEndBattle];
  11690. return Send(JSON.stringify({ calls }));
  11691. }
  11692.  
  11693. /**
  11694. * Checks if you can get a buff
  11695. *
  11696. * Проверяет можно ли получить баф
  11697. */
  11698. checkBuff(nodeInfo) {
  11699. let id = null;
  11700. let value = 0;
  11701. for (const buffId in nodeInfo.buffs) {
  11702. const buff = nodeInfo.buffs[buffId];
  11703. if (buff.owner == null && buff.value > value) {
  11704. id = buffId;
  11705. value = buff.value;
  11706. }
  11707. }
  11708. nodeInfo.buffs[id].owner = 'Я';
  11709. return id;
  11710. }
  11711.  
  11712. /**
  11713. * Collects a buff
  11714. *
  11715. * Собирает баф
  11716. */
  11717. async collectBuff(buff, path) {
  11718. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  11719. this.callCollectBuff.args = { buff, path };
  11720. const calls = [this.callCollectBuff];
  11721. return Send(JSON.stringify({ calls }));
  11722. }
  11723.  
  11724. getNodeInfo(nodeId) {
  11725. return this.nodes.find(node => node.id == nodeId);
  11726. }
  11727.  
  11728. errorHandling(error, data) {
  11729. //console.error(error);
  11730. let errorInfo = error.toString() + '\n';
  11731. try {
  11732. const errorStack = error.stack.split('\n');
  11733. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  11734. errorInfo += errorStack.slice(0, endStack).join('\n');
  11735. } catch (e) {
  11736. errorInfo += error.stack;
  11737. }
  11738. if (data) {
  11739. errorInfo += '\nData: ' + JSON.stringify(data);
  11740. }
  11741. copyText(errorInfo);
  11742. }
  11743.  
  11744. end() {
  11745. isCancalBattle = true;
  11746. setProgress(this.terminatеReason, true);
  11747. console.log(this.terminatеReason);
  11748. this.resolve();
  11749. }
  11750. }
  11751. class executeAdventure2 {
  11752.  
  11753. type = 'default';
  11754.  
  11755. actions = {
  11756. default: {
  11757. getInfo: "adventure_getInfo",
  11758. startBattle: 'adventure_turnStartBattle',
  11759. endBattle: 'adventure_endBattle',
  11760. collectBuff: 'adventure_turnCollectBuff'
  11761. },
  11762. solo: {
  11763. getInfo: "adventureSolo_getInfo",
  11764. startBattle: 'adventureSolo_turnStartBattle',
  11765. endBattle: 'adventureSolo_endBattle',
  11766. collectBuff: 'adventureSolo_turnCollectBuff'
  11767. }
  11768. }
  11769.  
  11770. terminatеReason = I18N('UNKNOWN');
  11771. callAdventureInfo = {
  11772. name: "adventure_getInfo",
  11773. args: {},
  11774. ident: "adventure_getInfo"
  11775. }
  11776. callTeamGetAll = {
  11777. name: "teamGetAll",
  11778. args: {},
  11779. ident: "teamGetAll"
  11780. }
  11781. callTeamGetFavor = {
  11782. name: "teamGetFavor",
  11783. args: {},
  11784. ident: "teamGetFavor"
  11785. }
  11786. callStartBattle = {
  11787. name: "adventure_turnStartBattle",
  11788. args: {},
  11789. ident: "body"
  11790. }
  11791. callEndBattle = {
  11792. name: "adventure_endBattle",
  11793. args: {
  11794. result: {},
  11795. progress: {},
  11796. },
  11797. ident: "body"
  11798. }
  11799. callCollectBuff = {
  11800. name: "adventure_turnCollectBuff",
  11801. args: {},
  11802. ident: "body"
  11803. }
  11804.  
  11805. constructor(resolve, reject) {
  11806. this.resolve = resolve;
  11807. this.reject = reject;
  11808. }
  11809.  
  11810. async start(type) {
  11811. this.type = type || this.type;
  11812. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  11813. const data = await Send(JSON.stringify({
  11814. calls: [
  11815. this.callAdventureInfo,
  11816. this.callTeamGetAll,
  11817. this.callTeamGetFavor
  11818. ]
  11819. }));
  11820. return this.checkAdventureInfo(data.results);
  11821. }
  11822.  
  11823. async getPath() {
  11824. const oldVal = getSaveVal('adventurePath', '');
  11825. const keyPath = `adventurePath:${this.mapIdent}`;
  11826. const answer = await popup.confirm(I18N('ENTER_THE_PATH'), [
  11827. {
  11828. msg: I18N('START_ADVENTURE'),
  11829. placeholder: '1,2,3,4,5,6',
  11830. isInput: true,
  11831. default: getSaveVal(keyPath, oldVal)
  11832. },
  11833. {
  11834. msg: I18N('BTN_CANCEL'),
  11835. result: false,
  11836. isCancel: true
  11837. },
  11838. ]);
  11839. if (!answer) {
  11840. this.terminatеReason = I18N('BTN_CANCELED');
  11841. return false;
  11842. }
  11843.  
  11844. let path = answer.split(',');
  11845. if (path.length < 2) {
  11846. path = answer.split('-');
  11847. }
  11848. if (path.length < 2) {
  11849. this.terminatеReason = I18N('MUST_TWO_POINTS');
  11850. return false;
  11851. }
  11852.  
  11853. for (let p in path) {
  11854. path[p] = +path[p].trim()
  11855. if (Number.isNaN(path[p])) {
  11856. this.terminatеReason = I18N('MUST_ONLY_NUMBERS');
  11857. return false;
  11858. }
  11859. }
  11860. if (!this.checkPath(path)) {
  11861. return false;
  11862. }
  11863. setSaveVal(keyPath, answer);
  11864. return path;
  11865. }
  11866.  
  11867. checkPath(path) {
  11868. for (let i = 0; i < path.length - 1; i++) {
  11869. const currentPoint = path[i];
  11870. const nextPoint = path[i + 1];
  11871.  
  11872. const isValidPath = this.paths.some(p =>
  11873. (p.from_id === currentPoint && p.to_id === nextPoint) ||
  11874. (p.from_id === nextPoint && p.to_id === currentPoint)
  11875. );
  11876.  
  11877. if (!isValidPath) {
  11878. this.terminatеReason = I18N('INCORRECT_WAY', {
  11879. from: currentPoint,
  11880. to: nextPoint,
  11881. });
  11882. return false;
  11883. }
  11884. }
  11885.  
  11886. return true;
  11887. }
  11888.  
  11889. async checkAdventureInfo(data) {
  11890. this.advInfo = data[0].result.response;
  11891. if (!this.advInfo) {
  11892. this.terminatеReason = I18N('NOT_ON_AN_ADVENTURE') ;
  11893. return this.end();
  11894. }
  11895. const heroesTeam = data[1].result.response.adventure_hero;
  11896. const favor = data[2]?.result.response.adventure_hero;
  11897. const heroes = heroesTeam.slice(0, 5);
  11898. const pet = heroesTeam[5];
  11899. this.args = {
  11900. pet,
  11901. heroes,
  11902. favor,
  11903. path: [],
  11904. broadcast: false
  11905. }
  11906. const advUserInfo = this.advInfo.users[userInfo.id];
  11907. this.turnsLeft = advUserInfo.turnsLeft;
  11908. this.currentNode = advUserInfo.currentNode;
  11909. this.nodes = this.advInfo.nodes;
  11910. this.paths = this.advInfo.paths;
  11911. this.mapIdent = this.advInfo.mapIdent;
  11912.  
  11913. this.path = await this.getPath();
  11914. if (!this.path) {
  11915. return this.end();
  11916. }
  11917.  
  11918. if (this.currentNode == 1 && this.path[0] != 1) {
  11919. this.path.unshift(1);
  11920. }
  11921.  
  11922. return this.loop();
  11923. }
  11924.  
  11925. async loop() {
  11926. const position = this.path.indexOf(+this.currentNode);
  11927. if (!(~position)) {
  11928. this.terminatеReason = I18N('YOU_IN_NOT_ON_THE_WAY');
  11929. return this.end();
  11930. }
  11931. this.path = this.path.slice(position);
  11932. if ((this.path.length - 1) > this.turnsLeft &&
  11933. await popup.confirm(I18N('ATTEMPTS_NOT_ENOUGH'), [
  11934. { msg: I18N('YES_CONTINUE'), result: false },
  11935. { msg: I18N('BTN_NO'), result: true },
  11936. ])) {
  11937. this.terminatеReason = I18N('NOT_ENOUGH_AP');
  11938. return this.end();
  11939. }
  11940. const toPath = [];
  11941. for (const nodeId of this.path) {
  11942. if (!this.turnsLeft) {
  11943. this.terminatеReason = I18N('ATTEMPTS_ARE_OVER');
  11944. return this.end();
  11945. }
  11946. toPath.push(nodeId);
  11947. console.log(toPath);
  11948. if (toPath.length > 1) {
  11949. setProgress(toPath.join(' > ') + ` ${I18N('MOVES')}: ` + this.turnsLeft);
  11950. }
  11951. if (nodeId == this.currentNode) {
  11952. continue;
  11953. }
  11954.  
  11955. const nodeInfo = this.getNodeInfo(nodeId);
  11956. if (nodeInfo.type == 'TYPE_COMBAT') {
  11957. if (nodeInfo.state == 'empty') {
  11958. this.turnsLeft--;
  11959. continue;
  11960. }
  11961.  
  11962. /**
  11963. * Disable regular battle cancellation
  11964. *
  11965. * Отключаем штатную отменую боя
  11966. */
  11967. isCancalBattle = false;
  11968. if (await this.battle(toPath)) {
  11969. this.turnsLeft--;
  11970. toPath.splice(0, toPath.indexOf(nodeId));
  11971. nodeInfo.state = 'empty';
  11972. isCancalBattle = true;
  11973. continue;
  11974. }
  11975. isCancalBattle = true;
  11976. return this.end()
  11977. }
  11978.  
  11979. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  11980. const buff = this.checkBuff(nodeInfo);
  11981. if (buff == null) {
  11982. continue;
  11983. }
  11984.  
  11985. if (await this.collectBuff(buff, toPath)) {
  11986. this.turnsLeft--;
  11987. toPath.splice(0, toPath.indexOf(nodeId));
  11988. continue;
  11989. }
  11990. this.terminatеReason = I18N('BUFF_GET_ERROR');
  11991. return this.end();
  11992. }
  11993. }
  11994. this.terminatеReason = I18N('SUCCESS');
  11995. return this.end();
  11996. }
  11997.  
  11998. /**
  11999. * Carrying out a fight
  12000. *
  12001. * Проведение боя
  12002. */
  12003. async battle(path, preCalc = true) {
  12004. const data = await this.startBattle(path);
  12005. try {
  12006. const battle = data.results[0].result.response.battle;
  12007. const result = await Calc(battle);
  12008. if (result.result.win) {
  12009. const info = await this.endBattle(result);
  12010. if (info.results[0].result.response?.error) {
  12011. this.terminatеReason = I18N('BATTLE_END_ERROR');
  12012. return false;
  12013. }
  12014. } else {
  12015. await this.cancelBattle(result);
  12016.  
  12017. if (preCalc && await this.preCalcBattle(battle)) {
  12018. path = path.slice(-2);
  12019. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  12020. setProgress(`${I18N('AUTOBOT')}: ${i}/${getInput('countAutoBattle')}`);
  12021. const result = await this.battle(path, false);
  12022. if (result) {
  12023. setProgress(I18N('VICTORY'));
  12024. return true;
  12025. }
  12026. }
  12027. this.terminatеReason = I18N('FAILED_TO_WIN_AUTO');
  12028. return false;
  12029. }
  12030. return false;
  12031. }
  12032. } catch (error) {
  12033. console.error(error);
  12034. if (await popup.confirm(I18N('ERROR_OF_THE_BATTLE_COPY'), [
  12035. { msg: I18N('BTN_NO'), result: false },
  12036. { msg: I18N('BTN_YES'), result: true },
  12037. ])) {
  12038. this.errorHandling(error, data);
  12039. }
  12040. this.terminatеReason = I18N('ERROR_DURING_THE_BATTLE');
  12041. return false;
  12042. }
  12043. return true;
  12044. }
  12045.  
  12046. /**
  12047. * Recalculate battles
  12048. *
  12049. * Прерасчтет битвы
  12050. */
  12051. async preCalcBattle(battle) {
  12052. const countTestBattle = getInput('countTestBattle');
  12053. for (let i = 0; i < countTestBattle; i++) {
  12054. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  12055. const result = await Calc(battle);
  12056. if (result.result.win) {
  12057. console.log(i, countTestBattle);
  12058. return true;
  12059. }
  12060. }
  12061. this.terminatеReason = I18N('NO_CHANCE_WIN') + countTestBattle;
  12062. return false;
  12063. }
  12064.  
  12065. /**
  12066. * Starts a fight
  12067. *
  12068. * Начинает бой
  12069. */
  12070. startBattle(path) {
  12071. this.args.path = path;
  12072. this.callStartBattle.name = this.actions[this.type].startBattle;
  12073. this.callStartBattle.args = this.args
  12074. const calls = [this.callStartBattle];
  12075. return Send(JSON.stringify({ calls }));
  12076. }
  12077.  
  12078. cancelBattle(battle) {
  12079. const fixBattle = function (heroes) {
  12080. for (const ids in heroes) {
  12081. const hero = heroes[ids];
  12082. hero.energy = random(1, 999);
  12083. if (hero.hp > 0) {
  12084. hero.hp = random(1, hero.hp);
  12085. }
  12086. }
  12087. }
  12088. fixBattle(battle.progress[0].attackers.heroes);
  12089. fixBattle(battle.progress[0].defenders.heroes);
  12090. return this.endBattle(battle);
  12091. }
  12092.  
  12093. /**
  12094. * Ends the fight
  12095. *
  12096. * Заканчивает бой
  12097. */
  12098. endBattle(battle) {
  12099. this.callEndBattle.name = this.actions[this.type].endBattle;
  12100. this.callEndBattle.args.result = battle.result
  12101. this.callEndBattle.args.progress = battle.progress
  12102. const calls = [this.callEndBattle];
  12103. return Send(JSON.stringify({ calls }));
  12104. }
  12105.  
  12106. /**
  12107. * Checks if you can get a buff
  12108. *
  12109. * Проверяет можно ли получить баф
  12110. */
  12111. checkBuff(nodeInfo) {
  12112. let id = null;
  12113. let value = 0;
  12114. for (const buffId in nodeInfo.buffs) {
  12115. const buff = nodeInfo.buffs[buffId];
  12116. if (buff.owner == null && buff.value > value) {
  12117. id = buffId;
  12118. value = buff.value;
  12119. }
  12120. }
  12121. nodeInfo.buffs[id].owner = 'Я';
  12122. return id;
  12123. }
  12124.  
  12125. /**
  12126. * Collects a buff
  12127. *
  12128. * Собирает баф
  12129. */
  12130. async collectBuff(buff, path) {
  12131. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  12132. this.callCollectBuff.args = { buff, path };
  12133. const calls = [this.callCollectBuff];
  12134. return Send(JSON.stringify({ calls }));
  12135. }
  12136.  
  12137. getNodeInfo(nodeId) {
  12138. return this.nodes.find(node => node.id == nodeId);
  12139. }
  12140.  
  12141. errorHandling(error, data) {
  12142. //console.error(error);
  12143. let errorInfo = error.toString() + '\n';
  12144. try {
  12145. const errorStack = error.stack.split('\n');
  12146. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  12147. errorInfo += errorStack.slice(0, endStack).join('\n');
  12148. } catch (e) {
  12149. errorInfo += error.stack;
  12150. }
  12151. if (data) {
  12152. errorInfo += '\nData: ' + JSON.stringify(data);
  12153. }
  12154. copyText(errorInfo);
  12155. }
  12156.  
  12157. end() {
  12158. isCancalBattle = true;
  12159. setProgress(this.terminatеReason, true);
  12160. console.log(this.terminatеReason);
  12161. this.resolve();
  12162. }
  12163. }
  12164. /**
  12165. * Passage of brawls
  12166. *
  12167. * Прохождение потасовок
  12168. */
  12169. function testBrawls(isAuto) {
  12170. return new Promise((resolve, reject) => {
  12171. const brawls = new executeBrawls(resolve, reject);
  12172. brawls.start(brawlsPack, isAuto);
  12173. });
  12174. }
  12175. /**
  12176. * Passage of brawls
  12177. *
  12178. * Прохождение потасовок
  12179. */
  12180. class executeBrawls {
  12181. callBrawlQuestGetInfo = {
  12182. name: "brawl_questGetInfo",
  12183. args: {},
  12184. ident: "brawl_questGetInfo"
  12185. }
  12186. callBrawlFindEnemies = {
  12187. name: "brawl_findEnemies",
  12188. args: {},
  12189. ident: "brawl_findEnemies"
  12190. }
  12191. callBrawlQuestFarm = {
  12192. name: "brawl_questFarm",
  12193. args: {},
  12194. ident: "brawl_questFarm"
  12195. }
  12196. callUserGetInfo = {
  12197. name: "userGetInfo",
  12198. args: {},
  12199. ident: "userGetInfo"
  12200. }
  12201. callTeamGetMaxUpgrade = {
  12202. name: "teamGetMaxUpgrade",
  12203. args: {},
  12204. ident: "teamGetMaxUpgrade"
  12205. }
  12206. callBrawlGetInfo = {
  12207. name: "brawl_getInfo",
  12208. args: {},
  12209. ident: "brawl_getInfo"
  12210. }
  12211.  
  12212. stats = {
  12213. win: 0,
  12214. loss: 0,
  12215. count: 0,
  12216. }
  12217.  
  12218. stage = {
  12219. '3': 1,
  12220. '7': 2,
  12221. '12': 3,
  12222. }
  12223.  
  12224. attempts = 0;
  12225.  
  12226. constructor(resolve, reject) {
  12227. this.resolve = resolve;
  12228. this.reject = reject;
  12229. const allHeroIds = Object.keys(lib.getData('hero'));
  12230. this.callTeamGetMaxUpgrade.args.units = {
  12231. hero: allHeroIds.filter((id) => +id < 1000),
  12232. titan: allHeroIds.filter((id) => +id >= 4000 && +id < 4100),
  12233. pet: allHeroIds.filter((id) => +id >= 6000 && +id < 6100),
  12234. };
  12235. }
  12236.  
  12237. async start(args, isAuto) {
  12238. this.isAuto = isAuto;
  12239. this.args = args;
  12240. isCancalBattle = false;
  12241. this.brawlInfo = await this.getBrawlInfo();
  12242. this.attempts = this.brawlInfo.attempts;
  12243.  
  12244. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12245. this.end(I18N('DONT_HAVE_LIVES'));
  12246. return;
  12247. }
  12248.  
  12249. while (1) {
  12250. if (!isBrawlsAutoStart) {
  12251. this.end(I18N('BTN_CANCELED'));
  12252. return;
  12253. }
  12254.  
  12255. const maxStage = this.brawlInfo.questInfo.stage;
  12256. const stage = this.stage[maxStage];
  12257. const progress = this.brawlInfo.questInfo.progress;
  12258.  
  12259. setProgress(
  12260. `${I18N('STAGE')} ${stage}: ${progress}/${maxStage}<br>${I18N('FIGHTS')}: ${this.stats.count}<br>${I18N('WINS')}: ${
  12261. this.stats.win
  12262. }<br>${I18N('LOSSES')}: ${this.stats.loss}<br>${I18N('LIVES')}: ${this.attempts}<br>${I18N('STOP')}`,
  12263. false,
  12264. function () {
  12265. isBrawlsAutoStart = false;
  12266. }
  12267. );
  12268.  
  12269. if (this.brawlInfo.questInfo.canFarm) {
  12270. const result = await this.questFarm();
  12271. console.log(result);
  12272. }
  12273.  
  12274. if (!this.continueAttack && this.brawlInfo.questInfo.stage == 12 && this.brawlInfo.questInfo.progress == 12) {
  12275. if (
  12276. await popup.confirm(I18N('BRAWL_DAILY_TASK_COMPLETED'), [
  12277. { msg: I18N('BTN_NO'), result: true },
  12278. { msg: I18N('BTN_YES'), result: false },
  12279. ])
  12280. ) {
  12281. this.end(I18N('SUCCESS'));
  12282. return;
  12283. } else {
  12284. this.continueAttack = true;
  12285. }
  12286. }
  12287.  
  12288. if (!this.attempts && !this.info.boughtEndlessLivesToday) {
  12289. this.end(I18N('DONT_HAVE_LIVES'))
  12290. return;
  12291. }
  12292.  
  12293. const enemie = Object.values(this.brawlInfo.findEnemies).shift();
  12294.  
  12295. // Автоматический подбор пачки
  12296. if (this.isAuto) {
  12297. if (this.mandatoryId <= 4000 && this.mandatoryId != 13) {
  12298. this.end(I18N('BRAWL_AUTO_PACK_NOT_CUR_HERO'));
  12299. return;
  12300. }
  12301. if (this.mandatoryId >= 4000 && this.mandatoryId < 4100) {
  12302. this.args = await this.updateTitanPack(enemie.heroes);
  12303. } else if (this.mandatoryId < 4000 && this.mandatoryId == 13) {
  12304. this.args = await this.updateHeroesPack(enemie.heroes);
  12305. }
  12306. }
  12307.  
  12308. const result = await this.battle(enemie.userId);
  12309. this.brawlInfo = {
  12310. questInfo: result[1].result.response,
  12311. findEnemies: result[2].result.response,
  12312. };
  12313. }
  12314. }
  12315.  
  12316. async updateTitanPack(enemieHeroes) {
  12317. const packs = [
  12318. [4033, 4040, 4041, 4042, 4043],
  12319. [4032, 4040, 4041, 4042, 4043],
  12320. [4031, 4040, 4041, 4042, 4043],
  12321. [4030, 4040, 4041, 4042, 4043],
  12322. [4032, 4033, 4040, 4042, 4043],
  12323. [4030, 4033, 4041, 4042, 4043],
  12324. [4031, 4033, 4040, 4042, 4043],
  12325. [4032, 4033, 4040, 4041, 4043],
  12326. [4023, 4040, 4041, 4042, 4043],
  12327. [4030, 4033, 4040, 4042, 4043],
  12328. [4031, 4033, 4040, 4041, 4043],
  12329. [4022, 4040, 4041, 4042, 4043],
  12330. [4030, 4033, 4040, 4041, 4043],
  12331. [4021, 4040, 4041, 4042, 4043],
  12332. [4020, 4040, 4041, 4042, 4043],
  12333. [4023, 4033, 4040, 4042, 4043],
  12334. [4030, 4032, 4033, 4042, 4043],
  12335. [4023, 4033, 4040, 4041, 4043],
  12336. [4031, 4032, 4033, 4040, 4043],
  12337. [4030, 4032, 4033, 4041, 4043],
  12338. [4030, 4031, 4033, 4042, 4043],
  12339. [4013, 4040, 4041, 4042, 4043],
  12340. [4030, 4032, 4033, 4040, 4043],
  12341. [4030, 4031, 4033, 4041, 4043],
  12342. [4012, 4040, 4041, 4042, 4043],
  12343. [4030, 4031, 4033, 4040, 4043],
  12344. [4011, 4040, 4041, 4042, 4043],
  12345. [4010, 4040, 4041, 4042, 4043],
  12346. [4023, 4032, 4033, 4042, 4043],
  12347. [4022, 4032, 4033, 4042, 4043],
  12348. [4023, 4032, 4033, 4041, 4043],
  12349. [4021, 4032, 4033, 4042, 4043],
  12350. [4022, 4032, 4033, 4041, 4043],
  12351. [4023, 4030, 4033, 4042, 4043],
  12352. [4023, 4032, 4033, 4040, 4043],
  12353. [4013, 4033, 4040, 4042, 4043],
  12354. [4020, 4032, 4033, 4042, 4043],
  12355. [4021, 4032, 4033, 4041, 4043],
  12356. [4022, 4030, 4033, 4042, 4043],
  12357. [4022, 4032, 4033, 4040, 4043],
  12358. [4023, 4030, 4033, 4041, 4043],
  12359. [4023, 4031, 4033, 4040, 4043],
  12360. [4013, 4033, 4040, 4041, 4043],
  12361. [4020, 4031, 4033, 4042, 4043],
  12362. [4020, 4032, 4033, 4041, 4043],
  12363. [4021, 4030, 4033, 4042, 4043],
  12364. [4021, 4032, 4033, 4040, 4043],
  12365. [4022, 4030, 4033, 4041, 4043],
  12366. [4022, 4031, 4033, 4040, 4043],
  12367. [4023, 4030, 4033, 4040, 4043],
  12368. [4030, 4031, 4032, 4033, 4043],
  12369. [4003, 4040, 4041, 4042, 4043],
  12370. [4020, 4030, 4033, 4042, 4043],
  12371. [4020, 4031, 4033, 4041, 4043],
  12372. [4020, 4032, 4033, 4040, 4043],
  12373. [4021, 4030, 4033, 4041, 4043],
  12374. [4021, 4031, 4033, 4040, 4043],
  12375. [4022, 4030, 4033, 4040, 4043],
  12376. [4030, 4031, 4032, 4033, 4042],
  12377. [4002, 4040, 4041, 4042, 4043],
  12378. [4020, 4030, 4033, 4041, 4043],
  12379. [4020, 4031, 4033, 4040, 4043],
  12380. [4021, 4030, 4033, 4040, 4043],
  12381. [4030, 4031, 4032, 4033, 4041],
  12382. [4001, 4040, 4041, 4042, 4043],
  12383. [4030, 4031, 4032, 4033, 4040],
  12384. [4000, 4040, 4041, 4042, 4043],
  12385. [4013, 4032, 4033, 4042, 4043],
  12386. [4012, 4032, 4033, 4042, 4043],
  12387. [4013, 4032, 4033, 4041, 4043],
  12388. [4023, 4031, 4032, 4033, 4043],
  12389. [4011, 4032, 4033, 4042, 4043],
  12390. [4012, 4032, 4033, 4041, 4043],
  12391. [4013, 4030, 4033, 4042, 4043],
  12392. [4013, 4032, 4033, 4040, 4043],
  12393. [4023, 4030, 4032, 4033, 4043],
  12394. [4003, 4033, 4040, 4042, 4043],
  12395. [4013, 4023, 4040, 4042, 4043],
  12396. [4010, 4032, 4033, 4042, 4043],
  12397. [4011, 4032, 4033, 4041, 4043],
  12398. [4012, 4030, 4033, 4042, 4043],
  12399. [4012, 4032, 4033, 4040, 4043],
  12400. [4013, 4030, 4033, 4041, 4043],
  12401. [4013, 4031, 4033, 4040, 4043],
  12402. [4023, 4030, 4031, 4033, 4043],
  12403. [4003, 4033, 4040, 4041, 4043],
  12404. [4013, 4023, 4040, 4041, 4043],
  12405. [4010, 4031, 4033, 4042, 4043],
  12406. [4010, 4032, 4033, 4041, 4043],
  12407. [4011, 4030, 4033, 4042, 4043],
  12408. [4011, 4032, 4033, 4040, 4043],
  12409. [4012, 4030, 4033, 4041, 4043],
  12410. [4012, 4031, 4033, 4040, 4043],
  12411. [4013, 4030, 4033, 4040, 4043],
  12412. [4010, 4030, 4033, 4042, 4043],
  12413. [4010, 4031, 4033, 4041, 4043],
  12414. [4010, 4032, 4033, 4040, 4043],
  12415. [4011, 4030, 4033, 4041, 4043],
  12416. [4011, 4031, 4033, 4040, 4043],
  12417. [4012, 4030, 4033, 4040, 4043],
  12418. [4010, 4030, 4033, 4041, 4043],
  12419. [4010, 4031, 4033, 4040, 4043],
  12420. [4011, 4030, 4033, 4040, 4043],
  12421. [4003, 4032, 4033, 4042, 4043],
  12422. [4002, 4032, 4033, 4042, 4043],
  12423. [4003, 4032, 4033, 4041, 4043],
  12424. [4013, 4031, 4032, 4033, 4043],
  12425. [4001, 4032, 4033, 4042, 4043],
  12426. [4002, 4032, 4033, 4041, 4043],
  12427. [4003, 4030, 4033, 4042, 4043],
  12428. [4003, 4032, 4033, 4040, 4043],
  12429. [4013, 4030, 4032, 4033, 4043],
  12430. [4003, 4023, 4040, 4042, 4043],
  12431. [4000, 4032, 4033, 4042, 4043],
  12432. [4001, 4032, 4033, 4041, 4043],
  12433. [4002, 4030, 4033, 4042, 4043],
  12434. [4002, 4032, 4033, 4040, 4043],
  12435. [4003, 4030, 4033, 4041, 4043],
  12436. [4003, 4031, 4033, 4040, 4043],
  12437. [4020, 4022, 4023, 4042, 4043],
  12438. [4013, 4030, 4031, 4033, 4043],
  12439. [4003, 4023, 4040, 4041, 4043],
  12440. [4000, 4031, 4033, 4042, 4043],
  12441. [4000, 4032, 4033, 4041, 4043],
  12442. [4001, 4030, 4033, 4042, 4043],
  12443. [4001, 4032, 4033, 4040, 4043],
  12444. [4002, 4030, 4033, 4041, 4043],
  12445. [4002, 4031, 4033, 4040, 4043],
  12446. [4003, 4030, 4033, 4040, 4043],
  12447. [4021, 4022, 4023, 4040, 4043],
  12448. [4020, 4022, 4023, 4041, 4043],
  12449. [4020, 4021, 4023, 4042, 4043],
  12450. [4023, 4030, 4031, 4032, 4033],
  12451. [4000, 4030, 4033, 4042, 4043],
  12452. [4000, 4031, 4033, 4041, 4043],
  12453. [4000, 4032, 4033, 4040, 4043],
  12454. [4001, 4030, 4033, 4041, 4043],
  12455. [4001, 4031, 4033, 4040, 4043],
  12456. [4002, 4030, 4033, 4040, 4043],
  12457. [4020, 4022, 4023, 4040, 4043],
  12458. [4020, 4021, 4023, 4041, 4043],
  12459. [4022, 4030, 4031, 4032, 4033],
  12460. [4000, 4030, 4033, 4041, 4043],
  12461. [4000, 4031, 4033, 4040, 4043],
  12462. [4001, 4030, 4033, 4040, 4043],
  12463. [4020, 4021, 4023, 4040, 4043],
  12464. [4021, 4030, 4031, 4032, 4033],
  12465. [4020, 4030, 4031, 4032, 4033],
  12466. [4003, 4031, 4032, 4033, 4043],
  12467. [4020, 4022, 4023, 4033, 4043],
  12468. [4003, 4030, 4032, 4033, 4043],
  12469. [4003, 4013, 4040, 4042, 4043],
  12470. [4020, 4021, 4023, 4033, 4043],
  12471. [4003, 4030, 4031, 4033, 4043],
  12472. [4003, 4013, 4040, 4041, 4043],
  12473. [4013, 4030, 4031, 4032, 4033],
  12474. [4012, 4030, 4031, 4032, 4033],
  12475. [4011, 4030, 4031, 4032, 4033],
  12476. [4010, 4030, 4031, 4032, 4033],
  12477. [4013, 4023, 4031, 4032, 4033],
  12478. [4013, 4023, 4030, 4032, 4033],
  12479. [4020, 4022, 4023, 4032, 4033],
  12480. [4013, 4023, 4030, 4031, 4033],
  12481. [4021, 4022, 4023, 4030, 4033],
  12482. [4020, 4022, 4023, 4031, 4033],
  12483. [4020, 4021, 4023, 4032, 4033],
  12484. [4020, 4021, 4022, 4023, 4043],
  12485. [4003, 4030, 4031, 4032, 4033],
  12486. [4020, 4022, 4023, 4030, 4033],
  12487. [4020, 4021, 4023, 4031, 4033],
  12488. [4020, 4021, 4022, 4023, 4042],
  12489. [4002, 4030, 4031, 4032, 4033],
  12490. [4020, 4021, 4023, 4030, 4033],
  12491. [4020, 4021, 4022, 4023, 4041],
  12492. [4001, 4030, 4031, 4032, 4033],
  12493. [4020, 4021, 4022, 4023, 4040],
  12494. [4000, 4030, 4031, 4032, 4033],
  12495. [4003, 4023, 4031, 4032, 4033],
  12496. [4013, 4020, 4022, 4023, 4043],
  12497. [4003, 4023, 4030, 4032, 4033],
  12498. [4010, 4012, 4013, 4042, 4043],
  12499. [4013, 4020, 4021, 4023, 4043],
  12500. [4003, 4023, 4030, 4031, 4033],
  12501. [4011, 4012, 4013, 4040, 4043],
  12502. [4010, 4012, 4013, 4041, 4043],
  12503. [4010, 4011, 4013, 4042, 4043],
  12504. [4020, 4021, 4022, 4023, 4033],
  12505. [4010, 4012, 4013, 4040, 4043],
  12506. [4010, 4011, 4013, 4041, 4043],
  12507. [4020, 4021, 4022, 4023, 4032],
  12508. [4010, 4011, 4013, 4040, 4043],
  12509. [4020, 4021, 4022, 4023, 4031],
  12510. [4020, 4021, 4022, 4023, 4030],
  12511. [4003, 4013, 4031, 4032, 4033],
  12512. [4010, 4012, 4013, 4033, 4043],
  12513. [4003, 4020, 4022, 4023, 4043],
  12514. [4013, 4020, 4022, 4023, 4033],
  12515. [4003, 4013, 4030, 4032, 4033],
  12516. [4010, 4011, 4013, 4033, 4043],
  12517. [4003, 4020, 4021, 4023, 4043],
  12518. [4013, 4020, 4021, 4023, 4033],
  12519. [4003, 4013, 4030, 4031, 4033],
  12520. [4010, 4012, 4013, 4023, 4043],
  12521. [4003, 4020, 4022, 4023, 4033],
  12522. [4010, 4012, 4013, 4032, 4033],
  12523. [4010, 4011, 4013, 4023, 4043],
  12524. [4003, 4020, 4021, 4023, 4033],
  12525. [4011, 4012, 4013, 4030, 4033],
  12526. [4010, 4012, 4013, 4031, 4033],
  12527. [4010, 4011, 4013, 4032, 4033],
  12528. [4013, 4020, 4021, 4022, 4023],
  12529. [4010, 4012, 4013, 4030, 4033],
  12530. [4010, 4011, 4013, 4031, 4033],
  12531. [4012, 4020, 4021, 4022, 4023],
  12532. [4010, 4011, 4013, 4030, 4033],
  12533. [4011, 4020, 4021, 4022, 4023],
  12534. [4010, 4020, 4021, 4022, 4023],
  12535. [4010, 4012, 4013, 4023, 4033],
  12536. [4000, 4002, 4003, 4042, 4043],
  12537. [4010, 4011, 4013, 4023, 4033],
  12538. [4001, 4002, 4003, 4040, 4043],
  12539. [4000, 4002, 4003, 4041, 4043],
  12540. [4000, 4001, 4003, 4042, 4043],
  12541. [4010, 4011, 4012, 4013, 4043],
  12542. [4003, 4020, 4021, 4022, 4023],
  12543. [4000, 4002, 4003, 4040, 4043],
  12544. [4000, 4001, 4003, 4041, 4043],
  12545. [4010, 4011, 4012, 4013, 4042],
  12546. [4002, 4020, 4021, 4022, 4023],
  12547. [4000, 4001, 4003, 4040, 4043],
  12548. [4010, 4011, 4012, 4013, 4041],
  12549. [4001, 4020, 4021, 4022, 4023],
  12550. [4010, 4011, 4012, 4013, 4040],
  12551. [4000, 4020, 4021, 4022, 4023],
  12552. [4001, 4002, 4003, 4033, 4043],
  12553. [4000, 4002, 4003, 4033, 4043],
  12554. [4003, 4010, 4012, 4013, 4043],
  12555. [4003, 4013, 4020, 4022, 4023],
  12556. [4000, 4001, 4003, 4033, 4043],
  12557. [4003, 4010, 4011, 4013, 4043],
  12558. [4003, 4013, 4020, 4021, 4023],
  12559. [4010, 4011, 4012, 4013, 4033],
  12560. [4010, 4011, 4012, 4013, 4032],
  12561. [4010, 4011, 4012, 4013, 4031],
  12562. [4010, 4011, 4012, 4013, 4030],
  12563. [4001, 4002, 4003, 4023, 4043],
  12564. [4000, 4002, 4003, 4023, 4043],
  12565. [4003, 4010, 4012, 4013, 4033],
  12566. [4000, 4002, 4003, 4032, 4033],
  12567. [4000, 4001, 4003, 4023, 4043],
  12568. [4003, 4010, 4011, 4013, 4033],
  12569. [4001, 4002, 4003, 4030, 4033],
  12570. [4000, 4002, 4003, 4031, 4033],
  12571. [4000, 4001, 4003, 4032, 4033],
  12572. [4010, 4011, 4012, 4013, 4023],
  12573. [4000, 4002, 4003, 4030, 4033],
  12574. [4000, 4001, 4003, 4031, 4033],
  12575. [4010, 4011, 4012, 4013, 4022],
  12576. [4000, 4001, 4003, 4030, 4033],
  12577. [4010, 4011, 4012, 4013, 4021],
  12578. [4010, 4011, 4012, 4013, 4020],
  12579. [4001, 4002, 4003, 4013, 4043],
  12580. [4001, 4002, 4003, 4023, 4033],
  12581. [4000, 4002, 4003, 4013, 4043],
  12582. [4000, 4002, 4003, 4023, 4033],
  12583. [4003, 4010, 4012, 4013, 4023],
  12584. [4000, 4001, 4003, 4013, 4043],
  12585. [4000, 4001, 4003, 4023, 4033],
  12586. [4003, 4010, 4011, 4013, 4023],
  12587. [4001, 4002, 4003, 4013, 4033],
  12588. [4000, 4002, 4003, 4013, 4033],
  12589. [4000, 4001, 4003, 4013, 4033],
  12590. [4000, 4001, 4002, 4003, 4043],
  12591. [4003, 4010, 4011, 4012, 4013],
  12592. [4000, 4001, 4002, 4003, 4042],
  12593. [4002, 4010, 4011, 4012, 4013],
  12594. [4000, 4001, 4002, 4003, 4041],
  12595. [4001, 4010, 4011, 4012, 4013],
  12596. [4000, 4001, 4002, 4003, 4040],
  12597. [4000, 4010, 4011, 4012, 4013],
  12598. [4001, 4002, 4003, 4013, 4023],
  12599. [4000, 4002, 4003, 4013, 4023],
  12600. [4000, 4001, 4003, 4013, 4023],
  12601. [4000, 4001, 4002, 4003, 4033],
  12602. [4000, 4001, 4002, 4003, 4032],
  12603. [4000, 4001, 4002, 4003, 4031],
  12604. [4000, 4001, 4002, 4003, 4030],
  12605. [4000, 4001, 4002, 4003, 4023],
  12606. [4000, 4001, 4002, 4003, 4022],
  12607. [4000, 4001, 4002, 4003, 4021],
  12608. [4000, 4001, 4002, 4003, 4020],
  12609. [4000, 4001, 4002, 4003, 4013],
  12610. [4000, 4001, 4002, 4003, 4012],
  12611. [4000, 4001, 4002, 4003, 4011],
  12612. [4000, 4001, 4002, 4003, 4010],
  12613. ].filter((p) => p.includes(this.mandatoryId));
  12614. const bestPack = {
  12615. pack: packs[0],
  12616. winRate: 0,
  12617. countBattle: 0,
  12618. id: 0,
  12619. };
  12620. for (const id in packs) {
  12621. const pack = packs[id];
  12622. const attackers = this.maxUpgrade.filter((e) => pack.includes(e.id)).reduce((obj, e) => ({ ...obj, [e.id]: e }), {});
  12623. const battle = {
  12624. attackers,
  12625. defenders: [enemieHeroes],
  12626. type: 'brawl_titan',
  12627. };
  12628. const isRandom = this.isRandomBattle(battle);
  12629. const stat = {
  12630. count: 0,
  12631. win: 0,
  12632. winRate: 0,
  12633. };
  12634. for (let i = 1; i <= 20; i++) {
  12635. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12636. const result = await Calc(battle);
  12637. stat.win += result.result.win;
  12638. stat.count += 1;
  12639. stat.winRate = stat.win / stat.count;
  12640. if (!isRandom || (i >= 2 && stat.winRate < 0.65) || (i >= 10 && stat.winRate == 1)) {
  12641. break;
  12642. }
  12643. }
  12644. if (!isRandom && stat.win) {
  12645. return {
  12646. favor: {},
  12647. heroes: pack,
  12648. };
  12649. }
  12650. if (stat.winRate > 0.85) {
  12651. return {
  12652. favor: {},
  12653. heroes: pack,
  12654. };
  12655. }
  12656. if (stat.winRate > bestPack.winRate) {
  12657. bestPack.countBattle = stat.count;
  12658. bestPack.winRate = stat.winRate;
  12659. bestPack.pack = pack;
  12660. bestPack.id = id;
  12661. }
  12662. }
  12663. //console.log(bestPack.id, bestPack.pack, bestPack.winRate, bestPack.countBattle);
  12664. return {
  12665. favor: {},
  12666. heroes: bestPack.pack,
  12667. };
  12668. }
  12669. isRandomPack(pack) {
  12670. const ids = Object.keys(pack);
  12671. return ids.includes('4023') || ids.includes('4021');
  12672. }
  12673. isRandomBattle(battle) {
  12674. return this.isRandomPack(battle.attackers) || this.isRandomPack(battle.defenders[0]);
  12675. }
  12676. async updateHeroesPack(enemieHeroes) {
  12677. const packs = [{id:1,args:{userId:-830021,heroes:[63,13,9,48,1],pet:6006,favor:{1:6004,9:6005,13:6002,48:6e3,63:6009}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6027:130,8270:1,8271:1},power:195886,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6005,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:7020.32,strength:3068,armor:19995,dodge:14644,magicPower:64780.6,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6005,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6041:130,8272:1,8273:1},power:193520,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6009,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:54213.6,strength:2877,armor:800,armorPenetration:32477.6,magicResist:8526,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6009,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:2,args:{userId:-830049,heroes:[46,13,52,49,4],pet:6006,favor:{4:6001,13:6002,46:6006,49:6004,52:6003}},attackers:{4:{id:4,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{255:130,256:130,257:130,258:130,6007:130},power:189782,star:6,runes:[43750,43750,43750,43750,43750],skins:{4:60,35:60,92:60,161:60,236:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:3065,hp:482631,intelligence:3402,physicalAttack:2800,strength:17488,armor:56262.6,magicPower:51021,magicResist:36971,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},46:{id:46,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{230:130,231:130,232:130,233:130,6032:130},power:189653,star:6,runes:[43750,43750,43750,43750,43750],skins:{101:60,159:60,178:60,262:60,315:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2122,hp:637517,intelligence:16208,physicalAttack:50,strength:5151,armor:38507.6,magicPower:74495.6,magicResist:22237,skin:0,favorPetId:6006,favorPower:11064},49:{id:49,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{245:130,246:130,247:130,248:130,6022:130},power:193163,star:6,runes:[43750,43750,43750,43750,43750],skins:{104:60,191:60,252:60,305:60,329:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[10,1,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17935,hp:250405,intelligence:2790,physicalAttack:40413.6,strength:2987,armor:11655,dodge:14844.28,magicResist:3175,physicalCritChance:14135,skin:0,favorPetId:6004,favorPower:11064},52:{id:52,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{310:130,311:130,312:130,313:130,6017:130},power:185075,star:6,runes:[43750,43750,43750,43750,43750],skins:{188:60,213:60,248:60,297:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[5,8,2,13,15,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:18270,hp:226207,intelligence:2620,physicalAttack:44206,strength:3260,armor:13150,armorPenetration:40301,magicPower:9957.6,magicResist:33892.6,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:3,args:{userId:8263225,heroes:[29,63,13,48,1],pet:6006,favor:{1:6004,13:6002,29:6006,48:6e3,63:6003}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},48:{id:48,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{240:130,241:130,242:130,243:130,6002:130},power:190584,star:6,runes:[43750,43750,43750,43750,43750],skins:{103:60,165:60,217:60,296:60,326:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6e3,type:"hero",perks:[5,2],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:17308,hp:397737,intelligence:2888,physicalAttack:40298.32,physicalCritChance:12280,strength:3169,armor:12185,armorPenetration:20137.6,magicResist:24816,skin:0,favorPetId:6e3,favorPower:11064},63:{id:63,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{442:130,443:130,444:130,445:130,6017:130,8272:1,8273:1},power:191031,star:6,runes:[43750,43750,43750,43750,43750],skins:{341:60,350:60,351:60,352:1},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[6,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17931,hp:488832,intelligence:2737,physicalAttack:44256,strength:2877,armor:800,armorPenetration:22520,magicPower:9957.6,magicResist:18483.6,physicalCritChance:9545,modifiedSkillTier:3,skin:0,favorPetId:6003,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:4,args:{userId:8263247,heroes:[55,13,40,51,1],pet:6006,favor:{1:6007,13:6002,40:6004,51:6006,55:6001}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6035:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:65773.6,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6007,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},51:{id:51,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{305:130,306:130,307:130,308:130,6032:130},power:190005,star:6,runes:[43750,43750,43750,43750,43750],skins:{181:60,219:60,260:60,290:60,334:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,9,1,12],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2526,hp:438205,intelligence:18851,physicalAttack:50,strength:2921,armor:39442.6,magicPower:88978.6,magicResist:22960,skin:0,favorPetId:6006,favorPower:11064},55:{id:55,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{325:130,326:130,327:130,328:130,6007:130},power:190529,star:6,runes:[43750,43750,43750,43750,43750],skins:{239:60,278:60,309:60,327:60,346:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[7,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2631,hp:499591,intelligence:19438,physicalAttack:50,strength:3286,armor:32892.6,armorPenetration:36870,magicPower:60704,magicResist:10010,skin:0,favorPetId:6001,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:5,args:{userId:8263303,heroes:[31,29,13,40,1],pet:6004,favor:{1:6001,13:6007,29:6002,31:6006,40:6004}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6007:130,8268:1,8269:1},power:195170,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:519225,intelligence:3644,physicalAttack:1524,strength:17049,armor:22677.6,dodge:14245,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6001,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6035:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6007,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6012:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:27759,magicPenetration:9957.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6002,favorPower:11064},31:{id:31,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{155:130,156:130,157:130,158:130,6032:130},power:190305,star:6,runes:[43750,43750,43750,43750,43750],skins:{44:60,94:60,133:60,200:60,295:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2781,dodge:12620,hp:374484,intelligence:18945,physicalAttack:78,strength:2916,armor:28049.6,magicPower:67686.6,magicResist:15252,skin:0,favorPetId:6006,favorPower:11064},40:{id:40,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{200:130,201:130,202:130,203:130,6022:130,8244:1,8245:1},power:192541,star:6,runes:[43750,43750,43750,43750,43750],skins:{53:60,89:60,129:60,168:60,314:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[5,9,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:17540,hp:343191,intelligence:2805,physicalAttack:48430.6,strength:2976,armor:24410,dodge:15732.28,magicResist:17633,modifiedSkillTier:3,skin:0,favorPetId:6004,favorPower:11064},6004:{id:6004,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6020:130,6021:130},power:181943,type:"pet",perks:[5],name:null,armorPenetration:47911,intelligence:11064,strength:12360}}},{id:6,args:{userId:8263317,heroes:[62,13,9,56,61],pet:6003,favor:{9:6004,13:6002,56:6006,61:6001,62:6003}},attackers:{9:{id:9,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{335:130,336:130,337:130,338:130,6022:130,8270:1,8271:1},power:198525,star:6,runes:[43750,43750,43750,43750,43750],skins:{9:60,41:60,163:60,189:60,311:60,338:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[7,2,20],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3068,hp:227134,intelligence:19003,physicalAttack:10007.6,strength:3068,armor:19995,dodge:17631.28,magicPower:54823,magicResist:31597,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6012:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:19060,magicPenetration:58138.6,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6002,favorPower:11064},56:{id:56,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{376:130,377:130,378:130,379:130,6032:130},power:184420,star:6,runes:[43750,43750,43750,43750,43750],skins:{264:60,279:60,294:60,321:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[5,7,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2791,hp:235111,intelligence:18813,physicalAttack:50,strength:2656,armor:22982.6,magicPenetration:48159,magicPower:75598.6,magicResist:13990,skin:0,favorPetId:6006,favorPower:11064},61:{id:61,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{411:130,412:130,413:130,414:130,6007:130},power:184868,star:6,runes:[43750,43750,43750,43750,43750],skins:{302:60,306:60,323:60,340:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6001,type:"hero",perks:[4,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2545,hp:466176,intelligence:3320,physicalAttack:34305,strength:18309,armor:31077.6,magicResist:24101,physicalCritChance:9009,skin:0,favorPetId:6001,favorPower:11064},62:{id:62,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{437:130,438:130,439:130,440:130,6017:130},power:173991,star:6,runes:[43750,43750,43750,43750,43750],skins:{320:60,343:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6003,type:"hero",perks:[8,7,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2530,hp:276010,intelligence:19245,physicalAttack:50,strength:3543,armor:12890,magicPenetration:23658,magicPower:80966.6,magicResist:12447.6,skin:0,favorPetId:6003,favorPower:11064},6003:{id:6003,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6015:130,6016:130},power:181943,type:"pet",perks:[8],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}},{id:7,args:{userId:8263335,heroes:[32,29,13,43,1],pet:6006,favor:{1:6004,13:6008,29:6006,32:6002,43:6007}},attackers:{1:{id:1,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{2:130,3:130,4:130,5:130,6022:130,8268:1,8269:1},power:198058,star:6,runes:[43750,43750,43750,43750,43750],skins:{1:60,54:60,95:60,154:60,250:60,325:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6004,type:"hero",perks:[4,1],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:3093,hp:419649,intelligence:3644,physicalAttack:11481.6,strength:17049,armor:12720,dodge:17232.28,magicPenetration:22780,magicPower:55816,magicResist:1580,modifiedSkillTier:5,skin:0,favorPetId:6004,favorPower:11064},13:{id:"13",xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{452:130,453:130,454:130,455:130,6038:130,8274:1,8275:1},power:194833,star:6,runes:[43750,43750,43750,43750,43750],skins:{13:60,38:60,148:60,199:60,240:60,335:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6008,type:"hero",perks:[7,2,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,9,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,9,10]},agility:2885,hp:344763,intelligence:17625,physicalAttack:50,strength:3020,armor:29017.6,magicPenetration:48181,magicPower:70100.6,magicResist:27227,modifiedSkillTier:4,skin:0,favorPetId:6008,favorPower:11064},29:{id:29,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{145:130,146:130,147:130,148:130,6032:130},power:189790,star:6,runes:[43750,43750,43750,43750,43750],skins:{29:60,72:60,88:60,147:60,242:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6006,type:"hero",perks:[9,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2885,hp:491431,intelligence:18331,physicalAttack:106,strength:3020,armor:37716.6,magicPower:76792.6,magicResist:31377,skin:0,favorPetId:6006,favorPower:11064},32:{id:32,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{160:130,161:130,162:130,163:130,6012:130},power:189956,star:6,runes:[43750,43750,43750,43750,43750],skins:{45:60,73:60,81:60,135:60,212:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6002,type:"hero",perks:[7,5,2,22],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2815,hp:551066,intelligence:18800,physicalAttack:50,strength:2810,armor:19040,magicPenetration:9957.6,magicPower:89495.6,magicResist:20805,skin:0,favorPetId:6002,favorPower:11064},43:{id:43,xp:3625195,level:130,color:18,slots:[0,0,0,0,0,0],skills:{215:130,216:130,217:130,218:130,6035:130},power:189593,star:6,runes:[43750,43750,43750,43750,43750],skins:{98:60,130:60,169:60,201:60,304:60},currentSkin:0,titanGiftLevel:30,titanCoinsSpent:null,artifacts:[{level:130,star:6},{level:130,star:6},{level:130,star:6}],scale:1,petId:6007,type:"hero",perks:[7,9,1,21],ascensions:{1:[0,1,2,3,4,5,6,7,8,9],2:[0,1,2,3,4,5,6,7,8,10],3:[0,1,2,3,4,5,6,7,8,9],4:[0,1,2,3,4,5,6,7,8,9],5:[0,1,2,3,4,5,6,7,8,10]},agility:2447,hp:265217,intelligence:18758,physicalAttack:50,strength:2842,armor:18637.6,magicPenetration:52439,magicPower:75465.6,magicResist:22695,skin:0,favorPetId:6007,favorPower:11064},6006:{id:6006,color:10,star:6,xp:450551,level:130,slots:[25,50,50,25,50,50],skills:{6030:130,6031:130},power:181943,type:"pet",perks:[5,9],name:null,intelligence:11064,magicPenetration:47911,strength:12360}}}];
  12678. const bestPack = {
  12679. pack: packs[0],
  12680. countWin: 0,
  12681. }
  12682. for (const pack of packs) {
  12683. const attackers = pack.attackers;
  12684. const battle = {
  12685. attackers,
  12686. defenders: [enemieHeroes],
  12687. type: 'brawl',
  12688. };
  12689. let countWinBattles = 0;
  12690. let countTestBattle = 10;
  12691. for (let i = 0; i < countTestBattle; i++) {
  12692. battle.seed = Math.floor(Date.now() / 1000) + Math.random() * 1000;
  12693. const result = await Calc(battle);
  12694. if (result.result.win) {
  12695. countWinBattles++;
  12696. }
  12697. if (countWinBattles > 7) {
  12698. console.log(pack)
  12699. return pack.args;
  12700. }
  12701. }
  12702. if (countWinBattles > bestPack.countWin) {
  12703. bestPack.countWin = countWinBattles;
  12704. bestPack.pack = pack.args;
  12705. }
  12706. }
  12707. console.log(bestPack);
  12708. return bestPack.pack;
  12709. }
  12710. async questFarm() {
  12711. const calls = [this.callBrawlQuestFarm];
  12712. const result = await Send(JSON.stringify({ calls }));
  12713. return result.results[0].result.response;
  12714. }
  12715. async getBrawlInfo() {
  12716. const data = await Send(JSON.stringify({
  12717. calls: [
  12718. this.callUserGetInfo,
  12719. this.callBrawlQuestGetInfo,
  12720. this.callBrawlFindEnemies,
  12721. this.callTeamGetMaxUpgrade,
  12722. this.callBrawlGetInfo,
  12723. ]
  12724. }));
  12725. let attempts = data.results[0].result.response.refillable.find(n => n.id == 48);
  12726. const maxUpgrade = data.results[3].result.response;
  12727. const maxHero = Object.values(maxUpgrade.hero);
  12728. const maxTitan = Object.values(maxUpgrade.titan);
  12729. const maxPet = Object.values(maxUpgrade.pet);
  12730. this.maxUpgrade = [...maxHero, ...maxPet, ...maxTitan];
  12731. this.info = data.results[4].result.response;
  12732. this.mandatoryId = lib.data.brawl.promoHero[this.info.id].promoHero;
  12733. return {
  12734. attempts: attempts.amount,
  12735. questInfo: data.results[1].result.response,
  12736. findEnemies: data.results[2].result.response,
  12737. }
  12738. }
  12739.  
  12740. /**
  12741. * Carrying out a fight
  12742. *
  12743. * Проведение боя
  12744. */
  12745. async battle(userId) {
  12746. this.stats.count++;
  12747. const battle = await this.startBattle(userId, this.args);
  12748. const result = await Calc(battle);
  12749. console.log(result.result);
  12750. if (result.result.win) {
  12751. this.stats.win++;
  12752. } else {
  12753. this.stats.loss++;
  12754. if (!this.info.boughtEndlessLivesToday) {
  12755. this.attempts--;
  12756. }
  12757. }
  12758. return await this.endBattle(result);
  12759. // return await this.cancelBattle(result);
  12760. }
  12761.  
  12762. /**
  12763. * Starts a fight
  12764. *
  12765. * Начинает бой
  12766. */
  12767. async startBattle(userId, args) {
  12768. const call = {
  12769. name: "brawl_startBattle",
  12770. args,
  12771. ident: "brawl_startBattle"
  12772. }
  12773. call.args.userId = userId;
  12774. const calls = [call];
  12775. const result = await Send(JSON.stringify({ calls }));
  12776. return result.results[0].result.response;
  12777. }
  12778.  
  12779. cancelBattle(battle) {
  12780. const fixBattle = function (heroes) {
  12781. for (const ids in heroes) {
  12782. const hero = heroes[ids];
  12783. hero.energy = random(1, 999);
  12784. if (hero.hp > 0) {
  12785. hero.hp = random(1, hero.hp);
  12786. }
  12787. }
  12788. }
  12789. fixBattle(battle.progress[0].attackers.heroes);
  12790. fixBattle(battle.progress[0].defenders.heroes);
  12791. return this.endBattle(battle);
  12792. }
  12793.  
  12794. /**
  12795. * Ends the fight
  12796. *
  12797. * Заканчивает бой
  12798. */
  12799. async endBattle(battle) {
  12800. battle.progress[0].attackers.input = ['auto', 0, 0, 'auto', 0, 0];
  12801. const calls = [{
  12802. name: "brawl_endBattle",
  12803. args: {
  12804. result: battle.result,
  12805. progress: battle.progress
  12806. },
  12807. ident: "brawl_endBattle"
  12808. },
  12809. this.callBrawlQuestGetInfo,
  12810. this.callBrawlFindEnemies,
  12811. ];
  12812. const result = await Send(JSON.stringify({ calls }));
  12813. return result.results;
  12814. }
  12815.  
  12816. end(endReason) {
  12817. isCancalBattle = true;
  12818. isBrawlsAutoStart = false;
  12819. setProgress(endReason, true);
  12820. console.log(endReason);
  12821. this.resolve();
  12822. }
  12823. }
  12824.  
  12825. // подземку вконце впихнул
  12826. function DungeonFull() {
  12827. return new Promise((resolve, reject) => {
  12828. const dung = new executeDungeon2(resolve, reject);
  12829. const titanit = getInput('countTitanit');
  12830. dung.start(titanit);
  12831. });
  12832. }
  12833. /** Прохождение подземелья */
  12834. function executeDungeon2(resolve, reject) {
  12835. let dungeonActivity = 0;
  12836. let startDungeonActivity = 0;
  12837. let maxDungeonActivity = 150;
  12838. let limitDungeonActivity = 30180;
  12839. let countShowStats = 1;
  12840. //let fastMode = isChecked('fastMode');
  12841. let end = false;
  12842.  
  12843. let countTeam = [];
  12844. let timeDungeon = {
  12845. all: new Date().getTime(),
  12846. findAttack: 0,
  12847. attackNeutral: 0,
  12848. attackEarthOrFire: 0
  12849. }
  12850.  
  12851. let titansStates = {};
  12852. let bestBattle = {};
  12853.  
  12854. let teams = {
  12855. neutral: [],
  12856. water: [],
  12857. earth: [],
  12858. fire: [],
  12859. hero: []
  12860. }
  12861.  
  12862. let callsExecuteDungeon = {
  12863. calls: [{
  12864. name: "dungeonGetInfo",
  12865. args: {},
  12866. ident: "dungeonGetInfo"
  12867. }, {
  12868. name: "teamGetAll",
  12869. args: {},
  12870. ident: "teamGetAll"
  12871. }, {
  12872. name: "teamGetFavor",
  12873. args: {},
  12874. ident: "teamGetFavor"
  12875. }, {
  12876. name: "clanGetInfo",
  12877. args: {},
  12878. ident: "clanGetInfo"
  12879. }]
  12880. }
  12881.  
  12882. this.start = async function(titanit) {
  12883. //maxDungeonActivity = titanit > limitDungeonActivity ? limitDungeonActivity : titanit;
  12884. maxDungeonActivity = titanit || getInput('countTitanit');
  12885. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  12886. }
  12887.  
  12888. /** Получаем данные по подземелью */
  12889. function startDungeon(e) {
  12890. stopDung = false; // стоп подземка
  12891. let res = e.results;
  12892. let dungeonGetInfo = res[0].result.response;
  12893. if (!dungeonGetInfo) {
  12894. endDungeon('noDungeon', res);
  12895. return;
  12896. }
  12897. console.log("Начинаем копать на фулл: ", new Date());
  12898. let teamGetAll = res[1].result.response;
  12899. let teamGetFavor = res[2].result.response;
  12900. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  12901. startDungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  12902. titansStates = dungeonGetInfo.states.titans;
  12903.  
  12904. teams.hero = {
  12905. favor: teamGetFavor.dungeon_hero,
  12906. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  12907. teamNum: 0,
  12908. }
  12909. let heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  12910. if (heroPet) {
  12911. teams.hero.pet = heroPet;
  12912. }
  12913. teams.neutral = getTitanTeam('neutral');
  12914. teams.water = {
  12915. favor: {},
  12916. heroes: getTitanTeam('water'),
  12917. teamNum: 0,
  12918. };
  12919. teams.earth = {
  12920. favor: {},
  12921. heroes: getTitanTeam('earth'),
  12922. teamNum: 0,
  12923. };
  12924. teams.fire = {
  12925. favor: {},
  12926. heroes: getTitanTeam('fire'),
  12927. teamNum: 0,
  12928. };
  12929.  
  12930. checkFloor(dungeonGetInfo);
  12931. }
  12932.  
  12933. function getTitanTeam(type) {
  12934. switch (type) {
  12935. case 'neutral':
  12936. return [4023, 4022, 4012, 4021, 4011, 4010, 4020];
  12937. case 'water':
  12938. return [4000, 4001, 4002, 4003]
  12939. .filter(e => !titansStates[e]?.isDead);
  12940. case 'earth':
  12941. return [4020, 4022, 4021, 4023]
  12942. .filter(e => !titansStates[e]?.isDead);
  12943. case 'fire':
  12944. return [4010, 4011, 4012, 4013]
  12945. .filter(e => !titansStates[e]?.isDead);
  12946. }
  12947. }
  12948.  
  12949. /** Создать копию объекта */
  12950. function clone(a) {
  12951. return JSON.parse(JSON.stringify(a));
  12952. }
  12953.  
  12954. /** Находит стихию на этаже */
  12955. function findElement(floor, element) {
  12956. for (let i in floor) {
  12957. if (floor[i].attackerType === element) {
  12958. return i;
  12959. }
  12960. }
  12961. return undefined;
  12962. }
  12963.  
  12964. /** Проверяем этаж */
  12965. async function checkFloor(dungeonInfo) {
  12966. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  12967. saveProgress();
  12968. return;
  12969. }
  12970. // console.log(dungeonInfo, dungeonActivity);
  12971. setProgress(`${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  12972. //setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  12973. if (dungeonActivity >= maxDungeonActivity) {
  12974. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  12975. return;
  12976. }
  12977. let activity = dungeonActivity - startDungeonActivity;
  12978. titansStates = dungeonInfo.states.titans;
  12979. if (stopDung){
  12980. endDungeon('Стоп подземка,', 'набрано титанита: ' + dungeonActivity + '/' + maxDungeonActivity);
  12981. return;
  12982. }
  12983. /*if (activity / 1000 > countShowStats) {
  12984. countShowStats++;
  12985. showStats();
  12986. }*/
  12987. bestBattle = {};
  12988. let floorChoices = dungeonInfo.floor.userData;
  12989. if (floorChoices.length > 1) {
  12990. for (let element in teams) {
  12991. let teamNum = findElement(floorChoices, element);
  12992. if (!!teamNum) {
  12993. if (element == 'earth') {
  12994. teamNum = await chooseEarthOrFire(floorChoices);
  12995. if (teamNum < 0) {
  12996. endDungeon('Невозможно победить без потери Титана!', dungeonInfo);
  12997. return;
  12998. }
  12999. }
  13000. chooseElement(floorChoices[teamNum].attackerType, teamNum);
  13001. return;
  13002. }
  13003. }
  13004. } else {
  13005. chooseElement(floorChoices[0].attackerType, 0);
  13006. }
  13007. }
  13008.  
  13009. /** Выбираем огнем или землей атаковать */
  13010. async function chooseEarthOrFire(floorChoices) {
  13011. bestBattle.recovery = -11;
  13012. let selectedTeamNum = -1;
  13013. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  13014. for (let teamNum in floorChoices) {
  13015. let attackerType = floorChoices[teamNum].attackerType;
  13016. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  13017. }
  13018. }
  13019. console.log("Выбор команды огня или земли: ", selectedTeamNum < 0 ? "не сделан" : floorChoices[selectedTeamNum].attackerType);
  13020. return selectedTeamNum;
  13021. }
  13022.  
  13023. /** Попытка атаки землей и огнем */
  13024. async function attemptAttackEarthOrFire(teamNum, attackerType, attempt) {
  13025. let start = new Date();
  13026. let team = clone(teams[attackerType]);
  13027. let startIndex = team.heroes.length + attempt - 4;
  13028. if (startIndex >= 0) {
  13029. team.heroes = team.heroes.slice(startIndex);
  13030. let recovery = await getBestRecovery(teamNum, attackerType, team, 25);
  13031. if (recovery > bestBattle.recovery) {
  13032. bestBattle.recovery = recovery;
  13033. bestBattle.selectedTeamNum = teamNum;
  13034. bestBattle.team = team;
  13035. }
  13036. }
  13037. let workTime = new Date().getTime() - start.getTime();
  13038. timeDungeon.attackEarthOrFire += workTime;
  13039. if (bestBattle.recovery < -10) {
  13040. return -1;
  13041. }
  13042. return bestBattle.selectedTeamNum;
  13043. }
  13044.  
  13045. /** Выбираем стихию для атаки */
  13046. async function chooseElement(attackerType, teamNum) {
  13047. let result;
  13048. switch (attackerType) {
  13049. case 'hero':
  13050. case 'water':
  13051. result = await startBattle(teamNum, attackerType, teams[attackerType]);
  13052. break;
  13053. case 'earth':
  13054. case 'fire':
  13055. result = await attackEarthOrFire(teamNum, attackerType);
  13056. break;
  13057. case 'neutral':
  13058. result = await attackNeutral(teamNum, attackerType);
  13059. }
  13060. if (!!result && attackerType != 'hero') {
  13061. let recovery = (!!!bestBattle.recovery ? 10 * getRecovery(result) : bestBattle.recovery) * 100;
  13062. let titans = result.progress[0].attackers.heroes;
  13063. console.log("Проведен бой: " + attackerType +
  13064. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", titans);
  13065. }
  13066. endBattle(result);
  13067. }
  13068.  
  13069. /** Атакуем Землей или Огнем */
  13070. async function attackEarthOrFire(teamNum, attackerType) {
  13071. if (!!!bestBattle.recovery) {
  13072. bestBattle.recovery = -11;
  13073. let selectedTeamNum = -1;
  13074. for (let attempt = 0; selectedTeamNum < 0 && attempt < 4; attempt++) {
  13075. selectedTeamNum = await attemptAttackEarthOrFire(teamNum, attackerType, attempt);
  13076. }
  13077. if (selectedTeamNum < 0) {
  13078. endDungeon('Невозможно победить без потери Титана!', attackerType);
  13079. return;
  13080. }
  13081. }
  13082. return findAttack(teamNum, attackerType, bestBattle.team);
  13083. }
  13084.  
  13085. /** Находим подходящий результат для атаки */
  13086. async function findAttack(teamNum, attackerType, team) {
  13087. let start = new Date();
  13088. let recovery = -1000;
  13089. let iterations = 0;
  13090. let result;
  13091. let correction = 0.01;
  13092. for (let needRecovery = bestBattle.recovery; recovery < needRecovery; needRecovery -= correction, iterations++) {
  13093. result = await startBattle(teamNum, attackerType, team);
  13094. recovery = getRecovery(result);
  13095. }
  13096. bestBattle.recovery = recovery;
  13097. let workTime = new Date().getTime() - start.getTime();
  13098. timeDungeon.findAttack += workTime;
  13099. return result;
  13100. }
  13101.  
  13102. /** Атакуем Нейтральной командой */
  13103. async function attackNeutral(teamNum, attackerType) {
  13104. let start = new Date();
  13105. let factors = calcFactor();
  13106. bestBattle.recovery = -0.2;
  13107. await findBestBattleNeutral(teamNum, attackerType, factors, true)
  13108. if (bestBattle.recovery < 0 || (bestBattle.recovery < 0.2 && factors[0].value < 0.5)) {
  13109. let recovery = 100 * bestBattle.recovery;
  13110. console.log("Не удалось найти удачный бой в быстром режиме: " + attackerType +
  13111. ", recovery = " + (recovery > 0 ? "+" : "") + Math.round(recovery) + "% \r\n", bestBattle.attackers);
  13112. await findBestBattleNeutral(teamNum, attackerType, factors, false)
  13113. }
  13114. let workTime = new Date().getTime() - start.getTime();
  13115. timeDungeon.attackNeutral += workTime;
  13116. if (!!bestBattle.attackers) {
  13117. let team = getTeam(bestBattle.attackers);
  13118. return findAttack(teamNum, attackerType, team);
  13119. }
  13120. endDungeon('Не удалось найти удачный бой!', attackerType);
  13121. return undefined;
  13122. }
  13123.  
  13124. /** Находит лучшую нейтральную команду */
  13125. async function findBestBattleNeutral(teamNum, attackerType, factors, mode) {
  13126. let countFactors = factors.length < 4 ? factors.length : 4;
  13127. let aradgi = !titansStates['4013']?.isDead;
  13128. let edem = !titansStates['4023']?.isDead;
  13129. let dark = [4032, 4033].filter(e => !titansStates[e]?.isDead);
  13130. let light = [4042].filter(e => !titansStates[e]?.isDead);
  13131. let actions = [];
  13132. if (mode) {
  13133. for (let i = 0; i < countFactors; i++) {
  13134. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  13135. }
  13136. if (countFactors > 1) {
  13137. let firstId = factors[0].id;
  13138. let secondId = factors[1].id;
  13139. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13140. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13141. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, secondId)));
  13142. }
  13143. if (aradgi) {
  13144. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  13145. if (countFactors > 0) {
  13146. let firstId = factors[0].id;
  13147. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4000, 4013)));
  13148. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, 4013)));
  13149. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, 4013)));
  13150. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4003, 4013)));
  13151. }
  13152. if (edem) {
  13153. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4023, 4000, 4013)));
  13154. }
  13155. }
  13156. } else {
  13157. if (mode) {
  13158. for (let i = 0; i < factors.length; i++) {
  13159. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(factors[i].id)));
  13160. }
  13161. } else {
  13162. countFactors = factors.length < 2 ? factors.length : 2;
  13163. }
  13164. for (let i = 0; i < countFactors; i++) {
  13165. let mainId = factors[i].id;
  13166. if (aradgi && (mode || i > 0)) {
  13167. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, 4013)));
  13168. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, 4013)));
  13169. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, 4013)));
  13170. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, 4013)));
  13171. }
  13172. for (let i = 0; i < dark.length; i++) {
  13173. let darkId = dark[i];
  13174. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, darkId)));
  13175. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, darkId)));
  13176. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, darkId)));
  13177. }
  13178. for (let i = 0; i < light.length; i++) {
  13179. let lightId = light[i];
  13180. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, lightId)));
  13181. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, lightId)));
  13182. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4003, lightId)));
  13183. }
  13184. let isFull = mode || i > 0;
  13185. for (let j = isFull ? i + 1 : 2; j < factors.length; j++) {
  13186. let extraId = factors[j].id;
  13187. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4000, extraId)));
  13188. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4001, extraId)));
  13189. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(mainId, 4002, extraId)));
  13190. }
  13191. }
  13192. if (aradgi) {
  13193. if (mode) {
  13194. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(4013)));
  13195. }
  13196. for (let i = 0; i < dark.length; i++) {
  13197. let darkId = dark[i];
  13198. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4001, 4013)));
  13199. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(darkId, 4002, 4013)));
  13200. }
  13201. for (let i = 0; i < light.length; i++) {
  13202. let lightId = light[i];
  13203. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4001, 4013)));
  13204. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(lightId, 4002, 4013)));
  13205. }
  13206. }
  13207. for (let i = 0; i < dark.length; i++) {
  13208. let firstId = dark[i];
  13209. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  13210. for (let j = i + 1; j < dark.length; j++) {
  13211. let secondId = dark[j];
  13212. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13213. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13214. }
  13215. }
  13216. for (let i = 0; i < light.length; i++) {
  13217. let firstId = light[i];
  13218. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId)));
  13219. for (let j = i + 1; j < light.length; j++) {
  13220. let secondId = light[j];
  13221. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4001, secondId)));
  13222. actions.push(startBattle(teamNum, attackerType, getNeutralTeam(firstId, 4002, secondId)));
  13223. }
  13224. }
  13225. }
  13226. for (let result of await Promise.all(actions)) {
  13227. let recovery = getRecovery(result);
  13228. if (recovery > bestBattle.recovery) {
  13229. bestBattle.recovery = recovery;
  13230. bestBattle.attackers = result.progress[0].attackers.heroes;
  13231. }
  13232. }
  13233. }
  13234.  
  13235. /** Получаем нейтральную команду */
  13236. function getNeutralTeam(id, swapId, addId) {
  13237. let neutralTeam = clone(teams.water);
  13238. let neutral = neutralTeam.heroes;
  13239. if (neutral.length == 4) {
  13240. if (!!swapId) {
  13241. for (let i in neutral) {
  13242. if (neutral[i] == swapId) {
  13243. neutral[i] = addId;
  13244. }
  13245. }
  13246. }
  13247. } else if (!!addId) {
  13248. neutral.push(addId);
  13249. }
  13250. neutral.push(id);
  13251. return neutralTeam;
  13252. }
  13253.  
  13254. /** Получить команду титанов */
  13255. function getTeam(titans) {
  13256. return {
  13257. favor: {},
  13258. heroes: Object.keys(titans).map(id => parseInt(id)),
  13259. teamNum: 0,
  13260. };
  13261. }
  13262.  
  13263. /** Вычисляем фактор боеготовности титанов */
  13264. function calcFactor() {
  13265. let neutral = teams.neutral;
  13266. let factors = [];
  13267. for (let i in neutral) {
  13268. let titanId = neutral[i];
  13269. let titan = titansStates[titanId];
  13270. let factor = !!titan ? titan.hp / titan.maxHp + titan.energy / 10000.0 : 1;
  13271. if (factor > 0) {
  13272. factors.push({id: titanId, value: factor});
  13273. }
  13274. }
  13275. factors.sort(function(a, b) {
  13276. return a.value - b.value;
  13277. });
  13278. return factors;
  13279. }
  13280.  
  13281. /** Возвращает наилучший результат из нескольких боев */
  13282. async function getBestRecovery(teamNum, attackerType, team, countBattle) {
  13283. let bestRecovery = -1000;
  13284. let actions = [];
  13285. for (let i = 0; i < countBattle; i++) {
  13286. actions.push(startBattle(teamNum, attackerType, team));
  13287. }
  13288. for (let result of await Promise.all(actions)) {
  13289. let recovery = getRecovery(result);
  13290. if (recovery > bestRecovery) {
  13291. bestRecovery = recovery;
  13292. }
  13293. }
  13294. return bestRecovery;
  13295. }
  13296.  
  13297. /** Возвращает разницу в здоровье атакующей команды после и до битвы и проверяет здоровье титанов на необходимый минимум*/
  13298. function getRecovery(result) {
  13299. if (result.result.stars < 3) {
  13300. return -100;
  13301. }
  13302. let beforeSumFactor = 0;
  13303. let afterSumFactor = 0;
  13304. let beforeTitans = result.battleData.attackers;
  13305. let afterTitans = result.progress[0].attackers.heroes;
  13306. for (let i in afterTitans) {
  13307. let titan = afterTitans[i];
  13308. let percentHP = titan.hp / beforeTitans[i].hp;
  13309. let energy = titan.energy;
  13310. let factor = checkTitan(i, energy, percentHP) ? getFactor(i, energy, percentHP) : -100;
  13311. afterSumFactor += factor;
  13312. }
  13313. for (let i in beforeTitans) {
  13314. let titan = beforeTitans[i];
  13315. let state = titan.state;
  13316. beforeSumFactor += !!state ? getFactor(i, state.energy, state.hp / titan.hp) : 1;
  13317. }
  13318. return afterSumFactor - beforeSumFactor;
  13319. }
  13320.  
  13321. /** Возвращает состояние титана*/
  13322. function getFactor(id, energy, percentHP) {
  13323. let elemantId = id.slice(2, 3);
  13324. let isEarthOrFire = elemantId == '1' || elemantId == '2';
  13325. let energyBonus = id == '4020' && energy == 1000 ? 0.1 : energy / 20000.0;
  13326. let factor = percentHP + energyBonus;
  13327. return isEarthOrFire ? factor : factor / 10;
  13328. }
  13329.  
  13330. /** Проверяет состояние титана*/
  13331. function checkTitan(id, energy, percentHP) {
  13332. switch (id) {
  13333. case '4020':
  13334. return percentHP > 0.25 || (energy == 1000 && percentHP > 0.05);
  13335. break;
  13336. case '4010':
  13337. return percentHP + energy / 2000.0 > 0.63;
  13338. break;
  13339. case '4000':
  13340. return percentHP > 0.62 || (energy < 1000 && (
  13341. (percentHP > 0.45 && energy >= 400) ||
  13342. (percentHP > 0.3 && energy >= 670)));
  13343. }
  13344. return true;
  13345. }
  13346.  
  13347.  
  13348. /** Начинаем бой */
  13349. function startBattle(teamNum, attackerType, args) {
  13350. return new Promise(function (resolve, reject) {
  13351. args.teamNum = teamNum;
  13352. let startBattleCall = {
  13353. calls: [{
  13354. name: "dungeonStartBattle",
  13355. args,
  13356. ident: "body"
  13357. }]
  13358. }
  13359. send(JSON.stringify(startBattleCall), resultBattle, {
  13360. resolve,
  13361. teamNum,
  13362. attackerType
  13363. });
  13364. });
  13365. }
  13366.  
  13367. /** Возращает результат боя в промис */
  13368. /*function resultBattle(resultBattles, args) {
  13369. if (!!resultBattles && !!resultBattles.results) {
  13370. let battleData = resultBattles.results[0].result.response;
  13371. let battleType = "get_tower";
  13372. if (battleData.type == "dungeon_titan") {
  13373. battleType = "get_titan";
  13374. }
  13375. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];//тест подземка правки
  13376. BattleCalc(battleData, battleType, function (result) {
  13377. result.teamNum = args.teamNum;
  13378. result.attackerType = args.attackerType;
  13379. args.resolve(result);
  13380. });
  13381. } else {
  13382. endDungeon('Потеряна связь с сервером игры!', 'break');
  13383. }
  13384. }*/
  13385. function resultBattle(resultBattles, args) {
  13386. battleData = resultBattles.results[0].result.response;
  13387. battleType = "get_tower";
  13388. if (battleData.type == "dungeon_titan") {
  13389. battleType = "get_titan";
  13390. }
  13391. battleData.progress = [{ attackers: { input: ["auto", 0, 0, "auto", 0, 0] } }];
  13392. BattleCalc(battleData, battleType, function (result) {
  13393. result.teamNum = args.teamNum;
  13394. result.attackerType = args.attackerType;
  13395. args.resolve(result);
  13396. });
  13397. }
  13398.  
  13399. /** Заканчиваем бой */
  13400.  
  13401. ////
  13402. async function endBattle(battleInfo) {
  13403. if (!!battleInfo) {
  13404. const args = {
  13405. result: battleInfo.result,
  13406. progress: battleInfo.progress,
  13407. }
  13408. if (battleInfo.result.stars < 3) {
  13409. endDungeon('Герой или Титан мог погибнуть в бою!', battleInfo);
  13410. return;
  13411. }
  13412. if (countPredictionCard > 0) {
  13413. args.isRaid = true;
  13414. } else {
  13415. const timer = getTimer(battleInfo.battleTime);
  13416. console.log(timer);
  13417. await countdownTimer(timer, `${I18N('DUNGEON2')}: ${I18N('TITANIT')} ${dungeonActivity}/${maxDungeonActivity}`);
  13418. }
  13419. const calls = [{
  13420. name: "dungeonEndBattle",
  13421. args,
  13422. ident: "body"
  13423. }];
  13424. lastDungeonBattleData = null;
  13425. send(JSON.stringify({ calls }), resultEndBattle);
  13426. } else {
  13427. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  13428. }
  13429. }
  13430. /** Получаем и обрабатываем результаты боя */
  13431. function resultEndBattle(e) {
  13432. if (!!e && !!e.results) {
  13433. let battleResult = e.results[0].result.response;
  13434. if ('error' in battleResult) {
  13435. endDungeon('errorBattleResult', battleResult);
  13436. return;
  13437. }
  13438. let dungeonGetInfo = battleResult.dungeon ?? battleResult;
  13439. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  13440. checkFloor(dungeonGetInfo);
  13441. } else {
  13442. endDungeon('Потеряна связь с сервером игры!', 'break');
  13443. }
  13444. }
  13445.  
  13446. /** Добавить команду титанов в общий список команд */
  13447. function addTeam(team) {
  13448. for (let i in countTeam) {
  13449. if (equalsTeam(countTeam[i].team, team)) {
  13450. countTeam[i].count++;
  13451. return;
  13452. }
  13453. }
  13454. countTeam.push({team: team, count: 1});
  13455. }
  13456.  
  13457. /** Сравнить команды на равенство */
  13458. function equalsTeam(team1, team2) {
  13459. if (team1.length == team2.length) {
  13460. for (let i in team1) {
  13461. if (team1[i] != team2[i]) {
  13462. return false;
  13463. }
  13464. }
  13465. return true;
  13466. }
  13467. return false;
  13468. }
  13469.  
  13470. function saveProgress() {
  13471. let saveProgressCall = {
  13472. calls: [{
  13473. name: "dungeonSaveProgress",
  13474. args: {},
  13475. ident: "body"
  13476. }]
  13477. }
  13478. send(JSON.stringify(saveProgressCall), resultEndBattle);
  13479. }
  13480.  
  13481.  
  13482. /** Выводит статистику прохождения подземелья */
  13483. function showStats() {
  13484. let activity = dungeonActivity - startDungeonActivity;
  13485. let workTime = clone(timeDungeon);
  13486. workTime.all = new Date().getTime() - workTime.all;
  13487. for (let i in workTime) {
  13488. workTime[i] = (workTime[i] / 1000).round(0);
  13489. }
  13490. countTeam.sort(function(a, b) {
  13491. return b.count - a.count;
  13492. });
  13493. console.log(titansStates);
  13494. console.log("Собрано титанита: ", activity);
  13495. console.log("Скорость сбора: " + (3600 * activity / workTime.all).round(0) + " титанита/час");
  13496. console.log("Время раскопок: ");
  13497. for (let i in workTime) {
  13498. let timeNow = workTime[i];
  13499. console.log(i + ": ", (timeNow / 3600).round(0) + " ч. " + (timeNow % 3600 / 60).round(0) + " мин. " + timeNow % 60 + " сек.");
  13500. }
  13501. console.log("Частота использования команд: ");
  13502. for (let i in countTeam) {
  13503. let teams = countTeam[i];
  13504. console.log(teams.team + ": ", teams.count);
  13505. }
  13506. }
  13507.  
  13508. /** Заканчиваем копать подземелье */
  13509. function endDungeon(reason, info) {
  13510. if (!end) {
  13511. end = true;
  13512. console.log(reason, info);
  13513. showStats();
  13514. if (info == 'break') {
  13515. setProgress('Dungeon stoped: Титанит ' + dungeonActivity + '/' + maxDungeonActivity +
  13516. "\r\nПотеряна связь с сервером игры!", false, hideProgress);
  13517. } else {
  13518. setProgress('Dungeon completed: Титанит ' + dungeonActivity + '/' + maxDungeonActivity, false, hideProgress);
  13519. }
  13520. setTimeout(cheats.refreshGame, 1000);
  13521. resolve();
  13522. }
  13523. }
  13524. }
  13525.  
  13526. //дарим подарки участникам других гильдий не выходя из своей гильдии
  13527. function NewYearGift_Clan() {
  13528. console.log('NewYearGift_Clan called...');
  13529. const userID = getInput('userID');
  13530. const AmontID = getInput('AmontID');
  13531. const GiftNum = getInput('GiftNum');
  13532.  
  13533. const data = {
  13534. "calls": [{
  13535. "name": "newYearGiftSend",
  13536. "args": {
  13537. "userId": userID,
  13538. "amount": AmontID,
  13539. "giftNum": GiftNum,
  13540. "users": {
  13541. [userID]: AmontID
  13542. }
  13543. },
  13544. "ident": "body"
  13545. }
  13546. ]
  13547. }
  13548.  
  13549. const dataJson = JSON.stringify(data);
  13550.  
  13551. SendRequest(dataJson, e => {
  13552. let userInfo = e.results[0].result.response;
  13553. console.log(userInfo);
  13554. });
  13555. setProgress(I18N('SEND_GIFT'), true);
  13556. }
  13557. })();
  13558.  
  13559. /**
  13560. * TODO:
  13561. * Получение всех уровней при сборе всех наград (квест на титанит и на энку) +-
  13562. * Добивание на арене титанов
  13563. * Закрытие окошек по Esc +-
  13564. * Починить работу скрипта на уровне команды ниже 10 +-
  13565. * Написать номальную синхронизацию
  13566. * Добавить дополнительные настройки автопокупки в "Тайном богатстве"
  13567. */