HeroWarsHelper

Автоматизация действий для игры Хроники Хаоса

当前为 2023-03-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @namespace HeroWarsHelper
  5. // @version 2.044
  6. // @description Автоматизация действий для игры Хроники Хаоса
  7. // @description:en Automation of actions for the game Hero Wars
  8. // @author ZingerY
  9. // @homepage http://ilovemycomp.narod.ru/HeroWarsHelper.user.js
  10. // @icon http://ilovemycomp.narod.ru/VaultBoyIco16.ico
  11. // @icon64 http://ilovemycomp.narod.ru/VaultBoyIco64.png
  12. // @encoding utf-8
  13. // @include https://*.nextersglobal.com/*
  14. // @include https://*.hero-wars*.com/*
  15. // @match https://www.solfors.com/
  16. // @match https://t.me/s/hw_ru
  17. // @run-at document-start
  18. // ==/UserScript==
  19.  
  20. (function() {
  21. /** Стартуем скрипт */
  22. console.log('Start ' + GM_info.script.name + ', v' + GM_info.script.version);
  23. /** Информация о скрипте */
  24. const scriptInfo = (({name, version, author, homepage, lastModified}, updateUrl, source) =>
  25. ({name, version, author, homepage, lastModified, updateUrl, source}))
  26. (GM_info.script, GM_info.scriptUpdateURL, arguments.callee.toString());
  27. /** Если находимся на странице подарков, то собираем и отправляем их на сервер */
  28. if (['www.solfors.com', 't.me'].includes(location.host)) {
  29. setTimeout(sendCodes, 2000);
  30. return;
  31. }
  32. /** Загружены ли данные игры */
  33. let isLoadGame = false;
  34. /** Заголовки последнего запроса */
  35. let lastHeaders = {};
  36. /** Информация об отправленных подарках */
  37. let freebieCheckInfo = null;
  38. /** Данные пользователя */
  39. let userInfo;
  40. /** Оригинальные методы для работы с AJAX */
  41. const original = {
  42. open: XMLHttpRequest.prototype.open,
  43. send: XMLHttpRequest.prototype.send,
  44. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  45. };
  46. /** Декодер для перобразования байтовых данных в JSON строку */
  47. const decoder = new TextDecoder("utf-8");
  48. /** Хранит историю запросов */
  49. let requestHistory = {};
  50. /** Была ли взломана подписка deprecated */
  51. let isHackSubscribe = false;
  52. /** URL для запросов к API */
  53. let apiUrl = '';
  54. /** Идетификатор социальной сети deprecated */
  55. let sNetwork = '';
  56. /** Идетификаторы подписки для соц сетей deprecated */
  57. const socials = {
  58. vk: 1, // vk.com
  59. ok: 2, // ok.ru
  60. mm: 3, // my.mail.ru
  61. mg: 5, // store.my.games
  62. fb: 4, // apps.facebook.com
  63. wb: 6, // hero-wars.com
  64. }
  65.  
  66. /** Подключение к коду игры */
  67. this.cheats = new hackGame();
  68. /** Функция расчета результатов боя */
  69. this.BattleCalc = cheats.BattleCalc;
  70. /** Отправка запроса доступная через консоль */
  71. this.SendRequest = send;
  72. /**
  73. * Короткий асинхронный запрос
  74. * Пример использования (возвращает информацию о персонаже):
  75. * const userInfo = await Send('{"calls":[{"name":"userGetInfo","args":{},"ident":"body"}]}')
  76. */
  77. this.Send = function (json, pr) {
  78. return new Promise((resolve, reject) => {
  79. try {
  80. send(json, resolve, pr);
  81. } catch (e) {
  82. reject(e);
  83. }
  84. })
  85. }
  86.  
  87. /** Чекбоксы */
  88. const checkboxes = {
  89. passBattle: {
  90. label: 'Пропуск боев',
  91. cbox: null,
  92. title: 'Пропуск боев в запределье и арене титанов, автопропуск в башне и кампании',
  93. default: false
  94. },
  95. endlessCards: {
  96. label: 'Бесконечные карты',
  97. cbox: null,
  98. title: 'Бесконечные карты предсказаний',
  99. default: true
  100. },
  101. sendExpedition: {
  102. label: 'АвтоЭкспедиции',
  103. cbox: null,
  104. title: 'Автоотправка экспедиций',
  105. default: true
  106. },
  107. cancelBattle: {
  108. label: 'Отмена боя',
  109. cbox: null,
  110. title: 'Возможность отмены боя на ВГ',
  111. default: false
  112. },
  113. getAutoGifts: {
  114. label: 'Подарки',
  115. cbox: null,
  116. title: 'Собирать подарки автоматически',
  117. default: true
  118. },
  119. preCalcBattle: {
  120. label: 'Прерасчет боя',
  121. cbox: null,
  122. title: 'Предварительный расчет боя',
  123. default: false
  124. },
  125. countControl: {
  126. label: 'Контроль кол-ва',
  127. cbox: null,
  128. title: 'Возможность указывать колличество открываемых "лутбоксов"',
  129. default: true
  130. },
  131. repeatMission: {
  132. label: 'Повтор в компании',
  133. cbox: null,
  134. title: 'Автоповтор боев в кампании',
  135. default: false
  136. },
  137. noOfferDonat: {
  138. label: 'Отключить донат',
  139. cbox: null,
  140. title: 'Убирает все предложения доната',
  141. default: false
  142. },
  143. getAnswer: {
  144. label: 'АвтоВикторина',
  145. cbox: null,
  146. title: 'Автоматическое получение возможно правильных ответов на вопросы викторины',
  147. default: false
  148. }
  149. };
  150. /** Получить состояние чекбокса */
  151. function isChecked(checkBox) {
  152. return checkboxes[checkBox].cbox?.checked;
  153. }
  154. /** Поля ввода */
  155. const inputs = {
  156. countTitanit: {
  157. input: null,
  158. title: 'Сколько фармим титанита',
  159. default: 150,
  160. },
  161. speedBattle: {
  162. input: null,
  163. title: 'Множитель ускорения боя',
  164. default: 5,
  165. },
  166. countTestBattle: {
  167. input: null,
  168. title: 'Количество тестовых боев',
  169. default: 10,
  170. },
  171. countAutoBattle: {
  172. input: null,
  173. title: 'Количество попыток автобоев',
  174. default: 10,
  175. }
  176. }
  177. /** Поплучить данные поля ввода */
  178. function getInput(inputName) {
  179. return inputs[inputName].input.value;
  180. }
  181. /** Список кнопочек */
  182. const buttons = {
  183. getOutland: {
  184. name: 'Запределье',
  185. title: 'Собрать Запределье',
  186. func: function () {
  187. confShow('Запустить скрипт Запределье?', getOutland);
  188. },
  189. },
  190. testTitanArena: {
  191. name: 'Турнир Стихий',
  192. title: 'Автопрохождение Турнира Стихий',
  193. func: function () {
  194. confShow('Запустить скрипт Турнир Стихий?', testTitanArena);
  195. },
  196. },
  197. testDungeon: {
  198. name: 'Подземелье',
  199. title: 'Автопрохождение подземелья',
  200. func: function () {
  201. confShow('Запустить скрипт Подземелье?', () => {
  202. let titanit = getInput('countTitanit');
  203. testDungeon(titanit);
  204. });
  205. },
  206. },
  207. testTower: {
  208. name: 'Башня',
  209. title: 'Автопрохождение башни',
  210. func: function () {
  211. confShow('Запустить скрипт Башня?', testTower);
  212. },
  213. },
  214. sendExpedition: {
  215. name: 'Экспедиции',
  216. title: 'Отправка и сбор экспедиций',
  217. func: function () {
  218. confShow('Запустить скрипт Экспедиции?', checkExpedition);
  219. },
  220. },
  221. newDay: {
  222. name: 'Синхронизация',
  223. title: 'Частичная синхонизация данных игры без перезагрузки сатраницы',
  224. func: function () {
  225. confShow('Запустить скрипт Синхронизация?', cheats.refreshGame);
  226. },
  227. },
  228. bossRatingEvent: {
  229. name: 'Архидемон',
  230. title: 'Набивает килы и собирает награду',
  231. func: function () {
  232. confShow('Запустить скрипт Архидемон?', bossRatingEvent);
  233. },
  234. },
  235. offerFarmAllReward: {
  236. name: 'Пасхалки',
  237. title: 'Собрать все пасхалки или награды',
  238. func: function () {
  239. confShow('Запустить скрипт Пасхалки?', offerFarmAllReward);
  240. },
  241. },
  242. questAllFarm: {
  243. name: 'Награды',
  244. title: 'Собрать все награды за задания',
  245. func: function () {
  246. confShow('Запустить скрипт Награды?', questAllFarm);
  247. },
  248. },
  249. mailGetAll: {
  250. name: 'Почта',
  251. title: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  252. func: function () {
  253. confShow('Запустить скрипт Почта?', mailGetAll);
  254. },
  255. },
  256. testRaidNodes: {
  257. name: 'Прислужники',
  258. title: 'Атакует прислужников сохраннеными пачками',
  259. func: function () {
  260. confShow('Запустить скрипт Прислужники?', testRaidNodes);
  261. },
  262. },
  263. goToSanctuary: {
  264. name: 'Святилище',
  265. title: 'Быстрый переход к Святилищу',
  266. func: cheats.goSanctuary,
  267. },
  268. goToClanWar: {
  269. name: 'Война гильдий',
  270. title: 'Быстрый переход к Войне гильдий',
  271. func: cheats.goClanWar,
  272. },
  273. }
  274. /** Вывести кнопочки */
  275. function addControlButtons() {
  276. for (let name in buttons) {
  277. button = buttons[name];
  278. scriptMenu.addButton(button.name, button.func, button.title);
  279. }
  280. }
  281. /** Добавляет ссылки */
  282. function addBottomUrls() {
  283. scriptMenu.addHeader('<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank">tg</a> <a href="https://vk.com/invite/YNPxKGX" target="_blank">vk</a>');
  284. }
  285. /** Остановить повтор миссии */
  286. let isStopSendMission = false;
  287. /** Идет повтор миссии */
  288. let isSendsMission = false;
  289. /** Данные о прошедшей мисии */
  290. let lastMissionStart = {}
  291.  
  292. /** Данные о прошедшей атаке на босса */
  293. let lastBossBattle = {}
  294. /** Данные для расчете последнего боя с боссом */
  295. let lastBossBattleInfo = null;
  296. /** Возможность отменить бой в Астгарде */
  297. let isCancalBossBattle = true;
  298. /** Данные о прошедшей битве */
  299. let lastBattleArg = {}
  300. /** Имя функции начала боя */
  301. let nameFuncStartBattle = '';
  302. /** Имя функции конца боя */
  303. let nameFuncEndBattle = '';
  304. /** Данные для расчете последнего боя */
  305. let lastBattleInfo = null;
  306. /** Возможность отменить бой */
  307. let isCancalBattle = true;
  308.  
  309. /** Идетификатор последней открытой матрешки */
  310. let lastRussianDollId = null;
  311. /** Отменить обучающее руководство */
  312. this.isCanceledTutorial = false;
  313.  
  314. /** Данные последнего вопроса викторины */
  315. let lastQuestion = null;
  316. /** Ответ на последний вопрос викторины */
  317. let lastAnswer = null;
  318. /** Флаг открытия сфер артефактов титанов */
  319. let titanArtifactChestOpen = false;
  320.  
  321. /**
  322. * Копирует тест в буфер обмена
  323. * @param {*} text копируемый текст
  324. */
  325. function copyText(text) {
  326. let copyTextarea = document.createElement("textarea");
  327. copyTextarea.style.opacity = "0";
  328. copyTextarea.textContent = text;
  329. document.body.appendChild(copyTextarea);
  330. copyTextarea.select();
  331. document.execCommand("copy");
  332. document.body.removeChild(copyTextarea);
  333. delete copyTextarea;
  334. }
  335. /** Возвращает историю запросов */
  336. this.getRequestHistory = function() {
  337. return requestHistory;
  338. }
  339. /** Гененирует случайное целое число от min до max */
  340. const random = function (min, max) {
  341. return Math.floor(Math.random() * (max - min + 1) + min);
  342. }
  343. /** Очистка истоии запросов */
  344. setInterval(function () {
  345. let now = Date.now();
  346. for (let i in requestHistory) {
  347. if (now - i > 300000) {
  348. delete requestHistory[i];
  349. }
  350. }
  351. }, 300000);
  352. /** Событие загрузки DOM дерева страницы */
  353. document.addEventListener("DOMContentLoaded", () => {
  354. createInterface();
  355. });
  356. /** Сбор и отправка кодов подарков */
  357. function sendCodes() {
  358. let codes = [], count = 0;
  359. if (!localStorage['giftSendIds']) {
  360. localStorage['giftSendIds'] = '';
  361. }
  362. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  363. let url = e?.href;
  364. if (!url) return;
  365. url = new URL(url);
  366. let giftId = url.searchParams.get('gift_id');
  367. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  368. localStorage['giftSendIds'] += ';' + giftId;
  369. codes.push(giftId);
  370. count++;
  371. });
  372.  
  373. if (codes.length) {
  374. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  375. sendGiftsCodes(codes);
  376. }
  377.  
  378. if (!count) {
  379. setTimeout(sendCodes, 2000);
  380. }
  381. }
  382. /** Проверка отправленных кодов */
  383. function checkSendGifts() {
  384. if (!freebieCheckInfo) {
  385. return;
  386. }
  387.  
  388. let giftId = freebieCheckInfo.args.giftId;
  389. let valName = 'giftSendIds_' + userInfo.id;
  390. localStorage[valName] = localStorage[valName] ?? '';
  391. if (!localStorage[valName].includes(giftId)) {
  392. localStorage[valName] += ';' + giftId;
  393. sendGiftsCodes([giftId]);
  394. }
  395. }
  396. /** Отправка кодов */
  397. function sendGiftsCodes(codes) {
  398. fetch('https://zingery.ru/heroes/setGifts.php', {
  399. method: 'POST',
  400. body: JSON.stringify(codes)
  401. }).then(
  402. response => response.json()
  403. ).then(
  404. data => {
  405. if (data.result) {
  406. console.log('Подарки отправлены!');
  407. }
  408. }
  409. )
  410. }
  411. /** Возвращает объект если переданный парамет строка */
  412. function getJson(result) {
  413. if (typeof result == 'string') {
  414. result = JSON.parse(result);
  415. }
  416. if (result?.error) {
  417. console.warn(result.error);
  418. return false;
  419. }
  420. return result;
  421. }
  422. /** Отображает диалоговое окно */
  423. function confShow(message, yesCallback, noCallback) {
  424. let buts = [];
  425. message = message || "Вы действительно хотите это сделать?";
  426. noCallback = noCallback || (() => {});
  427. if (yesCallback) {
  428. buts = [
  429. {msg: 'Запускай!', result: true},
  430. {msg: 'Отмена', result: false},
  431. ]
  432. } else {
  433. yesCallback = () => {};
  434. buts = [
  435. {msg: 'Ок', result: true},
  436. ];
  437. }
  438. popup.confirm(message, buts).then((e) => {
  439. if (e) {
  440. yesCallback();
  441. } else {
  442. noCallback();
  443. }
  444. });
  445. }
  446. /** Переопределяем/проксируем метод создания Ajax запроса */
  447. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  448. this.uniqid = Date.now();
  449. this.errorRequest = false;
  450. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  451. if (!apiUrl) {
  452. apiUrl = url;
  453. socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  454. sNetwork = socialInfo ? socialInfo[1] : 'vk';
  455. }
  456. requestHistory[this.uniqid] = {
  457. method,
  458. url,
  459. error: [],
  460. headers: {},
  461. request: null,
  462. response: null,
  463. signature: [],
  464. calls: {},
  465. };
  466. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  467. this.errorRequest = true;
  468. }
  469. return original.open.call(this, method, url, async, user, password);
  470. };
  471. /** Переопределяем/проксируем метод установки заголовков для AJAX запроса */
  472. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  473. if (this.uniqid in requestHistory) {
  474. requestHistory[this.uniqid].headers[name] = value;
  475. } else {
  476. check = true;
  477. }
  478.  
  479. if (name == 'X-Auth-Signature') {
  480. requestHistory[this.uniqid].signature.push(value);
  481. if (!check) {
  482. return;
  483. }
  484. }
  485.  
  486. return original.setRequestHeader.call(this, name, value);
  487. };
  488. /** Переопределяем/проксируем метод отправки AJAX запроса */
  489. XMLHttpRequest.prototype.send = async function (sourceData) {
  490. if (this.uniqid in requestHistory) {
  491. let tempData = null;
  492. if (getClass(sourceData) == "ArrayBuffer") {
  493. tempData = decoder.decode(sourceData);
  494. } else {
  495. tempData = sourceData;
  496. }
  497. requestHistory[this.uniqid].request = tempData;
  498. let headers = requestHistory[this.uniqid].headers;
  499. lastHeaders = Object.assign({}, headers);
  500. /** Событие загрузки игры */
  501. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  502. isLoadGame = true;
  503. if (isChecked('sendExpedition')) {
  504. checkExpedition();
  505. }
  506. if (isChecked('getAutoGifts')) {
  507. checkSendGifts();
  508. getAutoGifts();
  509. }
  510. cheats.activateHacks();
  511. addControlButtons();
  512. addBottomUrls();
  513. }
  514. /** Обработка данных исходящего запроса */
  515. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  516. /** Обработка данных входящего запроса */
  517. const oldReady = this.onreadystatechange;
  518. this.onreadystatechange = function (e) {
  519. if(this.readyState == 4 && this.status == 200) {
  520. isTextResponse = this.responseType != "json";
  521. let response = isTextResponse ? this.responseText : this.response;
  522. requestHistory[this.uniqid].response = response;
  523. /** Заменна данных входящего запроса */
  524. if (isTextResponse) {
  525. checkChangeResponse.call(this, response);
  526. }
  527. /** Функция запускаемая после выполения запроса */
  528. if (typeof this.onReadySuccess == 'function') {
  529. setTimeout(this.onReadySuccess, 500);
  530. }
  531. }
  532. if (oldReady) {
  533. return oldReady.apply(this, arguments);
  534. }
  535. }
  536. }
  537. if (this.errorRequest) {
  538. const oldReady = this.onreadystatechange;
  539. this.onreadystatechange = function () {
  540. Object.defineProperty(this, 'status', {
  541. writable: true
  542. });
  543. this.status = 200;
  544. Object.defineProperty(this, 'readyState', {
  545. writable: true
  546. });
  547. this.readyState = 4;
  548. Object.defineProperty(this, 'responseText', {
  549. writable: true
  550. });
  551. this.responseText = JSON.stringify({
  552. "result": true
  553. });
  554. return oldReady.apply(this, arguments);
  555. }
  556. this.onreadystatechange();
  557. } else {
  558. return original.send.call(this, sourceData);
  559. }
  560. };
  561. /** Обработка и подмена исходящих данных */
  562. async function checkChangeSend(sourceData, tempData) {
  563. try {
  564. /** Функция заменяющая данные боя на неверные для отмены боя */
  565. const fixBattle = function (heroes) {
  566. for (const ids in heroes) {
  567. hero = heroes[ids];
  568. hero.energy = random(1, 999);
  569. if (hero.hp > 0) {
  570. hero.hp = random(1, hero.hp);
  571. }
  572. }
  573. }
  574. /** Диалоговое окно */
  575. const showMsg = async function (msg, ansF, ansS) {
  576. if (typeof popup == 'object') {
  577. return await popup.confirm(msg, [
  578. {msg: ansF, result: false},
  579. {msg: ansS, result: true},
  580. ]);
  581. } else {
  582. return !confirm(msg + "\n" + ansF + " (Ок)\n" + ansS + " (Отмена)");
  583. }
  584. }
  585. /** Диалоговое окно */
  586. const showMsgs = async function (msg, ansF, ansS, ansT) {
  587. return await popup.confirm(msg, [
  588. {msg: ansF, result: 0},
  589. {msg: ansS, result: 1},
  590. {msg: ansT, result: 2},
  591. ]);
  592. }
  593.  
  594. let changeRequest = false;
  595. testData = JSON.parse(tempData);
  596. for (const call of testData.calls) {
  597. if (!titanArtifactChestOpen) {
  598. requestHistory[this.uniqid].calls[call.name] = call.ident;
  599. }
  600. /** Отмена боя в приключениях, на ВГ и с прислужниками Асгарда */
  601. if ((call.name == 'adventure_endBattle' ||
  602. call.name == 'adventureSolo_endBattle' ||
  603. call.name == 'clanWarEndBattle' && isChecked('cancelBattle') ||
  604. call.name == 'crossClanWar_endBattle' && isChecked('cancelBattle') ||
  605. call.name == 'brawl_endBattle' ||
  606. call.name == 'towerEndBattle' ||
  607. call.name == 'clanRaid_endNodeBattle') &&
  608. isCancalBattle) {
  609. nameFuncEndBattle = call.name;
  610. if (!call.args.result.win) {
  611. let resultPopup = false;
  612. if (call.name == 'crossClanWar_endBattle' ||
  613. call.name == 'clanWarEndBattle' ||
  614. call.name == 'adventure_endBattle' ||
  615. call.name == 'adventureSolo_endBattle') {
  616. resultPopup = await showMsgs('Вы потерпели поражение!', 'Хорошо', 'Отменить', 'Авто');
  617. } else {
  618. resultPopup = await showMsg('Вы потерпели поражение!', 'Хорошо', 'Отменить');
  619. }
  620. if (resultPopup) {
  621. fixBattle(call.args.progress[0].attackers.heroes);
  622. fixBattle(call.args.progress[0].defenders.heroes);
  623. changeRequest = true;
  624. if (resultPopup > 1) {
  625. this.onReadySuccess = testAutoBattle;
  626. // setTimeout(bossBattle, 1000);
  627. }
  628. }
  629. }
  630. }
  631. /** Отмена боя в Асгарде */
  632. if (call.name == 'clanRaid_endBossBattle' &&
  633. isCancalBossBattle) {
  634. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  635. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  636. let resultPopup = await showMsgs(
  637. 'Вы нанесли ' + sumDamage.toLocaleString() + ' урона.',
  638. 'Хорошо', 'Отменить', 'Авто')
  639. if (resultPopup) {
  640. fixBattle(call.args.progress[0].attackers.heroes);
  641. fixBattle(call.args.progress[0].defenders.heroes);
  642. changeRequest = true;
  643. if (resultPopup > 1) {
  644. this.onReadySuccess = testBossBattle;
  645. // setTimeout(bossBattle, 1000);
  646. }
  647. }
  648. }
  649. /** Сохраняем пачку для атаки босса Асгарда */
  650. if (call.name == 'clanRaid_startBossBattle') {
  651. lastBossBattle = call.args;
  652. }
  653. /** Сохранение запроса начала последнего боя */
  654. if (call.name == 'clanWarAttack' ||
  655. call.name == 'crossClanWar_startBattle' ||
  656. call.name == 'adventure_turnStartBattle') {
  657. nameFuncStartBattle = call.name;
  658. lastBattleArg = call.args;
  659. }
  660. /** Отключить трату карт предсказаний */
  661. if (call.name == 'dungeonEndBattle') {
  662. if (isChecked('endlessCards') && call.args.isRaid) {
  663. delete call.args.isRaid;
  664. changeRequest = true;
  665. }
  666. }
  667. /** Ответ на викторину */
  668. if (call.name == 'quizAnswer') {
  669. /** Автоматически меняет ответ на правильный если он есть */
  670. if (lastAnswer && isChecked('getAnswer')) {
  671. call.args.answerId = lastAnswer;
  672. lastAnswer = null;
  673. changeRequest = true;
  674. }
  675. }
  676. /** Подарки */
  677. if (call.name == 'freebieCheck' && isChecked('getAutoGifts')) {
  678. freebieCheckInfo = call;
  679. }
  680. /** Получение данных миссии для автоповтора */
  681. if (isChecked('repeatMission') &&
  682. call.name == 'missionEnd') {
  683. let missionInfo = {
  684. id: call.args.id,
  685. result: call.args.result,
  686. heroes: call.args.progress[0].attackers.heroes,
  687. count: 0,
  688. }
  689. setTimeout(async () => {
  690. if (!isSendsMission && await popup.confirm('Повторить миссию?', [
  691. {msg: 'Повторить', result: true},
  692. {msg: 'Нет', result: false},
  693. ])) {
  694. isStopSendMission = false;
  695. isSendsMission = true;
  696. sendsMission(missionInfo);
  697. }
  698. }, 0);
  699. }
  700. /** Получение данных миссии */
  701. if (call.name == 'missionStart') {
  702. lastMissionStart = call.args;
  703. }
  704. /** Указать колличество для сфер титанов и яиц петов */
  705. if (isChecked('countControl') &&
  706. (call.name == 'pet_chestOpen' ||
  707. call.name == 'titanUseSummonCircle') &&
  708. call.args.amount > 1) {
  709. const result = await popup.confirm('Указать колличество:', [
  710. {msg: 'Открыть', isInput: true, default: call.args.amount},
  711. ]);
  712. if (result) {
  713. call.args.amount = result;
  714. changeRequest = true;
  715. }
  716. }
  717. /** Указать колличество для сфер артефактов титанов */
  718. if (isChecked('countControl') &&
  719. call.name == 'titanArtifactChestOpen' &&
  720. call.args.amount > 1 &&
  721. !changeRequest) {
  722. let result = await popup.confirm('Указать колличество:', [
  723. { msg: 'Открыть', isInput: true, default: call.args.amount },
  724. ]);
  725. if (result) {
  726. let sphere = result < 10 ? 1 : 10;
  727.  
  728. call.args.amount = sphere;
  729. result -= sphere;
  730.  
  731. for (let count = result; count > 0; count -= sphere) {
  732. if (count < 10) sphere = 1;
  733. const ident = "titanArtifactChestOpen_" + count;
  734. testData.calls.push({
  735. name: "titanArtifactChestOpen",
  736. args: {
  737. amount: sphere,
  738. free: true,
  739. },
  740. ident: ident
  741. });
  742. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  743. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  744. }
  745. requestHistory[this.uniqid].calls[call.name].push(ident);
  746. }
  747.  
  748. titanArtifactChestOpen = true;
  749. changeRequest = true;
  750. }
  751. }
  752. /** Указать колличество для артефактных сундуков */
  753. if (isChecked('countControl') &&
  754. call.name == 'artifactChestOpen' &&
  755. call.args.amount > 1) {
  756. const result = await popup.confirm('Указать колличество:', [
  757. { msg: 'Открыть 1', result: 1 },
  758. { msg: 'Открыть 10', result: 10 },
  759. ]);
  760. if (result) {
  761. call.args.amount = result;
  762. changeRequest = true;
  763. }
  764. }
  765. if (call.name == 'consumableUseLootBox') {
  766. lastRussianDollId = call.args.libId;
  767. /** Указать колличество для золотых шкатулок */
  768. if (isChecked('countControl') &&
  769. call.args.libId == 148 &&
  770. call.args.amount > 1) {
  771. const result = await popup.confirm('Указать колличество:', [
  772. {msg: 'Открыть', isInput: true, default: call.args.amount},
  773. ]);
  774. call.args.amount = result;
  775. changeRequest = true;
  776. }
  777. }
  778. }
  779.  
  780. let headers = requestHistory[this.uniqid].headers;
  781. if (changeRequest) {
  782. sourceData = JSON.stringify(testData);
  783. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  784. }
  785.  
  786. let signature = headers['X-Auth-Signature'];
  787. if (signature) {
  788. this.setRequestHeader('X-Auth-Signature', signature, true);
  789. }
  790. } catch (err) {
  791. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  792. }
  793. return sourceData;
  794. }
  795. /** Обработка и подмена входящих данных */
  796. async function checkChangeResponse(response) {
  797. try {
  798. isChange = false;
  799. let nowTime = Math.round(Date.now() / 1000);
  800. callsIdent = requestHistory[this.uniqid].calls;
  801. respond = JSON.parse(response);
  802. /** Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации) */
  803. if (respond.error) {
  804. isChange = true;
  805. console.error(respond.error);
  806. delete respond.error;
  807. respond.results = [];
  808. }
  809. let mainReward = null;
  810. const allReward = {};
  811. for (const call of respond.results) {
  812. /** Типа активация Покровительства Валькирий на клиенте */
  813. // if (call.ident == callsIdent['subscriptionGetInfo'] &&
  814. // (call.result.response.subscription?.status != 1 || !call.result.response.subscription)) {
  815. // if (!call.result.response.subscription) {
  816. // call.result.response.subscription = {}
  817. // }
  818. // callRes = call.result.response.subscription;
  819. // /** Устанавливем время окончания подписки на +7 от подписки */
  820. // callRes.endTime = nowTime + 1001 * 24 * 60 * 60;
  821. // /** Статус подписки */
  822. // callRes.status = 1;
  823. // /** Тип (платформа) */
  824. // callRes.type = socials[sNetwork];
  825. // isHackSubscribe = true;
  826. // isChange = true;
  827. // }
  828. /** Фикс экспедиций */
  829. // if (call.ident == callsIdent['expeditionGet'] && isHackSubscribe) {
  830. // expeditions = call.result.response;
  831. // for (const n in expeditions) {
  832. // exped = expeditions[n];
  833. // if (exped.slotId == 6) {
  834. // exped.status = 3;
  835. // isChange = true;
  836. // }
  837. // }
  838. // }
  839. /** Бесконечные карты предсказаний */
  840. if (call.ident == callsIdent['inventoryGet']) {
  841. consumable = call.result.response.consumable;
  842. consumable[81] = 999;
  843. isChange = true;
  844. }
  845. /** Потасовка */
  846. if (call.ident == callsIdent['brawl_getInfo']) {
  847. brawl = call.result.response;
  848. if (brawl) {
  849. brawl.boughtEndlessLivesToday = 1;
  850. isChange = true;
  851. }
  852. }
  853. /** Скрываем предложения доната */
  854. if (isChecked('noOfferDonat') && call.ident == callsIdent['billingGetAll']) {
  855. const billings = call.result.response?.billings;
  856. const bundle = call.result.response?.bundle;
  857. if (billings && bundle) {
  858. call.result.response.billings = [];
  859. call.result.response.bundle = [];
  860. isChange = true;
  861. }
  862. }
  863. /** Скрываем предложения доната */
  864. if (isChecked('noOfferDonat') && call.ident == callsIdent['offerGetAll']) {
  865. const offers = call.result.response;
  866. if (offers) {
  867. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type));
  868. isChange = true;
  869. }
  870. }
  871. /** Копирует вопрос викторины в буфер обмена и получает на него ответ если есть */
  872. if (call.ident == callsIdent['quizGetNewQuestion']) {
  873. let quest = call.result.response;
  874. console.log(quest.question);
  875. copyText(quest.question);
  876. setProgress('Вопрос скопирован в буфер обмена', true);
  877. lastQuestion = quest;
  878. if (isChecked('getAnswer')) {
  879. const answer = await getAnswer(lastQuestion);
  880. if (answer) {
  881. lastAnswer = answer;
  882. console.log(answer);
  883. setProgress('Ответ известен: ' + answer, true);
  884. } else {
  885. setProgress('ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН', true);
  886. }
  887. }
  888. }
  889. /** Отправляет вопрос с ответом в базу данных */
  890. if (call.ident == callsIdent['quizAnswer']) {
  891. const answer = call.result.response;
  892. if (lastQuestion) {
  893. const answerInfo = {
  894. answer,
  895. question: lastQuestion
  896. }
  897. lastQuestion = null;
  898. setTimeout(sendAnswerInfo, 0, answerInfo);
  899. }
  900. }
  901. /** Получить даныне пользователя */
  902. if (call.ident == callsIdent['userGetInfo']) {
  903. let user = call.result.response;
  904. userInfo = Object.assign({}, user);
  905. delete userInfo.refillable;
  906. }
  907. /** Начало боя для прерасчета */
  908. if ((call.ident == callsIdent['clanWarAttack'] ||
  909. call.ident == callsIdent['crossClanWar_startBattle'] ||
  910. call.ident == callsIdent['battleGetReplay'] ||
  911. call.ident == callsIdent['adventure_turnStartBattle']) &&
  912. isChecked('preCalcBattle')) {
  913. setProgress('Идет прерасчет боя');
  914. let battle = call.result.response.battle || call.result.response.replay;
  915. lastBattleInfo = battle;
  916. console.log(battle.type);
  917. function getBattleInfo(battle, isRandSeed) {
  918. return new Promise(function (resolve) {
  919. if (isRandSeed) {
  920. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  921. }
  922. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  923. });
  924. }
  925. let actions = [getBattleInfo(battle, false)]
  926. const countTestBattle = getInput('countTestBattle');
  927. for (let i = 0; i < countTestBattle; i++) {
  928. actions.push(getBattleInfo(battle, true));
  929. }
  930. Promise.all(actions)
  931. .then(e => {
  932. let firstBattle = e.shift();
  933. let countWin = e.reduce((w, s) => w + s);
  934. setProgress((firstBattle ? 'Победа' : 'Поражение') + ' ' + countWin + '/' + e.length + ' X', false, hideProgress)
  935. });
  936. }
  937. /** Начало боя с боссом Асгарда */
  938. if (call.ident == callsIdent['clanRaid_startBossBattle'] && isChecked('preCalcBattle')) {
  939. lastBossBattleInfo = call.result.response.battle;
  940. }
  941. /** Отмена туториала */
  942. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  943. let chains = call.result.response.chains;
  944. for (let n in chains) {
  945. chains[n] = 9999;
  946. }
  947. isChange = true;
  948. }
  949. /** Открытие сфер артефактов титанов */
  950. if (titanArtifactChestOpen &&
  951. (call.ident == callsIdent['titanArtifactChestOpen'] ||
  952. (callsIdent['titanArtifactChestOpen'] && callsIdent['titanArtifactChestOpen'].includes(call.ident)))) {
  953. let reward = call.result.response.reward;
  954.  
  955. reward.forEach(e => {
  956. for (let f in e) {
  957. if (!allReward[f]) {
  958. allReward[f] = {};
  959. }
  960. for (let o in e[f]) {
  961. if (!allReward[f][o]) {
  962. allReward[f][o] = e[f][o];
  963. } else {
  964. allReward[f][o] += e[f][o];
  965. }
  966. }
  967. }
  968. });
  969.  
  970. if (!call.ident.includes('titanArtifactChestOpen')) {
  971. mainReward = call.result.response;
  972. }
  973. }
  974. /** АвтоПовтор открытия матрешек */
  975. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  976. let lootBox = call.result.response;
  977. let newCount = 0;
  978. for (let n of lootBox) {
  979. if (n?.consumable && n.consumable[lastRussianDollId]) {
  980. newCount += n.consumable[lastRussianDollId]
  981. }
  982. }
  983. if (newCount && await popup.confirm('Открыть ' + newCount + ' матрешек рекурсивно?', [
  984. {msg: 'Повторить', result: true},
  985. {msg: 'Нет', result: false},
  986. ])) {
  987. openRussianDoll(lastRussianDollId, newCount);
  988. }
  989. }
  990. }
  991.  
  992. if (mainReward && titanArtifactChestOpen) {
  993. console.log(allReward);
  994. mainReward.reward = [allReward];
  995. titanArtifactChestOpen = false;
  996. isChange = true;
  997. }
  998. } catch(err) {
  999. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  1000. }
  1001.  
  1002. if (isChange) {
  1003. Object.defineProperty(this, 'responseText', {
  1004. writable: true
  1005. });
  1006. this.responseText = JSON.stringify(respond);
  1007. }
  1008. }
  1009.  
  1010. /** Запрос ответа на вопрос */
  1011. async function getAnswer(question) {
  1012. return new Promise((resolve, reject) => {
  1013. fetch('https://zingery.ru/heroes/getAnswer.php', {
  1014. method: 'POST',
  1015. body: JSON.stringify(question)
  1016. }).then(
  1017. response => response.json()
  1018. ).then(
  1019. data => {
  1020. if (data.result) {
  1021. resolve(data.result);
  1022. } else {
  1023. resolve(false);
  1024. }
  1025. }
  1026. ).catch((error) => {
  1027. console.error(error);
  1028. resolve(false);
  1029. });
  1030. })
  1031. }
  1032.  
  1033. /** Отправка вопроса и ответа в базу данных */
  1034. function sendAnswerInfo(answerInfo) {
  1035. fetch('https://zingery.ru/heroes/setAnswer.php', {
  1036. method: 'POST',
  1037. body: JSON.stringify(answerInfo)
  1038. }).then(
  1039. response => response.json()
  1040. ).then(
  1041. data => {
  1042. if (data.result) {
  1043. console.log('Вопрос отправлен');
  1044. }
  1045. }
  1046. )
  1047. }
  1048.  
  1049. /** Возвращает тип боя по типу пресета */
  1050. function getBattleType(strBattleType) {
  1051. switch (strBattleType) {
  1052. case "invasion":
  1053. return "get_invasion";
  1054. case "titan_pvp_manual":
  1055. return "get_titanPvpManual";
  1056. case "titan_pvp":
  1057. return "get_titanPvp";
  1058. case "titan_clan_pvp":
  1059. case "clan_pvp_titan":
  1060. case "clan_global_pvp_titan":
  1061. case "challenge_titan":
  1062. return "get_titanClanPvp";
  1063. case "clan_raid": // Босс асгарда
  1064. case "adventure": // Приключения
  1065. case "clan_global_pvp":
  1066. case "clan_pvp":
  1067. case "challenge":
  1068. case "grand":
  1069. case "arena":
  1070. return "get_clanPvp";
  1071. case "titan_tower":
  1072. return "get_titan";
  1073. case "tower":
  1074. return "get_tower";
  1075. case "pve":
  1076. return "get_pve";
  1077. case "pvp_manual":
  1078. return "get_pvpManual";
  1079. case "pvp":
  1080. return "get_pvp";
  1081. case "core":
  1082. return "get_core";
  1083. default:
  1084. return "get_clanPvp";
  1085. }
  1086. }
  1087. /** Возвращает название класса переданного объекта */
  1088. function getClass(obj) {
  1089. return {}.toString.call(obj).slice(8, -1);
  1090. }
  1091. /** Расчитывает сигнатуру запроса */
  1092. this.getSignature = function(headers, data) {
  1093. let signatureStr = [headers["X-Request-Id"], headers["X-Auth-Token"], headers["X-Auth-Session-Id"], data, 'LIBRARY-VERSION=1'].join(':');
  1094. return md5(signatureStr);
  1095. }
  1096. /** Создает интерфейс */
  1097. function createInterface() {
  1098. scriptMenu.init({
  1099. showMenu: true
  1100. });
  1101. scriptMenu.addHeader(GM_info.script.name);
  1102. scriptMenu.addHeader('v' + GM_info.script.version);
  1103.  
  1104. const details = scriptMenu.addDetails('Настройки');
  1105. for (let name in checkboxes) {
  1106. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, details);
  1107. /** Получаем состояние чекбоксов из localStorage */
  1108. let val = storage.get(name, null);
  1109. if (val != null) {
  1110. checkboxes[name].cbox.checked = val;
  1111. } else {
  1112. storage.set(name, checkboxes[name].default);
  1113. checkboxes[name].cbox.checked = checkboxes[name].default;
  1114. }
  1115. /** Отсеживание события изменения чекбокса для записи в localStorage */
  1116. checkboxes[name].cbox.dataset['name'] = name;
  1117. checkboxes[name].cbox.addEventListener('change', function () {
  1118. storage.set(this.dataset['name'], this.checked);
  1119. })
  1120. }
  1121.  
  1122. const inputDetails = scriptMenu.addDetails('Значения');
  1123. for (let name in inputs) {
  1124. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  1125. /** Получаем состояние inputText из localStorage */
  1126. let val = storage.get(name, null);
  1127. if (val != null) {
  1128. inputs[name].input.value = val;
  1129. } else {
  1130. storage.set(name, inputs[name].default);
  1131. inputs[name].input.value = inputs[name].default;
  1132. }
  1133. /** Отсеживание события изменения поля для записи в localStorage */
  1134. inputs[name].input.dataset['name'] = name;
  1135. inputs[name].input.addEventListener('input', function () {
  1136. storage.set(this.dataset['name'], this.value);
  1137. })
  1138. }
  1139. }
  1140. /** Расчитывает HASH MD5 из строки */
  1141. function md5(r){for(var a=(r,n,t,e,o,u)=>f(c(f(f(n,r),f(e,u)),o),t),n=(r,n,t,e,o,u,f)=>a(n&t|~n&e,r,n,o,u,f),t=(r,n,t,e,o,u,f)=>a(n&e|t&~e,r,n,o,u,f),e=(r,n,t,e,o,u,f)=>a(n^t^e,r,n,o,u,f),o=(r,n,t,e,o,u,f)=>a(t^(n|~e),r,n,o,u,f),f=function(r,n){var t=(65535&r)+(65535&n);return(r>>16)+(n>>16)+(t>>16)<<16|65535&t},c=(r,n)=>r<<n|r>>>32-n,u=Array(r.length>>2),h=0;h<u.length;h++)u[h]=0;for(h=0;h<8*r.length;h+=8)u[h>>5]|=(255&r.charCodeAt(h/8))<<h%32;len=8*r.length,u[len>>5]|=128<<len%32,u[14+(len+64>>>9<<4)]=len;var l=1732584193,i=-271733879,g=-1732584194,v=271733878;for(h=0;h<u.length;h+=16){var A=l,d=i,C=g,m=v;i=o(i=o(i=o(i=o(i=e(i=e(i=e(i=e(i=t(i=t(i=t(i=t(i=n(i=n(i=n(i=n(i,g=n(g,v=n(v,l=n(l,i,g,v,u[h+0],7,-680876936),i,g,u[h+1],12,-389564586),l,i,u[h+2],17,606105819),v,l,u[h+3],22,-1044525330),g=n(g,v=n(v,l=n(l,i,g,v,u[h+4],7,-176418897),i,g,u[h+5],12,1200080426),l,i,u[h+6],17,-1473231341),v,l,u[h+7],22,-45705983),g=n(g,v=n(v,l=n(l,i,g,v,u[h+8],7,1770035416),i,g,u[h+9],12,-1958414417),l,i,u[h+10],17,-42063),v,l,u[h+11],22,-1990404162),g=n(g,v=n(v,l=n(l,i,g,v,u[h+12],7,1804603682),i,g,u[h+13],12,-40341101),l,i,u[h+14],17,-1502002290),v,l,u[h+15],22,1236535329),g=t(g,v=t(v,l=t(l,i,g,v,u[h+1],5,-165796510),i,g,u[h+6],9,-1069501632),l,i,u[h+11],14,643717713),v,l,u[h+0],20,-373897302),g=t(g,v=t(v,l=t(l,i,g,v,u[h+5],5,-701558691),i,g,u[h+10],9,38016083),l,i,u[h+15],14,-660478335),v,l,u[h+4],20,-405537848),g=t(g,v=t(v,l=t(l,i,g,v,u[h+9],5,568446438),i,g,u[h+14],9,-1019803690),l,i,u[h+3],14,-187363961),v,l,u[h+8],20,1163531501),g=t(g,v=t(v,l=t(l,i,g,v,u[h+13],5,-1444681467),i,g,u[h+2],9,-51403784),l,i,u[h+7],14,1735328473),v,l,u[h+12],20,-1926607734),g=e(g,v=e(v,l=e(l,i,g,v,u[h+5],4,-378558),i,g,u[h+8],11,-2022574463),l,i,u[h+11],16,1839030562),v,l,u[h+14],23,-35309556),g=e(g,v=e(v,l=e(l,i,g,v,u[h+1],4,-1530992060),i,g,u[h+4],11,1272893353),l,i,u[h+7],16,-155497632),v,l,u[h+10],23,-1094730640),g=e(g,v=e(v,l=e(l,i,g,v,u[h+13],4,681279174),i,g,u[h+0],11,-358537222),l,i,u[h+3],16,-722521979),v,l,u[h+6],23,76029189),g=e(g,v=e(v,l=e(l,i,g,v,u[h+9],4,-640364487),i,g,u[h+12],11,-421815835),l,i,u[h+15],16,530742520),v,l,u[h+2],23,-995338651),g=o(g,v=o(v,l=o(l,i,g,v,u[h+0],6,-198630844),i,g,u[h+7],10,1126891415),l,i,u[h+14],15,-1416354905),v,l,u[h+5],21,-57434055),g=o(g,v=o(v,l=o(l,i,g,v,u[h+12],6,1700485571),i,g,u[h+3],10,-1894986606),l,i,u[h+10],15,-1051523),v,l,u[h+1],21,-2054922799),g=o(g,v=o(v,l=o(l,i,g,v,u[h+8],6,1873313359),i,g,u[h+15],10,-30611744),l,i,u[h+6],15,-1560198380),v,l,u[h+13],21,1309151649),g=o(g,v=o(v,l=o(l,i,g,v,u[h+4],6,-145523070),i,g,u[h+11],10,-1120210379),l,i,u[h+2],15,718787259),v,l,u[h+9],21,-343485551),l=f(l,A),i=f(i,d),g=f(g,C),v=f(v,m)}var y=Array(l,i,g,v),b="";for(h=0;h<32*y.length;h+=8)b+=String.fromCharCode(y[h>>5]>>>h%32&255);var S="0123456789abcdef",j="";for(h=0;h<b.length;h++)u=b.charCodeAt(h),j+=S.charAt(u>>>4&15)+S.charAt(15&u);return j}
  1142. /** Скрипт для красивых диалоговых окошек */
  1143. const popup = new(function () {
  1144. this.popUp,
  1145. this.downer,
  1146. this.msgText,
  1147. this.buttons = [];
  1148.  
  1149. function init() {
  1150. addStyle();
  1151. addBlocks();
  1152. }
  1153.  
  1154. const addStyle = () => {
  1155. let style = document.createElement('style');
  1156. style.innerText = `
  1157. .PopUp_ {
  1158. position: absolute;
  1159. min-width: 300px;
  1160. max-width: 500px;
  1161. max-height: 400px;
  1162. background-color: #190e08e6;
  1163. z-index: 10001;
  1164. top: 169px;
  1165. left: 345px;
  1166. border: 3px #ce9767 solid;
  1167. border-radius: 10px;
  1168. display: flex;
  1169. flex-direction: column;
  1170. justify-content: space-around;
  1171. padding: 15px 12px;
  1172. }
  1173.  
  1174. .PopUp_back {
  1175. position: absolute;
  1176. background-color: #00000066;
  1177. width: 100%;
  1178. height: 100%;
  1179. z-index: 10000;
  1180. top: 0;
  1181. left: 0;
  1182. }
  1183.  
  1184. .PopUp_blocks {
  1185. width: 100%;
  1186. height: 50%;
  1187. display: flex;
  1188. justify-content: space-evenly;
  1189. align-items: center;
  1190. flex-wrap: wrap;
  1191. justify-content: center;
  1192. }
  1193.  
  1194. .PopUp_blocks:last-child {
  1195. margin-top: 25px;
  1196. }
  1197.  
  1198. .PopUp_buttons {
  1199. display: flex;
  1200. margin: 10px 12px;
  1201. flex-direction: column;
  1202. }
  1203.  
  1204. .PopUp_button {
  1205. background-color: #52A81C;
  1206. border-radius: 5px;
  1207. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  1208. cursor: pointer;
  1209. padding: 5px 18px 8px;
  1210. }
  1211.  
  1212. .PopUp_input {
  1213. width: 150px;
  1214. font-size: 16px;
  1215. height: 27px;
  1216. border: 1px solid #cf9250;
  1217. border-radius: 9px 9px 0px 0px;
  1218. background: transparent;
  1219. color: #fce1ac;
  1220. padding: 1px 10px;
  1221. box-sizing: border-box;
  1222. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  1223. }
  1224.  
  1225. .PopUp_input::placeholder {
  1226. color: #fce1ac75;
  1227. }
  1228.  
  1229. .PopUp_input:focus {
  1230. outline: 0;
  1231. }
  1232.  
  1233. .PopUp_input + .PopUp_button {
  1234. border-radius: 0px 0px 5px 5px;
  1235. padding: 2px 18px 5px;
  1236. }
  1237.  
  1238. .PopUp_button:hover {
  1239. filter: brightness(1.2);
  1240. }
  1241.  
  1242. .PopUp_text {
  1243. font-size: 22px;
  1244. font-family: sans-serif;
  1245. font-weight: 600;
  1246. font-stretch: condensed;
  1247. letter-spacing: 1px;
  1248. text-align: center;
  1249. }
  1250.  
  1251. .PopUp_buttonText {
  1252. color: #E4FF4C;
  1253. text-shadow: 0px 1px 2px black;
  1254. }
  1255.  
  1256. .PopUp_msgText {
  1257. color: #FDE5B6;
  1258. text-shadow: 0px 0px 2px;
  1259. }
  1260. `;
  1261. document.head.appendChild(style);
  1262. }
  1263.  
  1264. const addBlocks = () => {
  1265. this.back = document.createElement('div');
  1266. this.back.classList.add('PopUp_back');
  1267. this.back.style.display = 'none';
  1268. document.body.append(this.back);
  1269.  
  1270. this.popUp = document.createElement('div');
  1271. this.popUp.classList.add('PopUp_');
  1272. this.back.append(this.popUp);
  1273.  
  1274. let upper = document.createElement('div')
  1275. upper.classList.add('PopUp_blocks');
  1276. this.popUp.append(upper);
  1277.  
  1278. this.downer = document.createElement('div')
  1279. this.downer.classList.add('PopUp_blocks');
  1280. this.popUp.append(this.downer);
  1281.  
  1282. this.msgText = document.createElement('div');
  1283. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  1284. upper.append(this.msgText);
  1285. }
  1286.  
  1287. this.showBack = function () {
  1288. this.back.style.display = '';
  1289. }
  1290.  
  1291. this.hideBack = function () {
  1292. this.back.style.display = 'none';
  1293. }
  1294.  
  1295. this.show = function () {
  1296. this.showBack();
  1297. this.popUp.style.display = '';
  1298. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  1299. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  1300. }
  1301.  
  1302. this.hide = function () {
  1303. this.hideBack();
  1304. this.popUp.style.display = 'none';
  1305. }
  1306.  
  1307. this.addButton = (option, buttonClick) => {
  1308. const contButton = document.createElement('div');
  1309. contButton.classList.add('PopUp_buttons');
  1310. this.downer.append(contButton);
  1311.  
  1312. let inputField = {
  1313. value: option.result || option.default
  1314. }
  1315. if (option.isInput) {
  1316. inputField = document.createElement('input');
  1317. inputField.type = 'text';
  1318. if (option.placeholder) {
  1319. inputField.placeholder = option.placeholder;
  1320. }
  1321. if (option.default) {
  1322. inputField.value = option.default;
  1323. }
  1324. inputField.classList.add('PopUp_input');
  1325. contButton.append(inputField);
  1326. }
  1327.  
  1328. const button = document.createElement('div');
  1329. button.classList.add('PopUp_button');
  1330. contButton.append(button);
  1331.  
  1332. button.addEventListener('click', () => {
  1333. let result = '';
  1334. if (option.isInput) {
  1335. result = inputField.value;
  1336. }
  1337. buttonClick(result);
  1338. });
  1339.  
  1340. const buttonText = document.createElement('div');
  1341. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  1342. buttonText.innerText = option.msg;
  1343. button.append(buttonText);
  1344.  
  1345. this.buttons.push(contButton);
  1346. }
  1347.  
  1348. this.clearButtons = () => {
  1349. while (this.buttons.length) {
  1350. this.buttons.pop().remove();
  1351. }
  1352. }
  1353.  
  1354. this.setMsgText = (text) => {
  1355. this.msgText.innerHTML = text;
  1356. }
  1357.  
  1358. this.confirm = async (msg, buttOpt) => {
  1359. this.clearButtons();
  1360. return new Promise((complete, failed) => {
  1361. this.setMsgText(msg);
  1362. if (!buttOpt) {
  1363. buttOpt = [{msg:'Ок', result: true, isInput: false}];
  1364. }
  1365. for (let butt of buttOpt) {
  1366. this.addButton(butt, (result) => {
  1367. result = result || butt.result;
  1368. complete(result);
  1369. popup.hide();
  1370. });
  1371. }
  1372. this.show();
  1373. });
  1374. }
  1375.  
  1376. document.addEventListener('DOMContentLoaded', init);
  1377. });
  1378. /** Панель управления скриптом */
  1379. const scriptMenu = new (function () {
  1380.  
  1381. this.mainMenu,
  1382. this.buttons = [],
  1383. this.checkboxes = [];
  1384. this.option = {
  1385. showMenu: false,
  1386. showDetails: {}
  1387. };
  1388.  
  1389. this.init = function (option = {}) {
  1390. this.option = Object.assign(this.option, option);
  1391. addStyle();
  1392. addBlocks();
  1393. }
  1394.  
  1395. const addStyle = () => {
  1396. style = document.createElement('style');
  1397. style.innerText = `
  1398. .scriptMenu_status {
  1399. position: absolute;
  1400. z-index: 10001;
  1401. /* max-height: 30px; */
  1402. top: -1px;
  1403. left: 30%;
  1404. cursor: pointer;
  1405. border-radius: 0px 0px 10px 10px;
  1406. background: #190e08e6;
  1407. border: 1px #ce9767 solid;
  1408. font-size: 18px;
  1409. font-family: sans-serif;
  1410. font-weight: 600;
  1411. font-stretch: condensed;
  1412. letter-spacing: 1px;
  1413. color: #fce1ac;
  1414. text-shadow: 0px 0px 1px;
  1415. transition: 0.5s;
  1416. padding: 2px 10px 3px;
  1417. }
  1418. .scriptMenu_statusHide {
  1419. top: -35px;
  1420. height: 30px;
  1421. overflow: hidden;
  1422. }
  1423. .scriptMenu_label {
  1424. position: absolute;
  1425. top: 30%;
  1426. left: -4px;
  1427. z-index: 9999;
  1428. cursor: pointer;
  1429. width: 30px;
  1430. height: 30px;
  1431. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  1432. border: 1px solid #1a2f04;
  1433. border-radius: 5px;
  1434. box-shadow:
  1435. inset 0px 2px 4px #83ce26,
  1436. inset 0px -4px 6px #1a2f04,
  1437. 0px 0px 2px black,
  1438. 0px 0px 0px 2px #ce9767;
  1439. }
  1440. .scriptMenu_label:hover {
  1441. filter: brightness(1.2);
  1442. }
  1443. .scriptMenu_arrowLabel {
  1444. width: 100%;
  1445. height: 100%;
  1446. background-size: 75%;
  1447. background-position: center;
  1448. background-repeat: no-repeat;
  1449. 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");
  1450. box-shadow: 0px 1px 2px #000;
  1451. border-radius: 5px;
  1452. filter: drop-shadow(0px 1px 2px #000D);
  1453. }
  1454. .scriptMenu_main {
  1455. position: absolute;
  1456. max-width: 285px;
  1457. z-index: 9999;
  1458. top: 50%;
  1459. transform: translateY(-50%);
  1460. background: #190e08e6;
  1461. border: 1px #ce9767 solid;
  1462. border-radius: 0px 10px 10px 0px;
  1463. border-left: none;
  1464. padding: 5px 10px 5px 5px;
  1465. box-sizing: border-box;
  1466. font-size: 15px;
  1467. font-family: sans-serif;
  1468. font-weight: 600;
  1469. font-stretch: condensed;
  1470. letter-spacing: 1px;
  1471. color: #fce1ac;
  1472. text-shadow: 0px 0px 1px;
  1473. transition: 1s;
  1474. display: flex;
  1475. flex-direction: column;
  1476. flex-wrap: nowrap;
  1477. }
  1478. .scriptMenu_showMenu {
  1479. display: none;
  1480. }
  1481. .scriptMenu_showMenu:checked~.scriptMenu_main {
  1482. left: 0px;
  1483. }
  1484. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  1485. left: -300px;
  1486. }
  1487. .scriptMenu_divInput {
  1488. margin: 2px;
  1489. }
  1490. .scriptMenu_divInputText {
  1491. margin: 2px;
  1492. align-self: center;
  1493. }
  1494. .scriptMenu_checkbox {
  1495. position: absolute;
  1496. z-index: -1;
  1497. opacity: 0;
  1498. }
  1499. .scriptMenu_checkbox+label {
  1500. display: inline-flex;
  1501. align-items: center;
  1502. user-select: none;
  1503. }
  1504. .scriptMenu_checkbox+label::before {
  1505. content: '';
  1506. display: inline-block;
  1507. width: 20px;
  1508. height: 20px;
  1509. border: 1px solid #cf9250;
  1510. border-radius: 7px;
  1511. margin-right: 7px;
  1512. }
  1513. .scriptMenu_checkbox:checked+label::before {
  1514. 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");
  1515. }
  1516. .scriptMenu_close {
  1517. width: 40px;
  1518. height: 40px;
  1519. position: absolute;
  1520. right: -18px;
  1521. top: -18px;
  1522. border: 3px solid #c18550;
  1523. border-radius: 20px;
  1524. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  1525. background-position-y: 3px;
  1526. box-shadow: -1px 1px 3px black;
  1527. cursor: pointer;
  1528. box-sizing: border-box;
  1529. }
  1530. .scriptMenu_close:hover {
  1531. filter: brightness(1.2);
  1532. }
  1533. .scriptMenu_crossClose {
  1534. width: 100%;
  1535. height: 100%;
  1536. background-size: 65%;
  1537. background-position: center;
  1538. background-repeat: no-repeat;
  1539. 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")
  1540. }
  1541. .scriptMenu_button {
  1542. user-select: none;
  1543. border-radius: 5px;
  1544. cursor: pointer;
  1545. padding: 5px 14px 8px;
  1546. margin: 4px;
  1547. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  1548. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  1549. }
  1550. .scriptMenu_button:hover {
  1551. filter: brightness(1.2);
  1552. }
  1553. .scriptMenu_buttonText {
  1554. color: #fce5b7;
  1555. text-shadow: 0px 1px 2px black;
  1556. text-align: center;
  1557. }
  1558. .scriptMenu_header {
  1559. text-align: center;
  1560. align-self: center;
  1561. font-size: 15px;
  1562. }
  1563. .scriptMenu_header a {
  1564. color: #fce5b7;
  1565. text-decoration: none;
  1566. }
  1567. .scriptMenu_InputText {
  1568. width: 130px;
  1569. height: 24px;
  1570. border: 1px solid #cf9250;
  1571. border-radius: 9px;
  1572. background: transparent;
  1573. color: #fce1ac;
  1574. padding: 0px 10px;
  1575. box-sizing: border-box;
  1576. }
  1577. .scriptMenu_InputText:focus {
  1578. filter: brightness(1.2);
  1579. outline: 0;
  1580. }
  1581. .scriptMenu_InputText::placeholder {
  1582. color: #fce1ac75;
  1583. }
  1584. .scriptMenu_Summary {
  1585. cursor: pointer;
  1586. margin-left: 7px;
  1587. }
  1588. `;
  1589. document.head.appendChild(style);
  1590. }
  1591.  
  1592. const addBlocks = () => {
  1593. const main = document.createElement('div');
  1594. document.body.appendChild(main);
  1595.  
  1596. this.status = document.createElement('div');
  1597. this.status.classList.add('scriptMenu_status');
  1598. this.setStatus('');
  1599. main.appendChild(this.status);
  1600.  
  1601. const label = document.createElement('label');
  1602. label.classList.add('scriptMenu_label');
  1603. label.setAttribute('for', 'checkbox_showMenu');
  1604. main.appendChild(label);
  1605.  
  1606. const arrowLabel = document.createElement('div');
  1607. arrowLabel.classList.add('scriptMenu_arrowLabel');
  1608. label.appendChild(arrowLabel);
  1609.  
  1610. const checkbox = document.createElement('input');
  1611. checkbox.type = 'checkbox';
  1612. checkbox.id = 'checkbox_showMenu';
  1613. checkbox.checked = this.option.showMenu;
  1614. checkbox.classList.add('scriptMenu_showMenu');
  1615. main.appendChild(checkbox);
  1616.  
  1617. this.mainMenu = document.createElement('div');
  1618. this.mainMenu.classList.add('scriptMenu_main');
  1619. main.appendChild(this.mainMenu);
  1620.  
  1621. const closeButton = document.createElement('label');
  1622. closeButton.classList.add('scriptMenu_close');
  1623. closeButton.setAttribute('for', 'checkbox_showMenu');
  1624. this.mainMenu.appendChild(closeButton);
  1625.  
  1626. const crossClose = document.createElement('div');
  1627. crossClose.classList.add('scriptMenu_crossClose');
  1628. closeButton.appendChild(crossClose);
  1629. }
  1630.  
  1631. this.setStatus = (text, onclick) => {
  1632. if (!text) {
  1633. this.status.classList.add('scriptMenu_statusHide');
  1634. } else {
  1635. this.status.classList.remove('scriptMenu_statusHide');
  1636. this.status.innerHTML = text;
  1637. }
  1638.  
  1639. if (typeof onclick == 'function') {
  1640. this.status.addEventListener("click", onclick, {
  1641. once: true
  1642. });
  1643. }
  1644. }
  1645.  
  1646. /**
  1647. * Добавление текстового элемента
  1648. * @param {String} text текст
  1649. * @param {Function} func функция по клику
  1650. * @param {HTMLDivElement} main родитель
  1651. */
  1652. this.addHeader = (text, func, main) => {
  1653. main = main || this.mainMenu;
  1654. const header = document.createElement('div');
  1655. header.classList.add('scriptMenu_header');
  1656. header.innerHTML = text;
  1657. if (typeof func == 'function') {
  1658. header.addEventListener('click', func);
  1659. }
  1660. main.appendChild(header);
  1661. }
  1662.  
  1663. /**
  1664. * Добавление кнопки
  1665. * @param {String} text
  1666. * @param {Function} func
  1667. * @param {String} title
  1668. * @param {HTMLDivElement} main родитель
  1669. */
  1670. this.addButton = (text, func, title, main) => {
  1671. main = main || this.mainMenu;
  1672. const button = document.createElement('div');
  1673. button.classList.add('scriptMenu_button');
  1674. button.title = title;
  1675. button.addEventListener('click', func);
  1676. main.appendChild(button);
  1677.  
  1678. const buttonText = document.createElement('div');
  1679. buttonText.classList.add('scriptMenu_buttonText');
  1680. buttonText.innerText = text;
  1681. button.appendChild(buttonText);
  1682. this.buttons.push(button);
  1683. }
  1684.  
  1685. /**
  1686. * Добавление чекбокса
  1687. * @param {String} label
  1688. * @param {String} title
  1689. * @param {HTMLDivElement} main родитель
  1690. * @returns
  1691. */
  1692. this.addCheckbox = (label, title, main) => {
  1693. main = main || this.mainMenu;
  1694. const divCheckbox = document.createElement('div');
  1695. divCheckbox.classList.add('scriptMenu_divInput');
  1696. divCheckbox.title = title;
  1697. main.appendChild(divCheckbox);
  1698.  
  1699. const newCheckbox = document.createElement('input');
  1700. newCheckbox.type = 'checkbox';
  1701. newCheckbox.id = 'newCheckbox' + this.checkboxes.length;
  1702. newCheckbox.classList.add('scriptMenu_checkbox');
  1703. divCheckbox.appendChild(newCheckbox)
  1704.  
  1705. const newCheckboxLabel = document.createElement('label');
  1706. newCheckboxLabel.innerText = label;
  1707. newCheckboxLabel.setAttribute('for', newCheckbox.id);
  1708. divCheckbox.appendChild(newCheckboxLabel);
  1709.  
  1710. this.checkboxes.push(newCheckbox);
  1711. return newCheckbox;
  1712. }
  1713.  
  1714. /**
  1715. * Добавление поля ввода
  1716. * @param {String} title
  1717. * @param {String} placeholder
  1718. * @param {HTMLDivElement} main родитель
  1719. * @returns
  1720. */
  1721. this.addInputText = (title, placeholder, main) => {
  1722. main = main || this.mainMenu;
  1723. const divInputText = document.createElement('div');
  1724. divInputText.classList.add('scriptMenu_divInputText');
  1725. divInputText.title = title;
  1726. main.appendChild(divInputText);
  1727.  
  1728. const newInputText = document.createElement('input');
  1729. newInputText.type = 'text';
  1730. if (placeholder) {
  1731. newInputText.placeholder = placeholder;
  1732. }
  1733. newInputText.classList.add('scriptMenu_InputText');
  1734. divInputText.appendChild(newInputText)
  1735. return newInputText;
  1736. }
  1737.  
  1738. /**
  1739. * Добавляет раскрывающийся блок
  1740. * @param {String} summary
  1741. * @param {String} name
  1742. * @returns
  1743. */
  1744. this.addDetails = (summaryText, name) => {
  1745. const details = document.createElement('details');
  1746. if (this.option.showDetails[name]) {
  1747. details.open = this.option.showDetails[name];
  1748. }
  1749. this.mainMenu.appendChild(details);
  1750.  
  1751. const summary = document.createElement('summary');
  1752. summary.classList.add('scriptMenu_Summary');
  1753. summary.innerText = summaryText;
  1754. details.appendChild(summary);
  1755.  
  1756. return details;
  1757. }
  1758. });
  1759. /** Хранилище данных (только для числовых и булевых значений) */
  1760. const storage = {
  1761. name: GM_info.script.name,
  1762. get: function (key, def) {
  1763. let value = localStorage[this.name + ':' + key];
  1764. try {
  1765. return JSON.parse(value)
  1766. } catch {
  1767. return def;
  1768. }
  1769. },
  1770. set: function (key, value) {
  1771. return localStorage[this.name + ':' + key] = value;
  1772. },
  1773. delete: function (key) {
  1774. return delete localStorage[this.name + ':' + key];
  1775. }
  1776. }
  1777. /** Отправка экспедиций TODO: переписать в класс */
  1778. // Проверка и отправка экспедиций
  1779. function checkExpedition() {
  1780. var heroesInfo = '{"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}';
  1781. var sendExped = '{"calls":[{"name":"expeditionSendHeroes","args":{"expeditionId":#number#,"heroes":[#heroes#]},"ident":"body"}]}';
  1782. var checkExped = '{"calls":[{"name":"expeditionGet","args":{},"ident":"body"}]}';
  1783. var endExped = '{"calls":[{"name":"expeditionFarm","args":{"expeditionId":#number#},"ident":"body"}]}';
  1784.  
  1785. send(checkExped, function(res) {
  1786. let dataExpedition = getJson(res);
  1787. if (!dataExpedition) return;
  1788. dataExpedition = dataExpedition?.results[0]?.result?.response;
  1789. dataExped = {useHeroes:[], exped:[]};
  1790. for (var n in dataExpedition) {
  1791. var exped = dataExpedition[n];
  1792.  
  1793. // console.log(exped, exped.status, dateNow, exped.endTime);
  1794. var dateNow = (Date.now() / 1000);
  1795. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  1796. send(endExped.replace('#number#', exped.id), function(res, exped) {
  1797. // console.log(exped.id,res);
  1798. }, exped);
  1799. } else {
  1800. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  1801. }
  1802. if (exped.status == 1) {
  1803. dataExped.exped.push({id: exped.id, power: exped.power});
  1804. }
  1805. }
  1806. dataExped.exped = dataExped.exped.sort((a,b)=>(b.power - a.power));
  1807. send(heroesInfo, function(res, expData) {
  1808. let dataHeroes = getJson(res);
  1809. if (!dataHeroes) return;
  1810. dataHeroes = dataHeroes?.results[0]?.result?.response;
  1811. let heroesArr = [];
  1812. for (let n in dataHeroes) {
  1813. let hero = dataHeroes[n];
  1814. if (hero.xp > 0 && !expData.useHeroes.includes(hero.id)) {
  1815. heroesArr.push({id: hero.id, power: hero.power})
  1816. }
  1817. }
  1818. heroesArr = heroesArr.sort((a,b)=>(a.power - b.power));
  1819. for (let i in expData.exped) {
  1820. let exped = expData.exped[i];
  1821. let heroesIds = selectionHeroes(heroesArr, exped.power);
  1822. if (heroesIds && heroesIds.length > 4) {
  1823. for (let q in heroesArr) {
  1824. if (heroesIds.includes(heroesArr[q].id)) {
  1825. delete heroesArr[q];
  1826. }
  1827. }
  1828. let sendExp = sendExped.replace('#heroes#', heroesIds.join());
  1829. sendExp = sendExp.replace('#number#', exped.id)
  1830. send(sendExp, function(res, exped) {
  1831. // console.log(exped,res);
  1832. }, sendExp);
  1833. }
  1834. }
  1835. setProgress('Done', true);
  1836. }, dataExped)
  1837. }, null);
  1838. }
  1839. // Подбор героев для экспедиций
  1840. function selectionHeroes(heroes, power) {
  1841. let resultHeroers = [];
  1842. let heroesIds = [];
  1843. for (let q = 0; q < 5; q++) {
  1844. for (let i in heroes) {
  1845. let hero = heroes[i];
  1846. let summ = summArray(resultHeroers, 'power');
  1847. if (heroesIds.includes(hero.id)) {
  1848. continue;
  1849. }
  1850. // let dif = (summ + hero.power) - power;
  1851. let need = Math.round((power - summ) / (5 - resultHeroers.length));
  1852. // if (hero.power > need && dif < need) {
  1853. if (hero.power > need) {
  1854. resultHeroers.push(hero);
  1855. heroesIds.push(hero.id);
  1856. break;
  1857. }
  1858. }
  1859. }
  1860. let summ = summArray(resultHeroers, 'power');
  1861. if (summ < power) {
  1862. return false;
  1863. }
  1864. return heroesIds;
  1865. }
  1866. // Суммирует силу героев в пачке
  1867. function summArray(arr, elem) {
  1868. return arr.reduce((e,i)=>e+i[elem],0);
  1869. }
  1870. // Отправка запроса
  1871. function send(json, callback, pr) {
  1872. /** Получаем заголовки предыдущего перехваченого запроса */
  1873. let headers = lastHeaders;
  1874. /** Увеличиваем заголовок идетификатора запроса на 1 */
  1875. headers["X-Request-Id"]++;
  1876. /** Расчитываем заголовок с сигнатурой */
  1877. headers["X-Auth-Signature"] = getSignature(headers, json);
  1878. /** Создаем новый AJAX запрос */
  1879. let xhr = new XMLHttpRequest;
  1880. /** Указываем ранее сохраненный URL для API запросов */
  1881. xhr.open('POST', apiUrl, true);
  1882. /** Добавляем функцию к событию смены статуса запроса */
  1883. xhr.onreadystatechange = function() {
  1884. /** Если результат запроса получен вызываем колбек функцию */
  1885. if(xhr.readyState == 4) {
  1886. let randTimeout = Math.random() * 200 + 200;
  1887. setTimeout(callback, randTimeout, xhr.response, pr);
  1888. }
  1889. };
  1890. /** Указываем тип запроса */
  1891. xhr.responseType = 'json';
  1892. /** Задаем заголовки запроса */
  1893. for(let nameHeader in headers) {
  1894. let head = headers[nameHeader];
  1895. xhr.setRequestHeader(nameHeader, head);
  1896. }
  1897. /** Отправляем запрос */
  1898. xhr.send(json);
  1899. }
  1900.  
  1901. function testDungeon(titanit) {
  1902. return new Promise((resolve, reject) => {
  1903. popup.showBack();
  1904. dung = new executeDungeon(resolve, reject);
  1905. dung.start(titanit);
  1906. });
  1907. }
  1908.  
  1909. /** Прохождение подземелья */
  1910. function executeDungeon(resolve, reject) {
  1911. dungeonActivity = 0;
  1912. maxDungeonActivity = 150;
  1913.  
  1914. titanGetAll = [];
  1915.  
  1916. teams = {
  1917. heroes: [],
  1918. earth: [],
  1919. fire: [],
  1920. neutral: [],
  1921. water: [],
  1922. }
  1923.  
  1924. titanStats = [];
  1925.  
  1926. titansStates = {};
  1927.  
  1928. callsExecuteDungeon = {
  1929. calls: [{
  1930. name: "dungeonGetInfo",
  1931. args: {},
  1932. ident: "dungeonGetInfo"
  1933. }, {
  1934. name: "teamGetAll",
  1935. args: {},
  1936. ident: "teamGetAll"
  1937. }, {
  1938. name: "teamGetFavor",
  1939. args: {},
  1940. ident: "teamGetFavor"
  1941. }, {
  1942. name: "clanGetInfo",
  1943. args: {},
  1944. ident: "clanGetInfo"
  1945. }, {
  1946. name: "titanGetAll",
  1947. args: {},
  1948. ident: "titanGetAll"
  1949. }]
  1950. }
  1951.  
  1952. this.start = function(titanit) {
  1953. maxDungeonActivity = titanit || 75;
  1954. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  1955. }
  1956.  
  1957. /** Получаем данные по подземелью */
  1958. function startDungeon(e) {
  1959. res = e.results;
  1960. dungeonGetInfo = res[0].result.response;
  1961. if (!dungeonGetInfo) {
  1962. endDungeon('noDungeon', res);
  1963. return;
  1964. }
  1965. teamGetAll = res[1].result.response;
  1966. teamGetFavor = res[2].result.response;
  1967. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  1968. titanGetAll = Object.values(res[4].result.response);
  1969.  
  1970. teams.hero = {
  1971. favor: teamGetFavor.dungeon_hero,
  1972. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  1973. teamNum: 0,
  1974. }
  1975. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  1976. if (heroPet) {
  1977. teams.hero.pet = heroPet;
  1978. }
  1979.  
  1980. teams.neutral = {
  1981. favor: {},
  1982. heroes: getTitanTeam(titanGetAll, 'neutral'),
  1983. teamNum: 0,
  1984. };
  1985. teams.water = {
  1986. favor: {},
  1987. heroes: getTitanTeam(titanGetAll, 'water'),
  1988. teamNum: 0,
  1989. };
  1990. teams.fire = {
  1991. favor: {},
  1992. heroes: getTitanTeam(titanGetAll, 'fire'),
  1993. teamNum: 0,
  1994. };
  1995. teams.earth = {
  1996. favor: {},
  1997. heroes: getTitanTeam(titanGetAll, 'earth'),
  1998. teamNum: 0,
  1999. };
  2000.  
  2001.  
  2002. checkFloor(dungeonGetInfo);
  2003. }
  2004.  
  2005. function getTitanTeam(titans, type) {
  2006. switch (type) {
  2007. case 'neutral':
  2008. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  2009. case 'water':
  2010. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  2011. case 'fire':
  2012. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  2013. case 'earth':
  2014. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  2015. }
  2016. }
  2017.  
  2018. function fixTitanTeam(titans) {
  2019. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  2020. return titans;
  2021. }
  2022.  
  2023. /** Проверяем этаж */
  2024. function checkFloor(dungeonInfo) {
  2025. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  2026. saveProgress();
  2027. return;
  2028. }
  2029. // console.log(dungeonInfo, dungeonActivity);
  2030. setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  2031. if (dungeonActivity >= maxDungeonActivity) {
  2032. endDungeon('endDungeon');
  2033. return;
  2034. }
  2035. titansStates = dungeonInfo.states.titans;
  2036. titanStats = titanObjToArray(titansStates);
  2037. floorChoices = dungeonInfo.floor.userData;
  2038. floorType = dungeonInfo.floorType;
  2039. primeElement = dungeonInfo.elements.prime;
  2040. if (floorType == "battle") {
  2041. promises = [];
  2042. for (let teamNum in floorChoices) {
  2043. attackerType = floorChoices[teamNum].attackerType;
  2044. promises.push(startBattle(teamNum, attackerType));
  2045. }
  2046. Promise.all(promises)
  2047. .then(processingPromises);
  2048. }
  2049. }
  2050.  
  2051. function processingPromises(results) {
  2052. selectInfo = results[0];
  2053. if (results.length < 2) {
  2054. // console.log(selectInfo);
  2055. endBattle(selectInfo);
  2056. return;
  2057. }
  2058.  
  2059. selectInfo = false;
  2060. minRes = 1e10;
  2061. for (let info of results) {
  2062. diffXP = diffTitanXP(info.progress[0].attackers.heroes);
  2063. diffRes = diffXP;
  2064. if (info.attackerType == 'neutral') {
  2065. diffRes /= 2;
  2066. diffRes -= 4;
  2067. }
  2068. if (info.attackerType == primeElement) {
  2069. diffRes /= 2;
  2070. diffRes -= 5;
  2071. }
  2072. info.diffXP = diffXP
  2073. info.diffRes = diffRes
  2074. if (!info.result.win) {
  2075. continue;
  2076. }
  2077. if (diffRes < minRes) {
  2078. selectInfo = info;
  2079. minRes = diffRes;
  2080. }
  2081. }
  2082. // console.log(selectInfo.teamNum, results);
  2083. if (!selectInfo) {
  2084. endDungeon('dungeonEndBattle\n', results);
  2085. return;
  2086. }
  2087.  
  2088. startBattle(selectInfo.teamNum, selectInfo.attackerType)
  2089. .then(endBattle);
  2090. }
  2091.  
  2092. /** Начинаем бой */
  2093. function startBattle(teamNum, attackerType) {
  2094. return new Promise(function (resolve, reject) {
  2095. args = fixTitanTeam(teams[attackerType]);
  2096. args.teamNum = teamNum;
  2097. startBattleCall = {
  2098. calls: [{
  2099. name: "dungeonStartBattle",
  2100. args,
  2101. ident: "body"
  2102. }]
  2103. }
  2104. send(JSON.stringify(startBattleCall), resultBattle, {
  2105. resolve,
  2106. teamNum,
  2107. attackerType
  2108. });
  2109. });
  2110. }
  2111. /** Возращает резульат боя в промис */
  2112. function resultBattle(resultBattles, args) {
  2113. battleData = resultBattles.results[0].result.response;
  2114. battleType = "get_tower";
  2115. if (battleData.type == "dungeon_titan") {
  2116. battleType = "get_titan";
  2117. }
  2118. BattleCalc(battleData, battleType, function (result) {
  2119. result.teamNum = args.teamNum;
  2120. result.attackerType = args.attackerType;
  2121. args.resolve(result);
  2122. });
  2123. }
  2124. /** Заканчиваем бой */
  2125. function endBattle(battleInfo) {
  2126. if (battleInfo.result.win) {
  2127. endBattleCall = {
  2128. calls: [{
  2129. name: "dungeonEndBattle",
  2130. args: {
  2131. result: battleInfo.result,
  2132. progress: battleInfo.progress,
  2133. },
  2134. ident: "body"
  2135. }]
  2136. }
  2137. send(JSON.stringify(endBattleCall), resultEndBattle);
  2138. } else {
  2139. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  2140. }
  2141. }
  2142.  
  2143. /** Получаем и обрабатываем результаты боя */
  2144. function resultEndBattle(e) {
  2145. battleResult = e.results[0].result.response;
  2146. if ('error' in battleResult) {
  2147. endDungeon('errorBattleResult', battleResult);
  2148. return;
  2149. }
  2150. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  2151. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  2152. checkFloor(dungeonGetInfo);
  2153. }
  2154.  
  2155. /** Возвращает разницу между максимальными ХП титанов и переданными */
  2156. function diffTitanXP(titans) {
  2157. sumCurrentXp = 0;
  2158. for (let i in titans) {
  2159. sumCurrentXp += titans[i].hp
  2160. }
  2161. titanIds = Object.getOwnPropertyNames(titans);
  2162. maxHP = titanStats.reduce((n, e) =>
  2163. titanIds.includes(e.id.toString()) ? n + e.hp : n
  2164. , 0);
  2165. return maxHP < sumCurrentXp ? 0 : maxHP - sumCurrentXp;
  2166. }
  2167.  
  2168. /** Преобразует объект с идетификаторами в массив с идетификаторами*/
  2169. function titanObjToArray(obj) {
  2170. let titans = [];
  2171. for (let id in obj) {
  2172. obj[id].id = id;
  2173. titans.push(obj[id]);
  2174. }
  2175. return titans;
  2176. }
  2177.  
  2178. function saveProgress() {
  2179. let saveProgressCall = {
  2180. calls: [{
  2181. name: "dungeonSaveProgress",
  2182. args: {},
  2183. ident: "body"
  2184. }]
  2185. }
  2186. send(JSON.stringify(saveProgressCall), resultEndBattle);
  2187. }
  2188.  
  2189. function endDungeon(reason, info) {
  2190. console.log(reason, info);
  2191. setProgress('Dungeon completed!', true);
  2192. resolve();
  2193. }
  2194. }
  2195.  
  2196. function testTower() {
  2197. return new Promise((resolve, reject) => {
  2198. popup.showBack();
  2199. tower = new executeTower(resolve, reject);
  2200. tower.start();
  2201. });
  2202. }
  2203.  
  2204. /** Прохождение башни */
  2205. function executeTower(resolve, reject) {
  2206. lastTowerInfo = {};
  2207.  
  2208. scullCoin = 0;
  2209.  
  2210. heroGetAll = [];
  2211.  
  2212. heroesStates = {};
  2213.  
  2214. argsBattle = {
  2215. heroes: [],
  2216. favor: {},
  2217. };
  2218.  
  2219. callsExecuteTower = {
  2220. calls: [{
  2221. name: "towerGetInfo",
  2222. args: {},
  2223. ident: "towerGetInfo"
  2224. }, {
  2225. name: "teamGetAll",
  2226. args: {},
  2227. ident: "teamGetAll"
  2228. }, {
  2229. name: "teamGetFavor",
  2230. args: {},
  2231. ident: "teamGetFavor"
  2232. }, {
  2233. name: "inventoryGet",
  2234. args: {},
  2235. ident: "inventoryGet"
  2236. }, {
  2237. name: "heroGetAll",
  2238. args: {},
  2239. ident: "heroGetAll"
  2240. }]
  2241. }
  2242.  
  2243. buffIds = [
  2244. {id: 0, cost: 0, isBuy: false}, // заглушка
  2245. {id: 1, cost: 1, isBuy: true}, // 3% атака
  2246. {id: 2, cost: 6, isBuy: true}, // 2% атака
  2247. {id: 3, cost: 16, isBuy: true}, // 4% атака
  2248. {id: 4, cost: 40, isBuy: true}, // 8% атака
  2249. {id: 5, cost: 1, isBuy: true}, // 10% броня
  2250. {id: 6, cost: 6, isBuy: true}, // 5% броня
  2251. {id: 7, cost: 16, isBuy: true}, // 10% броня
  2252. {id: 8, cost: 40, isBuy: true}, // 20% броня
  2253. {id: 9, cost: 1, isBuy: true}, // 10% защита от магии
  2254. {id: 10, cost: 6, isBuy: true}, // 5% защита от магии
  2255. {id: 11, cost: 16, isBuy: true}, // 10% защита от магии
  2256. {id: 12, cost: 40, isBuy: true}, // 20% защита от магии
  2257. {id: 13, cost: 1, isBuy: false}, // 40% здоровья герою
  2258. {id: 14, cost: 6, isBuy: false}, // 40% здоровья герою
  2259. {id: 15, cost: 16, isBuy: false}, // 80% здоровья герою
  2260. {id: 16, cost: 40, isBuy: false}, // 40% здоровья всем героям
  2261. {id: 17, cost: 1, isBuy: false}, // 40% энергии герою
  2262. {id: 18, cost: 3, isBuy: false}, // 40% энергии герою
  2263. {id: 19, cost: 8, isBuy: false}, // 80% энергии герою
  2264. {id: 20, cost: 20, isBuy: false}, // 40% энергии всем героям
  2265. {id: 21, cost: 40, isBuy: false}, // Воскрешение героя
  2266. ]
  2267.  
  2268. this.start = function() {
  2269. send(JSON.stringify(callsExecuteTower), startTower);
  2270. }
  2271.  
  2272. /** Получаем данные по подземелью */
  2273. function startTower(e) {
  2274. res = e.results;
  2275. towerGetInfo = res[0].result.response;
  2276. if (!towerGetInfo) {
  2277. endTower('noTower', res);
  2278. return;
  2279. }
  2280. teamGetAll = res[1].result.response;
  2281. teamGetFavor = res[2].result.response;
  2282. inventoryGet = res[3].result.response;
  2283. heroGetAll = Object.values(res[4].result.response);
  2284.  
  2285. scullCoin = inventoryGet.coin[7] ?? 0;
  2286.  
  2287. argsBattle.favor = teamGetFavor.tower;
  2288. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);;
  2289. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  2290. if (pet) {
  2291. argsBattle.pet = pet;
  2292. }
  2293.  
  2294. checkFloor(towerGetInfo);
  2295. }
  2296.  
  2297. function fixHeroesTeam(argsBattle) {
  2298. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  2299. if (fixHeroes.length < 5) {
  2300. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  2301. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0,5).map(e => e.id);
  2302. Object.keys(argsBattle.favor).forEach(e => {
  2303. if (!fixHeroes.includes(+e)) {
  2304. delete argsBattle.favor[e];
  2305. }
  2306. })
  2307. }
  2308. argsBattle.heroes = fixHeroes;
  2309. return argsBattle;
  2310. }
  2311.  
  2312. /** Проверяем этаж */
  2313. function checkFloor(towerInfo) {
  2314. lastTowerInfo = towerInfo;
  2315. maySkipFloor = +towerInfo.maySkipFloor;
  2316. floorNumber = +towerInfo.floorNumber;
  2317. heroesStates = towerInfo.states.heroes;
  2318.  
  2319. isOpenChest = false;
  2320. if (towerInfo.floorType == "chest") {
  2321. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  2322. }
  2323.  
  2324. setProgress('Tower: Этаж ' + floorNumber);
  2325. if (floorNumber > 49) {
  2326. if (isOpenChest) {
  2327. endTower('alreadyOpenChest 50 floor', floorNumber);
  2328. return;
  2329. }
  2330. }
  2331. // towerInfo.chestSkip ???
  2332. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  2333. nextOpenChest(floorNumber);
  2334. return;
  2335. }
  2336.  
  2337. // console.log(towerInfo, scullCoin);
  2338. switch (towerInfo.floorType) {
  2339. case "battle":
  2340. if (floorNumber <= maySkipFloor) {
  2341. skipFloor();
  2342. return;
  2343. }
  2344. startBattle().then(endBattle);
  2345. return;
  2346. case "buff":
  2347. checkBuff(towerInfo);
  2348. return;
  2349. case "chest":
  2350. openChest(floorNumber);
  2351. return;
  2352. default:
  2353. console.log('!', towerInfo.floorType, towerInfo);
  2354. break;
  2355. }
  2356. }
  2357.  
  2358. /** Начинаем бой */
  2359. function startBattle() {
  2360. return new Promise(function (resolve, reject) {
  2361. towerStartBattle = {
  2362. calls: [{
  2363. name: "towerStartBattle",
  2364. args: fixHeroesTeam(argsBattle),
  2365. ident: "body"
  2366. }]
  2367. }
  2368. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  2369. });
  2370. }
  2371. /** Возращает резульат боя в промис */
  2372. function resultBattle(resultBattles, resolve) {
  2373. battleData = resultBattles.results[0].result.response;
  2374. battleType = "get_tower";
  2375. BattleCalc(battleData, battleType, function (result) {
  2376. resolve(result);
  2377. });
  2378. }
  2379. /** Заканчиваем бой */
  2380. function endBattle(battleInfo) {
  2381. if (battleInfo.result.win) {
  2382. endBattleCall = {
  2383. calls: [{
  2384. name: "towerEndBattle",
  2385. args: {
  2386. result: battleInfo.result,
  2387. progress: battleInfo.progress,
  2388. },
  2389. ident: "body"
  2390. }]
  2391. }
  2392. send(JSON.stringify(endBattleCall), resultEndBattle);
  2393. } else {
  2394. endTower('towerEndBattle win: false\n', battleInfo);
  2395. }
  2396. }
  2397.  
  2398. /** Получаем и обрабатываем результаты боя */
  2399. function resultEndBattle(e) {
  2400. battleResult = e.results[0].result.response;
  2401. if ('error' in battleResult) {
  2402. endTower('errorBattleResult', battleResult);
  2403. return;
  2404. }
  2405. if ('reward' in battleResult) {
  2406. scullCoin += battleResult.reward?.coin[7] ?? 0;
  2407. }
  2408. nextFloor();
  2409. }
  2410.  
  2411. function nextFloor() {
  2412. nextFloorCall = {
  2413. calls: [{
  2414. name: "towerNextFloor",
  2415. args: {},
  2416. ident: "body"
  2417. }]
  2418. }
  2419. send(JSON.stringify(nextFloorCall), checkDataFloor);
  2420. }
  2421.  
  2422. function openChest(floorNumber) {
  2423. floorNumber = floorNumber || 0;
  2424. openChestCall = {
  2425. calls: [{
  2426. name: "towerOpenChest",
  2427. args: {
  2428. num: 2
  2429. },
  2430. ident: "body"
  2431. }]
  2432. }
  2433. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  2434. }
  2435.  
  2436. function lastChest() {
  2437. endTower('openChest 50 floor', floorNumber);
  2438. }
  2439.  
  2440. function skipFloor() {
  2441. skipFloorCall = {
  2442. calls: [{
  2443. name: "towerSkipFloor",
  2444. args: {},
  2445. ident: "body"
  2446. }]
  2447. }
  2448. send(JSON.stringify(skipFloorCall), checkDataFloor);
  2449. }
  2450.  
  2451. function checkBuff(towerInfo) {
  2452. buffArr = towerInfo.floor;
  2453. promises = [];
  2454. for (let buff of buffArr) {
  2455. buffInfo = buffIds[buff.id];
  2456. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  2457. scullCoin -= buffInfo.cost;
  2458. promises.push(buyBuff(buff.id));
  2459. }
  2460. }
  2461. Promise.all(promises).then(nextFloor);
  2462. }
  2463.  
  2464. function buyBuff(buffId) {
  2465. return new Promise(function(resolve, reject) {
  2466. buyBuffCall = {
  2467. calls: [{
  2468. name: "towerBuyBuff",
  2469. args: {
  2470. buffId
  2471. },
  2472. ident: "body"
  2473. }]
  2474. }
  2475. send(JSON.stringify(buyBuffCall), resolve);
  2476. });
  2477. }
  2478.  
  2479. function checkDataFloor(result) {
  2480. towerInfo = result.results[0].result.response;
  2481. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  2482. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  2483. }
  2484. if ('tower' in towerInfo) {
  2485. towerInfo = towerInfo.tower;
  2486. }
  2487. if ('skullReward' in towerInfo) {
  2488. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  2489. }
  2490. checkFloor(towerInfo);
  2491. }
  2492. /** Получаем награды башни */
  2493. function farmPointRewards() {
  2494. let {pointRewards,points} = lastTowerInfo;
  2495. pointsAll = Object.getOwnPropertyNames(pointRewards);
  2496. farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  2497. if (!farmPoints.length) {
  2498. return;
  2499. }
  2500. farmPointRewardsCall = {
  2501. calls: [{
  2502. name: "tower_farmPointRewards",
  2503. args: {
  2504. points: farmPoints
  2505. },
  2506. ident: "body"
  2507. }]
  2508. }
  2509. send(JSON.stringify(farmPointRewardsCall), ()=>{});
  2510. }
  2511. /** Меняем черепа на монетки */
  2512. function farmSkullReward() {
  2513. farmSkullRewardCall = {
  2514. calls: [{
  2515. name: "tower_farmSkullReward",
  2516. args: {},
  2517. ident: "body"
  2518. }]
  2519. }
  2520. send(JSON.stringify(farmSkullRewardCall), () => {});
  2521. }
  2522.  
  2523. function nextOpenChest(floorNumber) {
  2524. if (floorNumber > 49) {
  2525. endTower('openChest 50 floor', floorNumber);
  2526. return;
  2527. }
  2528. nextOpenChestCall = {
  2529. calls: [{
  2530. name: "towerNextChest",
  2531. args: {},
  2532. ident: "towerNextChest"
  2533. }, {
  2534. name: "towerOpenChest",
  2535. args: {
  2536. num: 2
  2537. },
  2538. ident: "towerOpenChest"
  2539. }]
  2540. }
  2541. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  2542. }
  2543.  
  2544. function endTower(reason, info) {
  2545. console.log(reason, info);
  2546. if (reason != 'noTower') {
  2547. farmPointRewards();
  2548. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  2549. farmSkullReward();
  2550. }
  2551. }
  2552. setProgress('Tower completed!', true);
  2553. resolve();
  2554. }
  2555. }
  2556.  
  2557. function testTitanArena() {
  2558. return new Promise((resolve, reject) => {
  2559. popup.showBack();
  2560. titAren = new executeTitanArena(resolve, reject);
  2561. titAren.start();
  2562. });
  2563. }
  2564.  
  2565. /** Прохождение арены титанов */
  2566. function executeTitanArena(resolve, reject) {
  2567. let titan_arena = [];
  2568. let finishListBattle = [];
  2569. /** Идетификатор текущей пачки */
  2570. let currentRival = 0;
  2571. /** Колличество попыток добития пачки */
  2572. let attempts = 0;
  2573. /** Была ли попытка добития текущего тира */
  2574. let isCheckCurrentTier = false;
  2575. /** Текущий тир */
  2576. let currTier = 0;
  2577. /** Количество битв на текущем тире */
  2578. let countRivalsTier = 0;
  2579.  
  2580. let callsStart = {
  2581. calls: [{
  2582. name: "titanArenaGetStatus",
  2583. args: {},
  2584. ident: "titanArenaGetStatus"
  2585. }, {
  2586. name: "teamGetAll",
  2587. args: {},
  2588. ident: "teamGetAll"
  2589. }]
  2590. }
  2591.  
  2592. this.start = function () {
  2593. send(JSON.stringify(callsStart), startTitanArena);
  2594. }
  2595.  
  2596. function startTitanArena(data) {
  2597. let titanArena = data.results[0].result.response;
  2598. if (titanArena.status == 'disabled') {
  2599. endTitanArena('disabled', titanArena);
  2600. return;
  2601. }
  2602.  
  2603. let teamGetAll = data.results[1].result.response;
  2604. titan_arena = teamGetAll.titan_arena;
  2605.  
  2606. checkTier(titanArena)
  2607. }
  2608.  
  2609. function checkTier(titanArena) {
  2610. if (titanArena.status == "peace_time") {
  2611. endTitanArena('Peace_time', titanArena);
  2612. return;
  2613. }
  2614. currTier = titanArena.tier;
  2615. if (currTier) {
  2616. setProgress('Турнир Стихий: Уровень ' + currTier);
  2617. }
  2618.  
  2619. if (titanArena.status == "completed_tier") {
  2620. titanArenaCompleteTier();
  2621. return;
  2622. }
  2623. /** Проверка на возможность рейда */
  2624. if (titanArena.canRaid) {
  2625. titanArenaStartRaid();
  2626. return;
  2627. }
  2628. /** Проверка была ли попытка добития текущего тира */
  2629. if (!isCheckCurrentTier) {
  2630. checkRivals(titanArena.rivals);
  2631. return;
  2632. }
  2633.  
  2634. endTitanArena('Done or not canRaid', titanArena);
  2635. }
  2636. /** Отправка информации о тире на проверку */
  2637. function checkResultInfo(data) {
  2638. let titanArena = data.results[0].result.response;
  2639. checkTier(titanArena);
  2640. }
  2641. /** Завершить текущий тир */
  2642. function titanArenaCompleteTier() {
  2643. isCheckCurrentTier = false;
  2644. let calls = [{
  2645. name: "titanArenaCompleteTier",
  2646. args: {},
  2647. ident: "body"
  2648. }];
  2649. send(JSON.stringify({calls}), checkResultInfo);
  2650. }
  2651. /** Собираем точки которые нужно добить */
  2652. function checkRivals(rivals) {
  2653. finishListBattle = [];
  2654. for (let n in rivals) {
  2655. if (rivals[n].attackScore < 250) {
  2656. finishListBattle.push(n);
  2657. }
  2658. }
  2659. console.log('checkRivals', finishListBattle);
  2660. countRivalsTier = finishListBattle.length;
  2661. roundRivals();
  2662. }
  2663. /** Выбор следующей точки для добития */
  2664. function roundRivals() {
  2665. let countRivals = finishListBattle.length;
  2666. if (!countRivals) {
  2667. // Весь тир проверен
  2668. isCheckCurrentTier = true;
  2669. titanArenaGetStatus();
  2670. return;
  2671. }
  2672. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  2673. currentRival = finishListBattle.pop();
  2674. attempts = +currentRival;
  2675. // console.log('roundRivals', currentRival);
  2676. titanArenaStartBattle(currentRival);
  2677. }
  2678. /** Начало одиночной битвы */
  2679. function titanArenaStartBattle(rivalId) {
  2680. let calls = [{
  2681. name: "titanArenaStartBattle",
  2682. args: {
  2683. rivalId: rivalId,
  2684. titans: titan_arena
  2685. },
  2686. ident: "body"
  2687. }];
  2688. send(JSON.stringify({calls}), calcResult);
  2689. }
  2690. /** Расчет результатов боя */
  2691. function calcResult(data) {
  2692. let battlesInfo = data.results[0].result.response.battle;
  2693. /** Если попытки равны номеру текущего боя делаем прерасчет */
  2694. if (attempts == currentRival) {
  2695. preCalcBattle(battlesInfo);
  2696. return;
  2697. }
  2698. /** Если попытки еще есть делаем расчет нового боя*/
  2699. if (attempts > 0) {
  2700. attempts--;
  2701. calcBattleResult(battlesInfo)
  2702. .then(resultCalcBattle);
  2703. return;
  2704. }
  2705. /** Иначе переходим к следующему сопернику */
  2706. roundRivals();
  2707. }
  2708. /** Обработка результатов расчета битвы */
  2709. function resultCalcBattle(resultBattle) {
  2710. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  2711. /** Если текущий расчет победа или шансов нет или попытки кончились завершаем бой */
  2712. if (resultBattle.result.win || !attempts) {
  2713. titanArenaEndBattle({
  2714. progress: resultBattle.progress,
  2715. result: resultBattle.result,
  2716. rivalId: resultBattle.battleData.typeId
  2717. });
  2718. return;
  2719. }
  2720. /** Если не победа и есть попытки начинаем новый бой */
  2721. titanArenaStartBattle(resultBattle.battleData.typeId);
  2722. }
  2723. /** Возращает промис расчета результатов битвы */
  2724. function getBattleInfo(battle, isRandSeed) {
  2725. return new Promise(function (resolve) {
  2726. if (isRandSeed) {
  2727. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  2728. }
  2729. // console.log(battle.seed);
  2730. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  2731. });
  2732. }
  2733. /** Прерасчтет битвы */
  2734. function preCalcBattle(battle) {
  2735. let actions = [getBattleInfo(battle, false)];
  2736. const countTestBattle = getInput('countTestBattle');
  2737. for (let i = 0; i < countTestBattle; i++) {
  2738. actions.push(getBattleInfo(battle, true));
  2739. }
  2740. Promise.all(actions)
  2741. .then(resultPreCalcBattle);
  2742. }
  2743. /** Обработка результатов прерасчета битвы */
  2744. function resultPreCalcBattle(e) {
  2745. let wins = e.map(n => n.result.win);
  2746. let firstBattle = e.shift();
  2747. let countWin = wins.reduce((w, s) => w + s);
  2748. let numReval = countRivalsTier - finishListBattle.length;
  2749. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + numReval + '/' + countRivalsTier + ' - ' + countWin + '/11');
  2750. console.log('resultPreCalcBattle', countWin + '/11' )
  2751. if (countWin > 0) {
  2752. attempts = 10;
  2753. } else {
  2754. attempts = 0;
  2755. }
  2756. resultCalcBattle(firstBattle);
  2757. }
  2758.  
  2759. /** Завершить битву на арене */
  2760. function titanArenaEndBattle(args) {
  2761. let calls = [{
  2762. name: "titanArenaEndBattle",
  2763. args,
  2764. ident: "body"
  2765. }];
  2766. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  2767. }
  2768.  
  2769. function resultTitanArenaEndBattle(e) {
  2770. let attackScore = e.results[0].result.response.attackScore;
  2771. let numReval = countRivalsTier - finishListBattle.length;
  2772. setProgress('Турнир Стихий: Уровень ' + currTier + '</br>Бои: ' + numReval + '/' + countRivalsTier + ' - ' + attackScore);
  2773. /** TODO: Возможно стоит сделать улучшение результатов */
  2774. // console.log('resultTitanArenaEndBattle', e)
  2775. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  2776. roundRivals();
  2777. }
  2778. /** Состояние арены */
  2779. function titanArenaGetStatus() {
  2780. let calls = [{
  2781. name: "titanArenaGetStatus",
  2782. args: {},
  2783. ident: "body"
  2784. }];
  2785. send(JSON.stringify({calls}), checkResultInfo);
  2786. }
  2787. /** Запрос рейда арены */
  2788. function titanArenaStartRaid() {
  2789. let calls = [{
  2790. name: "titanArenaStartRaid",
  2791. args: {
  2792. titans: titan_arena
  2793. },
  2794. ident: "body"
  2795. }];
  2796. send(JSON.stringify({calls}), calcResults);
  2797. }
  2798.  
  2799. function calcResults(data) {
  2800. let battlesInfo = data.results[0].result.response;
  2801. let {attackers, rivals} = battlesInfo;
  2802.  
  2803. let promises = [];
  2804. for (let n in rivals) {
  2805. rival = rivals[n];
  2806. promises.push(calcBattleResult({
  2807. attackers: attackers,
  2808. defenders: [rival.team],
  2809. seed: rival.seed,
  2810. typeId: n,
  2811. }));
  2812. }
  2813.  
  2814. Promise.all(promises)
  2815. .then(results => {
  2816. const endResults = {};
  2817. for (let info of results) {
  2818. let id = info.battleData.typeId;
  2819. endResults[id] = {
  2820. progress: info.progress,
  2821. result: info.result,
  2822. }
  2823. }
  2824. titanArenaEndRaid(endResults);
  2825. });
  2826. }
  2827.  
  2828. function calcBattleResult(battleData) {
  2829. return new Promise(function (resolve, reject) {
  2830. BattleCalc(battleData, "get_titanClanPvp", resolve);
  2831. });
  2832. }
  2833.  
  2834. /** Отправка результатов рейда */
  2835. function titanArenaEndRaid(results) {
  2836. titanArenaEndRaidCall = {
  2837. calls: [{
  2838. name: "titanArenaEndRaid",
  2839. args: {
  2840. results
  2841. },
  2842. ident: "body"
  2843. }]
  2844. }
  2845. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  2846. }
  2847.  
  2848. function checkRaidResults(data) {
  2849. results = data.results[0].result.response.results;
  2850. isSucsesRaid = true;
  2851. for (let i in results) {
  2852. isSucsesRaid &&= (results[i].attackScore >= 250);
  2853. }
  2854.  
  2855. if (isSucsesRaid) {
  2856. titanArenaCompleteTier();
  2857. } else {
  2858. titanArenaGetStatus();
  2859. }
  2860. }
  2861.  
  2862. function titanArenaFarmDailyReward() {
  2863. titanArenaFarmDailyRewardCall = {
  2864. calls: [{
  2865. name: "titanArenaFarmDailyReward",
  2866. args: {},
  2867. ident: "body"
  2868. }]
  2869. }
  2870. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  2871. }
  2872.  
  2873. function endTitanArena(reason, info) {
  2874. if (!['Peace_time', 'disabled'].includes(reason)) {
  2875. titanArenaFarmDailyReward();
  2876. }
  2877. console.log(reason, info);
  2878. setProgress('TitanArena completed!', true);
  2879. resolve();
  2880. }
  2881. }
  2882. /** Скрыть прогресс */
  2883. function hideProgress(timeout) {
  2884. timeout = timeout || 0;
  2885. setTimeout(function () {
  2886. scriptMenu.setStatus('');
  2887. popup.hideBack();
  2888. }, timeout);
  2889. }
  2890. /** Отображение прогресса */
  2891. function setProgress(text, hide, onclick) {
  2892. scriptMenu.setStatus(text, onclick);
  2893. hide = hide || false;
  2894. if (hide) {
  2895. hideProgress(3000);
  2896. }
  2897. }
  2898. function hackGame() {
  2899. selfGame = null;
  2900. bindId = 1e9;
  2901. /** Список соответствия используемых классов их названиям */
  2902. ObjectsList = [
  2903. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  2904. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  2905. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  2906. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  2907. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  2908.  
  2909. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  2910. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  2911. {name:"GameModel", prop:"game.model.GameModel"},
  2912. {name:"CommandManager", prop:"game.command.CommandManager"},
  2913. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  2914. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  2915. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  2916. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  2917. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  2918. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  2919. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  2920. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  2921. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  2922. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  2923. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  2924. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  2925. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  2926. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  2927. {name:"SettingToggleButton", prop:"game.view.popup.settings.SettingToggleButton"},
  2928. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  2929. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  2930. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  2931. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  2932. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  2933. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  2934. {name:"BattleConfig", prop:"battle.BattleConfig"},
  2935. {name:"SpecialShopWelcomePopup", prop:"game.view.popup.shop.special.SpecialShopWelcomePopup"},
  2936. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  2937. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  2938. ];
  2939. /** Содержит классы игры необходимые для написания и подмены методов игры */
  2940. Game = {
  2941. /** Функция 'e' */
  2942. bindFunc: function (a, b) {
  2943. if (null == b)
  2944. return null;
  2945. null == b.__id__ && (b.__id__ = bindId++);
  2946. var c;
  2947. null == a.hx__closures__ ? a.hx__closures__ = {} :
  2948. c = a.hx__closures__[b.__id__];
  2949. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  2950. return c
  2951. },
  2952. };
  2953. /** Подключается к объектам игры через событие создания объекта */
  2954. function connectGame() {
  2955. for (let obj of ObjectsList) {
  2956. /**
  2957. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  2958. */
  2959. Object.defineProperty(Object.prototype, obj.prop, {
  2960. set: function (value) {
  2961. if (!selfGame) {
  2962. selfGame = this;
  2963. }
  2964. if (!Game[obj.name]) {
  2965. Game[obj.name] = value;
  2966. }
  2967. // console.log('set ' + obj.prop, this, value);
  2968. this[obj.prop + '_'] = value;
  2969. },
  2970. get: function () {
  2971. // console.log('get ' + obj.prop, this);
  2972. return this[obj.prop + '_'];
  2973. }
  2974. });
  2975. }
  2976. }
  2977. /**
  2978. * Game.BattlePresets
  2979. * @param {bool} a isReplay
  2980. * @param {bool} b autoToggleable
  2981. * @param {bool} c auto On Start
  2982. * @param {object} d config
  2983. * @param {bool} f showBothTeams
  2984. */
  2985. /**
  2986. * Возвращает в функцию callback результаты боя
  2987. * @param {*} battleData данные боя
  2988. * @param {*} battleConfig тип конфигурации боя варианты:
  2989. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  2990. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  2991. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  2992. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  2993. * @param {*} callback функция в которую вернуться результаты боя
  2994. */
  2995. this.BattleCalc = function (battleData, battleConfig, callback) {
  2996. battleConfig = battleConfig || getBattleType(battleData.type)
  2997. if (!Game.BattlePresets) throw Error('Use connectGame');
  2998. battlePresets = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  2999. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  3000. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  3001. battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  3002. battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  3003. callback({
  3004. battleData,
  3005. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  3006. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  3007. })
  3008. });
  3009. battleInstantPlay.start();
  3010. }
  3011.  
  3012. /**
  3013. * Возвращает из класса функцию с указанным именем
  3014. * @param {Object} classF класс
  3015. * @param {String} nameF имя функции
  3016. * @param {String} pos порядок имени и псевдонима
  3017. * @returns
  3018. */
  3019. function getF(classF, nameF, pos) {
  3020. pos = pos || false;
  3021. let prop = Object.entries(classF.prototype.__properties__)
  3022. if (!pos) {
  3023. return prop.filter((e) => e[1] == nameF).pop()[0];
  3024. } else {
  3025. return prop.filter((e) => e[0] == nameF).pop()[1];
  3026. }
  3027. }
  3028.  
  3029. /**
  3030. * Возвращает из класса функцию с указанным именем
  3031. * @param {Object} classF класс
  3032. * @param {String} nameF имя функции
  3033. * @returns
  3034. */
  3035. function getFnP(classF, nameF) {
  3036. let prop = Object.entries(classF.__properties__)
  3037. return prop.filter((e) => e[1] == nameF).pop()[0];
  3038. }
  3039.  
  3040. /**
  3041. * Возвращает имя функции с указаным порядковым номером из класса
  3042. * @param {Object} classF класс
  3043. * @param {Number} nF порядковый номер функции
  3044. * @returns
  3045. */
  3046. function getFn(classF, nF) {
  3047. // let prop = Object.getOwnPropertyNames(classF);
  3048. let prop = Object.keys(classF);
  3049. // let nan = Object.keys(classF).indexOf(prop[nF]);
  3050. // if (nan != nF) {
  3051. // console.log(nan, prop[nF], nF);
  3052. // }
  3053. return prop[nF];
  3054. }
  3055.  
  3056. /**
  3057. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  3058. * @param {Object} classF класс
  3059. * @param {Number} nF порядковый номер функции
  3060. * @returns
  3061. */
  3062. function getProtoFn(classF, nF) {
  3063. // let prop = Object.getOwnPropertyNames(classF.prototype);
  3064. let prop = Object.keys(classF.prototype);
  3065. // let nan = Object.keys(classF.prototype).indexOf(prop[nF]);
  3066. // if (nan != nF) {
  3067. // console.log(nan, prop[nF], nF);
  3068. // }
  3069. return prop[nF];
  3070. }
  3071. /** Описание подменяемых функций */
  3072. replaceFunction = {
  3073. company: function() {
  3074. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  3075. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  3076. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  3077. if (isChecked('passBattle')) {
  3078. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  3079.  
  3080. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  3081. a = new Game.BattleInstantPlay(c, a);
  3082. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  3083. a.start()
  3084. } else {
  3085. oldSkipMisson.call(this, a, b, c);
  3086. }
  3087. }
  3088.  
  3089. Game.PlayerMissionData.prototype.P$h = function (a) {
  3090. let GM_2 = getFn(Game.GameModel, 2);
  3091. let GM_P2 = getProtoFn(Game.GameModel, 2);
  3092. let CM_20 = getProtoFn(Game.CommandManager, 20);
  3093. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  3094. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  3095. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  3096. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  3097. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  3098. }
  3099. },
  3100. tower: function() {
  3101. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  3102. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  3103. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  3104. if (isChecked('passBattle')) {
  3105. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  3106. a = new Game.BattleInstantPlay(a, p);
  3107. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  3108. a.start()
  3109. } else {
  3110. oldSkipTower.call(this, a);;
  3111. }
  3112. }
  3113.  
  3114. Game.PlayerTowerData.prototype.P$h = function (a) {
  3115. let GM_2 = getFn(Game.GameModel, 2);
  3116. let GM_P2 = getProtoFn(Game.GameModel, 2);
  3117. let CM_29 = getProtoFn(Game.CommandManager, 29);
  3118. let TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  3119. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  3120. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  3121. let PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  3122. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]))
  3123. }
  3124. },
  3125. // skipSelectHero: function() {
  3126. // if (!HOST) throw Error('Use connectGame');
  3127. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  3128. // },
  3129. passBattle: function() {
  3130. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  3131. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  3132. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  3133. if (isChecked('passBattle')) {
  3134. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  3135. this[getProtoFn(Game.BattlePausePopup, 3)]();
  3136. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 1)]());
  3137. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabel, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  3138.  
  3139. this.clip[getProtoFn(Game.BattlePausePopupClip, 2)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](Game.Translate.translate("UI_POPUP_BATTLE_RETREAT"), (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 15)]))); /** 14 > 15 */
  3140. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  3141. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 12)](),
  3142. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]() ?
  3143. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) :
  3144. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) /** 15 > 16 */
  3145. );
  3146.  
  3147. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabel, 23)]();
  3148. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 8)]());
  3149. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  3150. } else {
  3151. oldPassBattle.call(this, a);
  3152. }
  3153. }
  3154.  
  3155. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  3156. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  3157. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  3158. if (isChecked('passBattle')) {
  3159. return 'ПРОПУСК';
  3160. } else {
  3161. return oldFunc.call(this);
  3162. }
  3163. }
  3164. },
  3165. endlessCards: function() {
  3166. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  3167. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  3168. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  3169. if (isChecked('endlessCards')) {
  3170. return true;
  3171. } else {
  3172. return oldEndlessCards.call(this);
  3173. }
  3174. }
  3175. },
  3176. speedBattle: function () {
  3177. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  3178. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  3179. Game.BattleController.prototype[get_timeScale] = function () {
  3180. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  3181. if (speedBattle) {
  3182. const BC_11 = getProtoFn(Game.BattleController, 11);
  3183. const BSM_11 = getProtoFn(Game.BattleSettingsModel, 11);
  3184. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  3185. if (this[BC_11][BSM_11][BP_get_value]()) {
  3186. return 0;
  3187. }
  3188. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  3189. const BC_44 = getProtoFn(Game.BattleController, 44);
  3190. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  3191. const BC_13 = getProtoFn(Game.BattleController, 13);
  3192. const BC_3 = getFn(Game.BattleController, 3);
  3193. if (this[BC_11][BSM_2][BP_get_value]()) {
  3194. var a = speedBattle * this[BC_44]();
  3195. } else {
  3196. a = this[BC_11][BSM_1][BP_get_value]();
  3197. const multiple = a == 1 ? speedBattle : this[BC_13][a];
  3198. a = multiple * Game.BattleController[BC_3][BP_get_value]() * this[BC_44]();
  3199. }
  3200. const BSM_22 = getProtoFn(Game.BattleSettingsModel, 22);
  3201. a > this[BC_11][BSM_22][BP_get_value]() && (a = this[BC_11][BSM_22][BP_get_value]());
  3202. const DS_21 = getFn(Game.DataStorage, 21);
  3203. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  3204. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  3205. var b = Game.DataStorage[DS_21][get_battleSpeedMultiplier]();
  3206. const R_1 = getFn(selfGame.Reflect, 1);
  3207. const BC_1 = getFn(Game.BattleController, 1);
  3208. const get_config = getF(Game.BattlePresets, "get_config");
  3209. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  3210. null != b && (a = selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) ? a * selfGame.Reflect[R_1](b, this[BC_1][get_config]().ident) : a * selfGame.Reflect[R_1](b, "default"));
  3211. return a
  3212. } else {
  3213. return oldSpeedBattle.call(this);
  3214. }
  3215. }
  3216. },
  3217. /** Попытка убрать лавку редкойстей */
  3218. // removeWelcomeShop: function () {
  3219. // let SSWP_4 = getProtoFn(Game.SpecialShopWelcomePopup, 1);
  3220. // const oldWelcomeShop = Game.SpecialShopWelcomePopup.prototype[SSWP_4];
  3221. // Game.SpecialShopWelcomePopup.prototype[SSWP_4] = function () {
  3222. // if (true) {
  3223. // return;
  3224. // } else {
  3225. // return oldWelcomeShop.call(this);
  3226. // }
  3227. // }
  3228. // },
  3229. /** Кнопка ускорения без Покровительства Валькирий */
  3230. battleFastKey: function () {
  3231. const BGM_37 = getProtoFn(Game.BattleGuiMediator, 37);
  3232. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_37];
  3233. Game.BattleGuiMediator.prototype[BGM_37] = function () {
  3234. if (true) {
  3235. const BGM_8 = getProtoFn(Game.BattleGuiMediator, 8);
  3236. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  3237. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  3238. this[BGM_8][BPW_0](true);
  3239. this[BGM_9][BPW_0](true);
  3240. } else {
  3241. return oldBattleFastKey.call(this);
  3242. }
  3243. }
  3244. }
  3245. }
  3246. /** Запускает замену записанных функций */
  3247. this.activateHacks = function () {
  3248. if (!selfGame) throw Error('Use connectGame');
  3249. for (let func in replaceFunction) {
  3250. replaceFunction[func]();
  3251. }
  3252. }
  3253. /** Возвращает объект игры */
  3254. this.getSelfGame = function () {
  3255. return selfGame;
  3256. }
  3257. /** Обновляет данные игры */
  3258. this.refreshGame = function () {
  3259. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  3260. }
  3261.  
  3262. /**
  3263. * Сменить экран игры на windowName
  3264. * Возможные варианты:
  3265. * 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
  3266. */
  3267. this.goNavigtor = function (windowName) {
  3268. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  3269. let window = mechanicStorage[windowName];
  3270. let event = selfGame["game.mediator.gui.popup.PopupStashEventParams"]('');
  3271. let Game = selfGame['Game'];
  3272. let navigator = getF(Game, "get_navigator")
  3273. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  3274. let instance = getFnP(Game, 'get_instance');
  3275. Game[instance]()[navigator]()[navigate](window, event);
  3276. }
  3277. /** Переместиться в святилище cheats.goSanctuary() */
  3278. this.goSanctuary = () => {
  3279. this.goNavigtor("SANCTUARY");
  3280. }
  3281. /** Перейти к Войне Гильдий */
  3282. this.goClanWar = function() {
  3283. let instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  3284. let player = selfGame["game.model.GameModel"][instance]().A;
  3285. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  3286. new clanWarSelect(player).open();
  3287. }
  3288.  
  3289. connectGame();
  3290. }
  3291. /** Автосбор подарков */
  3292. function getAutoGifts() {
  3293. let valName = 'giftSendIds_' + userInfo.id;
  3294.  
  3295. if (!localStorage['clearGift' + userInfo.id]) {
  3296. localStorage[valName] = '';
  3297. localStorage['clearGift' + userInfo.id] = '+';
  3298. }
  3299.  
  3300. if (!localStorage[valName]) {
  3301. localStorage[valName] = '';
  3302. }
  3303.  
  3304. /** Отправка запроса для получения кодов подарков */
  3305. fetch('https://zingery.ru/heroes/getGifts.php', {
  3306. method: 'POST',
  3307. body: JSON.stringify({scriptInfo, userInfo})
  3308. }).then(
  3309. response => response.json()
  3310. ).then(
  3311. data => {
  3312. let freebieCheckCalls = {
  3313. calls: []
  3314. }
  3315. data.forEach((giftId, n) => {
  3316. if (localStorage[valName].includes(giftId)) return;
  3317. //localStorage[valName] += ';' + giftId;
  3318. freebieCheckCalls.calls.push({
  3319. name: "freebieCheck",
  3320. args: {
  3321. giftId
  3322. },
  3323. ident: giftId
  3324. });
  3325. });
  3326.  
  3327. if (!freebieCheckCalls.calls.length) {
  3328. return;
  3329. }
  3330.  
  3331. send(JSON.stringify(freebieCheckCalls), e => {
  3332. let countGetGifts = 0;
  3333. const gifts = [];
  3334. for (check of e.results) {
  3335. gifts.push(check.ident);
  3336. if (check.result.response != null) {
  3337. countGetGifts++;
  3338. }
  3339. }
  3340. const saveGifts = localStorage[valName].split(';');
  3341. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  3342. setProgress('Подарки: ' + countGetGifts, true);
  3343. console.log('Подарки: ' + countGetGifts);
  3344. });
  3345. }
  3346. )
  3347. }
  3348. /** Набить килов в горниле душк */
  3349. async function bossRatingEvent() {
  3350. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  3351. if (!topGet) {
  3352. setProgress('Эвент завершен', true);
  3353. return;
  3354. }
  3355. const replayId = topGet.results[0].result.response[0].userData.replayId;
  3356. const result = await Send(JSON.stringify({
  3357. calls: [
  3358. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  3359. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  3360. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  3361. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  3362. ]
  3363. }));
  3364. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  3365. if (!bossEventInfo) {
  3366. setProgress('Эвент завершен', true);
  3367. return;
  3368. }
  3369. const usedHeroes = bossEventInfo.progress.usedHeroes;
  3370. const party = Object.values(result.results[0].result.response.replay.attackers);
  3371. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  3372. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  3373. const calls = [];
  3374. /** Первая пачка */
  3375. const args = {
  3376. heroes: [],
  3377. favor: {}
  3378. }
  3379. for (let hero of party) {
  3380. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  3381. continue;
  3382. }
  3383. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  3384. args.pet = hero.id;
  3385. }
  3386. args.heroes.push(hero.id);
  3387. if (hero.favorPetId) {
  3388. args.favor[hero.id] = hero.favorPetId;
  3389. }
  3390. }
  3391. if (args.heroes.length) {
  3392. calls.push({
  3393. name: "bossRatingEvent_startBattle",
  3394. args,
  3395. ident: "body_0"
  3396. });
  3397. }
  3398. /** Другие пачки */
  3399. let heroes = [];
  3400. let count = 1;
  3401. while (heroId = availableHeroes.pop()) {
  3402. if (args.heroes.includes(heroId) || usedHeroes.includes(hero.id)) {
  3403. continue;
  3404. }
  3405. heroes.push(heroId);
  3406. if (heroes.length == 5) {
  3407. calls.push({
  3408. name: "bossRatingEvent_startBattle",
  3409. args: {
  3410. heroes: [...heroes],
  3411. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  3412. },
  3413. ident: "body_" + count
  3414. });
  3415. heroes = [];
  3416. count++;
  3417. }
  3418. }
  3419.  
  3420. if (!calls.length) {
  3421. setProgress('Нет героев', true);
  3422. return;
  3423. }
  3424.  
  3425. const resultBattles = await Send(JSON.stringify({ calls }));
  3426. console.log(resultBattles);
  3427. rewardBossRatingEvent();
  3428. }
  3429. /** Сбор награды из Горнила Душ */
  3430. function rewardBossRatingEvent() {
  3431. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  3432. send(rewardBossRatingCall, function (data) {
  3433. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  3434. if (!bossEventInfo) {
  3435. setProgress('Эвент завершен', true);
  3436. return;
  3437. }
  3438.  
  3439. let farmedChests = bossEventInfo.progress.farmedChests;
  3440. let score = bossEventInfo.progress.score;
  3441. setProgress('Количество урона: ' + score);
  3442. let revard = bossEventInfo.reward;
  3443.  
  3444. let getRewardCall = {
  3445. calls: []
  3446. }
  3447.  
  3448. let count = 0;
  3449. for (let i = 1; i < 10; i++) {
  3450. if (farmedChests.includes(i)) {
  3451. continue;
  3452. }
  3453. if (score < revard[i].score) {
  3454. break;
  3455. }
  3456. getRewardCall.calls.push({
  3457. name: "bossRatingEvent_getReward",
  3458. args: {
  3459. rewardId: i
  3460. },
  3461. ident: "body_" + i
  3462. });
  3463. count++;
  3464. }
  3465. if (!count) {
  3466. setProgress('Нечего собирать', true);
  3467. return;
  3468. }
  3469.  
  3470. send(JSON.stringify(getRewardCall), e => {
  3471. console.log(e);
  3472. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  3473. });
  3474. });
  3475. }
  3476. /** Собрать пасхалки и награды событий */
  3477. function offerFarmAllReward() {
  3478. let offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  3479. send(offerGetAllCall, function (data) {
  3480. let offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  3481. if (!offerGetAll.length) {
  3482. setProgress('Нечего собирать', true);
  3483. return;
  3484. }
  3485.  
  3486. let rewardListCall = {
  3487. calls: []
  3488. };
  3489. for (let n in offerGetAll) {
  3490. let reward = offerGetAll[n];
  3491. rewardListCall.calls.push({
  3492. name: "offerFarmReward",
  3493. args: {
  3494. offerId: reward.id
  3495. },
  3496. ident: "offerFarmReward_" + reward.id
  3497. });
  3498. }
  3499.  
  3500. send(JSON.stringify(rewardListCall), e => {
  3501. console.log(e);
  3502. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  3503. });
  3504. });
  3505. }
  3506. /** Собрать запределье */
  3507. function getOutland() {
  3508. return new Promise(function (resolve, reject) {
  3509. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  3510. let bosses = e.results[0].result.response;
  3511.  
  3512. let bossRaidOpenChestCall = {
  3513. calls: []
  3514. };
  3515.  
  3516. for (let boss of bosses) {
  3517. if (boss.mayRaid) {
  3518. bossRaidOpenChestCall.calls.push({
  3519. name: "bossRaid",
  3520. args: {
  3521. bossId: boss.id
  3522. },
  3523. ident: "bossRaid_" + boss.id
  3524. });
  3525. bossRaidOpenChestCall.calls.push({
  3526. name: "bossOpenChest",
  3527. args: {
  3528. bossId: boss.id,
  3529. amount: 1,
  3530. starmoney: 0
  3531. },
  3532. ident: "bossOpenChest_" + boss.id
  3533. });
  3534. } else if (boss.chestId == 1) {
  3535. bossRaidOpenChestCall.calls.push({
  3536. name: "bossOpenChest",
  3537. args: {
  3538. bossId: boss.id,
  3539. amount: 1,
  3540. starmoney: 0
  3541. },
  3542. ident: "bossOpenChest_" + boss.id
  3543. });
  3544. }
  3545. }
  3546.  
  3547. if (!bossRaidOpenChestCall.calls.length) {
  3548. setProgress('Запределье уже было собрано', true);
  3549. resolve();
  3550. return;
  3551. }
  3552.  
  3553. send(JSON.stringify(bossRaidOpenChestCall), e => {
  3554. setProgress('Запределье собрано', true);
  3555. resolve();
  3556. });
  3557. });
  3558. });
  3559. }
  3560. /** Собрать все награды */
  3561. function questAllFarm() {
  3562. return new Promise(function (resolve, reject) {
  3563. let questGetAllCall = {
  3564. calls: [{
  3565. name: "questGetAll",
  3566. args: {},
  3567. ident: "body"
  3568. }]
  3569. }
  3570. send(JSON.stringify(questGetAllCall), function (data) {
  3571. let questGetAll = data.results[0].result.response;
  3572. const questAllFarmCall = {
  3573. calls: []
  3574. }
  3575. let number = 0;
  3576. for (let quest of questGetAll) {
  3577. if (quest.id < 1e6 && quest.state == 2) {
  3578. questAllFarmCall.calls.push({
  3579. name: "questFarm",
  3580. args: {
  3581. questId: quest.id
  3582. },
  3583. ident: `group_${number}_body`
  3584. });
  3585. number++;
  3586. }
  3587. }
  3588.  
  3589. if (!questAllFarmCall.calls.length) {
  3590. setProgress('Собрано наград: ' + number, true);
  3591. resolve();
  3592. return;
  3593. }
  3594.  
  3595. send(JSON.stringify(questAllFarmCall), function (res) {
  3596. console.log(res);
  3597. setProgress('Собрано наград: ' + number, true);
  3598. resolve();
  3599. });
  3600. });
  3601. })
  3602. }
  3603.  
  3604. /**
  3605. * Атака прислужников Асгарда
  3606. * @returns
  3607. */
  3608. function testRaidNodes() {
  3609. return new Promise((resolve, reject) => {
  3610. const tower = new executeRaidNodes(resolve, reject);
  3611. tower.start();
  3612. });
  3613. }
  3614.  
  3615. /** Атака прислужников Асгарда */
  3616. function executeRaidNodes(resolve, reject) {
  3617. let raidData = {
  3618. teams: [],
  3619. favor: {},
  3620. nodes: [],
  3621. attempts: 0,
  3622. countExecuteBattles: 0,
  3623. cancelBattle: 0,
  3624. }
  3625.  
  3626. callsExecuteRaidNodes = {
  3627. calls: [{
  3628. name: "clanRaid_getInfo",
  3629. args: {},
  3630. ident: "clanRaid_getInfo"
  3631. }, {
  3632. name: "teamGetAll",
  3633. args: {},
  3634. ident: "teamGetAll"
  3635. }, {
  3636. name: "teamGetFavor",
  3637. args: {},
  3638. ident: "teamGetFavor"
  3639. }]
  3640. }
  3641.  
  3642. this.start = function () {
  3643. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  3644. }
  3645.  
  3646. function startRaidNodes(data) {
  3647. res = data.results;
  3648. clanRaidInfo = res[0].result.response;
  3649. teamGetAll = res[1].result.response;
  3650. teamGetFavor = res[2].result.response;
  3651.  
  3652. let index = 0;
  3653. for (let team of teamGetAll.clanRaid_nodes) {
  3654. raidData.teams.push({
  3655. data: {},
  3656. heroes: team.filter(id => id < 6000),
  3657. pet: team.filter(id => id >= 6000).pop(),
  3658. battleIndex: index++
  3659. });
  3660. }
  3661. raidData.favor = teamGetFavor.clanRaid_nodes;
  3662.  
  3663. raidData.nodes = clanRaidInfo.nodes;
  3664. raidData.attempts = clanRaidInfo.attempts;
  3665. isCancalBattle = false;
  3666.  
  3667. checkNodes();
  3668. }
  3669.  
  3670. function getAttackNode() {
  3671. for (let nodeId in raidData.nodes) {
  3672. let node = raidData.nodes[nodeId];
  3673. let points = 0
  3674. for (team of node.teams) {
  3675. points += team.points;
  3676. }
  3677. let now = Date.now() / 1000;
  3678. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  3679. let countTeam = node.teams.length;
  3680. delete raidData.nodes[nodeId];
  3681. return {
  3682. nodeId,
  3683. countTeam
  3684. };
  3685. }
  3686. }
  3687. return null;
  3688. }
  3689.  
  3690. function checkNodes() {
  3691. setProgress('Осталось попыток: ' + raidData.attempts);
  3692. let nodeInfo = getAttackNode();
  3693. if (nodeInfo && raidData.attempts) {
  3694. startNodeBattles(nodeInfo);
  3695. return;
  3696. }
  3697.  
  3698. endRaidNodes('EndRaidNodes');
  3699. }
  3700.  
  3701. function startNodeBattles(nodeInfo) {
  3702. let {nodeId, countTeam} = nodeInfo;
  3703. let teams = raidData.teams.slice(0, countTeam);
  3704. let heroes = raidData.teams.map(e => e.heroes).flat();
  3705. let favor = {...raidData.favor};
  3706. for (let heroId in favor) {
  3707. if (!heroes.includes(+heroId)) {
  3708. delete favor[heroId];
  3709. }
  3710. }
  3711.  
  3712. let calls = [{
  3713. name: "clanRaid_startNodeBattles",
  3714. args: {
  3715. nodeId,
  3716. teams,
  3717. favor
  3718. },
  3719. ident: "body"
  3720. }];
  3721.  
  3722. send(JSON.stringify({calls}), resultNodeBattles);
  3723. }
  3724.  
  3725. function resultNodeBattles(e) {
  3726. if (e['error']) {
  3727. endRaidNodes('nodeBattlesError', e['error']);
  3728. return;
  3729. }
  3730.  
  3731. console.log(e);
  3732. let battles = e.results[0].result.response.battles;
  3733. let promises = [];
  3734. let battleIndex = 0;
  3735. for (let battle of battles) {
  3736. battle.battleIndex = battleIndex++;
  3737. promises.push(calcBattleResult(battle));
  3738. }
  3739.  
  3740. Promise.all(promises)
  3741. .then(results => {
  3742. const endResults = {};
  3743. let isAllWin = true;
  3744. for (let r of results) {
  3745. isAllWin &&= r.result.win;
  3746. }
  3747. if (!isAllWin) {
  3748. cancelEndNodeBattle(results[0]);
  3749. return;
  3750. }
  3751. raidData.countExecuteBattles = results.length;
  3752. let timeout = 500;
  3753. for (let r of results) {
  3754. setTimeout(endNodeBattle, timeout, r);
  3755. timeout += 500;
  3756. }
  3757. });
  3758. }
  3759. /** Возвращает промис расчета боя */
  3760. function calcBattleResult(battleData) {
  3761. return new Promise(function (resolve, reject) {
  3762. BattleCalc(battleData, "get_clanPvp", resolve);
  3763. });
  3764. }
  3765. /** Отменяет бой */
  3766. function cancelEndNodeBattle(r) {
  3767. const fixBattle = function (heroes) {
  3768. for (const ids in heroes) {
  3769. hero = heroes[ids];
  3770. hero.energy = random(1, 999);
  3771. if (hero.hp > 0) {
  3772. hero.hp = random(1, hero.hp);
  3773. }
  3774. }
  3775. }
  3776. fixBattle(r.progress[0].attackers.heroes);
  3777. fixBattle(r.progress[0].defenders.heroes);
  3778. endNodeBattle(r);
  3779. }
  3780. /** Завершает бой */
  3781. function endNodeBattle(r) {
  3782. let nodeId = r.battleData.result.nodeId;
  3783. let battleIndex = r.battleData.battleIndex;
  3784. let calls = [{
  3785. name: "clanRaid_endNodeBattle",
  3786. args: {
  3787. nodeId,
  3788. battleIndex,
  3789. result: r.result,
  3790. progress: r.progress
  3791. },
  3792. ident: "body"
  3793. }]
  3794.  
  3795. SendRequest(JSON.stringify({calls}), battleResult);
  3796. }
  3797. /** Обработка результатов боя */
  3798. function battleResult(e) {
  3799. if (e['error']) {
  3800. endRaidNodes('missionEndError', e['error']);
  3801. return;
  3802. }
  3803. r = e.results[0].result.response;
  3804. if (r['error']) {
  3805. if (r.reason == "invalidBattle") {
  3806. raidData.cancelBattle++;
  3807. checkNodes();
  3808. } else {
  3809. endRaidNodes('missionEndError', e['error']);
  3810. }
  3811. return;
  3812. }
  3813.  
  3814. if (!(--raidData.countExecuteBattles)) {
  3815. raidData.attempts--;
  3816. checkNodes();
  3817. }
  3818. }
  3819. /** Завершение задачи */
  3820. function endRaidNodes(reason, info) {
  3821. isCancalBattle = true;
  3822. let textCancel = raidData.cancelBattle ? ' Битв отменено: ' + raidData.cancelBattle : '';
  3823. setProgress('Рейд прислужников завершен!' + textCancel, true);
  3824. console.log(reason, info);
  3825. resolve();
  3826. }
  3827. }
  3828. /**
  3829. * Автоповтор миссии
  3830. * isStopSendMission = false;
  3831. * isSendsMission = true;
  3832. **/
  3833. this.sendsMission = async function (param) {
  3834. if (isStopSendMission) {
  3835. isSendsMission = false;
  3836. console.log('Остановлено');
  3837. setProgress('');
  3838. await popup.confirm('Остановлено<br>Повторений: ' + param.count, [{
  3839. msg: 'Ok',
  3840. result: true
  3841. }, ])
  3842. return;
  3843. }
  3844.  
  3845. let missionStartCall = {
  3846. "calls": [{
  3847. "name": "missionStart",
  3848. "args": lastMissionStart,
  3849. "ident": "body"
  3850. }]
  3851. }
  3852. // Запрос на выполнение мисии
  3853. SendRequest(JSON.stringify(missionStartCall), async e => {
  3854. if (e['error']) {
  3855. isSendsMission = false;
  3856. console.log(e['error']);
  3857. setProgress('');
  3858. let msg = e['error'].name + ' ' + e['error'].description + '<br>Повторений: ' + param.count;
  3859. await popup.confirm(msg, [
  3860. {msg: 'Ok', result: true},
  3861. ])
  3862. return;
  3863. }
  3864. // Расчет данных мисии
  3865. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  3866.  
  3867. let missionEndCall = {
  3868. "calls": [{
  3869. "name": "missionEnd",
  3870. "args": {
  3871. "id": param.id,
  3872. "result": r.result,
  3873. "progress": r.progress
  3874. },
  3875. "ident": "body"
  3876. }]
  3877. }
  3878. // Запрос на завершение миссии
  3879. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  3880. if (e['error']) {
  3881. isSendsMission = false;
  3882. console.log(e['error']);
  3883. setProgress('');
  3884. let msg = e['error'].name + ' ' + e['error'].description + '<br>Повторений: ' + param.count;
  3885. await popup.confirm(msg, [
  3886. {msg: 'Ok', result: true},
  3887. ])
  3888. return;
  3889. }
  3890. r = e.results[0].result.response;
  3891. if (r['error']) {
  3892. isSendsMission = false;
  3893. console.log(r['error']);
  3894. setProgress('');
  3895. await popup.confirm('Повторений: ' + param.count + ' 3 ' + r['error'], [
  3896. {msg: 'Ok', result: true},
  3897. ])
  3898. return;
  3899. }
  3900.  
  3901. param.count++;
  3902. setProgress('Миссий пройдено: ' + param.count + ' (остановить)', false, () => {
  3903. isStopSendMission = true;
  3904. });
  3905. setTimeout(sendsMission, 1, param);
  3906. });
  3907. })
  3908. });
  3909. }
  3910. /** Рекурсивное открытие матрешек */
  3911. function openRussianDoll(id, count, sum) {
  3912. sum = sum || 0;
  3913. sum += count;
  3914. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  3915. setProgress('Открыто ' + count, true);
  3916. let result = e.results[0].result.response;
  3917. let newCount = 0;
  3918. for(let n of result) {
  3919. if (n?.consumable && n.consumable[id]) {
  3920. newCount += n.consumable[id]
  3921. }
  3922. }
  3923. if (newCount) {
  3924. openRussianDoll(id, newCount, sum);
  3925. } else {
  3926. popup.confirm('Всего открыто ' + sum);
  3927. }
  3928. })
  3929. }
  3930.  
  3931. function testBossBattle() {
  3932. return new Promise((resolve, reject) => {
  3933. const bossBattle = new executeBossBattle(resolve, reject);
  3934. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  3935. });
  3936. }
  3937.  
  3938. /** Повтор атаки босса Асгарда */
  3939. function executeBossBattle(resolve, reject) {
  3940. let lastBossBattleArgs = {};
  3941. let reachDamage = 0;
  3942. let countBattle = 0;
  3943. let countMaxBattle = 10;
  3944. let lastDamage = 0;
  3945.  
  3946. this.start = function (battleArg, battleInfo) {
  3947. lastBossBattleArgs = battleArg;
  3948. preCalcBattle(battleInfo);
  3949. }
  3950.  
  3951. function getBattleInfo(battle) {
  3952. return new Promise(function (resolve) {
  3953. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  3954. BattleCalc(battle, getBattleType(battle.type), e => {
  3955. let extra = e.progress[0].defenders.heroes[1].extra;
  3956. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  3957. });
  3958. });
  3959. }
  3960.  
  3961. function preCalcBattle(battle) {
  3962. let actions = [];
  3963. const countTestBattle = getInput('countTestBattle');
  3964. for (let i = 0; i < countTestBattle; i++) {
  3965. actions.push(getBattleInfo(battle, true));
  3966. }
  3967. Promise.all(actions)
  3968. .then(resultPreCalcBattle);
  3969. }
  3970.  
  3971. function fixDamage(damage) {
  3972. for (let i = 1e6; i > 1; i /= 10) {
  3973. if (damage > i) {
  3974. let n = i / 10;
  3975. damage = Math.ceil(damage / n) * n;
  3976. break;
  3977. }
  3978. }
  3979. return damage;
  3980. }
  3981.  
  3982. async function resultPreCalcBattle(damages) {
  3983. let maxDamage = 0;
  3984. let minDamage = 1e10;
  3985. let avgDamage = 0;
  3986. for (let damage of damages) {
  3987. avgDamage += damage
  3988. if (damage > maxDamage) {
  3989. maxDamage = damage;
  3990. }
  3991. if (damage < minDamage) {
  3992. minDamage = damage;
  3993. }
  3994. }
  3995. avgDamage /= damages.length;
  3996. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  3997.  
  3998. reachDamage = fixDamage(avgDamage);
  3999. const result = await popup.confirm(
  4000. 'Статистика урона:' +
  4001. '<br>Минимальный: ' + minDamage.toLocaleString() +
  4002. '<br>Максимальный: ' + maxDamage.toLocaleString() +
  4003. '<br>Средний: ' + avgDamage.toLocaleString() +
  4004. '<br>Поиск урона больше чем ' + reachDamage.toLocaleString(), [
  4005. {msg: 'Отмена', result: 0},
  4006. {msg: 'Погнали', isInput: true, default: reachDamage},
  4007. ])
  4008. if (result) {
  4009. reachDamage = result;
  4010. isCancalBossBattle = false;
  4011. startBossBattle();
  4012. return;
  4013. }
  4014. endBossBattle('Отмена');
  4015. }
  4016.  
  4017. function startBossBattle() {
  4018. countBattle++;
  4019. countMaxBattle = getInput('countAutoBattle');
  4020. if (countBattle > countMaxBattle) {
  4021. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  4022. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  4023. return;
  4024. }
  4025. let calls = [{
  4026. name: "clanRaid_startBossBattle",
  4027. args: lastBossBattleArgs,
  4028. ident: "body"
  4029. }];
  4030. send(JSON.stringify({calls}), calcResultBattle);
  4031. }
  4032.  
  4033. function calcResultBattle(e) {
  4034. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  4035. }
  4036.  
  4037. async function resultBattle(e) {
  4038. let extra = e.progress[0].defenders.heroes[1].extra
  4039. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  4040. console.log(resultDamage);
  4041. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  4042. lastDamage = resultDamage;
  4043. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  4044. {msg: 'Ок', result: true},
  4045. {msg: 'Не пойдет', result: false},
  4046. ])) {
  4047. endBattle(e, false);
  4048. return;
  4049. }
  4050. cancelEndBattle(e);
  4051. }
  4052.  
  4053. function cancelEndBattle (r) {
  4054. const fixBattle = function (heroes) {
  4055. for (const ids in heroes) {
  4056. hero = heroes[ids];
  4057. hero.energy = random(1, 999);
  4058. if (hero.hp > 0) {
  4059. hero.hp = random(1, hero.hp);
  4060. }
  4061. }
  4062. }
  4063. fixBattle(r.progress[0].attackers.heroes);
  4064. fixBattle(r.progress[0].defenders.heroes);
  4065. endBattle(r, true);
  4066. }
  4067.  
  4068. function endBattle(battleResult, isCancal) {
  4069. let calls = [{
  4070. name: "clanRaid_endBossBattle",
  4071. args: {
  4072. result: battleResult.result,
  4073. progress: battleResult.progress
  4074. },
  4075. ident: "body"
  4076. }];
  4077.  
  4078. send(JSON.stringify({calls}), e => {
  4079. console.log(e);
  4080. if (isCancal) {
  4081. startBossBattle();
  4082. return;
  4083. }
  4084. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  4085. setTimeout(() => {
  4086. scriptMenu.setStatus('');
  4087. }, 5000);
  4088. endBossBattle('Узпех!');
  4089. });
  4090. }
  4091.  
  4092. /** Завершение задачи */
  4093. function endBossBattle(reason, info) {
  4094. isCancalBossBattle = true;
  4095. console.log(reason, info);
  4096. resolve();
  4097. }
  4098. }
  4099.  
  4100. function testAutoBattle() {
  4101. return new Promise((resolve, reject) => {
  4102. const bossBattle = new executeAutoBattle(resolve, reject);
  4103. bossBattle.start(lastBattleArg, lastBattleInfo);
  4104. });
  4105. }
  4106.  
  4107. /** Автоповтор атаки */
  4108. function executeAutoBattle(resolve, reject) {
  4109. let battleArg = {};
  4110. let countBattle = 0;
  4111. let countMaxBattle = 10;
  4112.  
  4113. this.start = function (battleArgs, battleInfo) {
  4114. battleArg = battleArgs;
  4115. preCalcBattle(battleInfo);
  4116. }
  4117. /** Возвращает промис для прерасчета боя */
  4118. function getBattleInfo(battle) {
  4119. return new Promise(function (resolve) {
  4120. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  4121. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  4122. });
  4123. }
  4124. /** Прерасчет боя */
  4125. function preCalcBattle(battle) {
  4126. let actions = [];
  4127. const countTestBattle = getInput('countTestBattle');
  4128. for (let i = 0; i < countTestBattle; i++) {
  4129. actions.push(getBattleInfo(battle));
  4130. }
  4131. Promise.all(actions)
  4132. .then(resultPreCalcBattle);
  4133. }
  4134. /** Обработка результатов прерасчета боя */
  4135. function resultPreCalcBattle(results) {
  4136. let countWin = results.reduce((w, s) => w + s);
  4137. if (countWin > 0) {
  4138. isCancalBattle = false;
  4139. startBattle();
  4140. return;
  4141. }
  4142. setProgress('Не судьба, шансы 0', true);
  4143. endAutoBattle('Не в этот раз');
  4144. }
  4145. /** Начало боя */
  4146. function startBattle() {
  4147. countBattle++;
  4148. countMaxBattle = getInput('countAutoBattle');
  4149. setProgress(countBattle + '/' + countMaxBattle);
  4150. if (countBattle > countMaxBattle) {
  4151. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  4152. endAutoBattle('Превышен лимит попыток: ' + countMaxBattle)
  4153. return;
  4154. }
  4155. let calls = [{
  4156. name: nameFuncStartBattle,
  4157. args: battleArg,
  4158. ident: "body"
  4159. }];
  4160. send(JSON.stringify({
  4161. calls
  4162. }), calcResultBattle);
  4163. }
  4164. /** Расчет боя */
  4165. function calcResultBattle(e) {
  4166. let battle = e.results[0].result.response.battle
  4167. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  4168. }
  4169. /** Обработка результатов боя */
  4170. function resultBattle(e) {
  4171. let isWin = e.result.win;
  4172. console.log(isWin);
  4173. if (isWin) {
  4174. endBattle(e, false);
  4175. return;
  4176. }
  4177. cancelEndBattle(e);
  4178. }
  4179. /** Отмена боя */
  4180. function cancelEndBattle(r) {
  4181. const fixBattle = function (heroes) {
  4182. for (const ids in heroes) {
  4183. hero = heroes[ids];
  4184. hero.energy = random(1, 999);
  4185. if (hero.hp > 0) {
  4186. hero.hp = random(1, hero.hp);
  4187. }
  4188. }
  4189. }
  4190. fixBattle(r.progress[0].attackers.heroes);
  4191. fixBattle(r.progress[0].defenders.heroes);
  4192. endBattle(r, true);
  4193. }
  4194. /** Завершение боя */
  4195. function endBattle(battleResult, isCancal) {
  4196. let calls = [{
  4197. name: nameFuncEndBattle,
  4198. args: {
  4199. result: battleResult.result,
  4200. progress: battleResult.progress
  4201. },
  4202. ident: "body"
  4203. }];
  4204.  
  4205. send(JSON.stringify({
  4206. calls
  4207. }), e => {
  4208. console.log(e);
  4209. if (isCancal) {
  4210. startBattle();
  4211. return;
  4212. }
  4213. scriptMenu.setStatus('Победа!');
  4214. setTimeout(() => {
  4215. scriptMenu.setStatus('');
  4216. }, 5000)
  4217. endAutoBattle('Успех!')
  4218. });
  4219. }
  4220. /** Завершение задачи */
  4221. function endAutoBattle(reason, info) {
  4222. isCancalBattle = true;
  4223. console.log(reason, info);
  4224. resolve();
  4225. }
  4226. }
  4227. /** Собрать всю почту, кроме писем с энергией и зарядами портала */
  4228. function mailGetAll() {
  4229. let getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  4230. let getLetters = '{"calls":[{"name":"mailFarm","args":{"letterIds":[#letterIds#]},"ident":"body"}]}';
  4231.  
  4232. send(getMailInfo, function(res) {
  4233. let dataMail = getJson(res);
  4234. if (!dataMail) return;
  4235. let letters = dataMail?.results[0]?.result?.response?.letters;
  4236. lettersIds = [];
  4237. for (let l in letters) {
  4238. letter = letters[l];
  4239. const reward = letter.reward;
  4240. /** Исключения на сбор писем */
  4241. const isFarmLetter = !(
  4242. (reward?.refillable ? reward.refillable[45] : false) || // сферы портала
  4243. (reward?.stamina ? reward.stamina : false) || // энергия
  4244. (reward?.buff ? true : false) || // ускорение набора энергии
  4245. (reward?.vipPoints ? reward.vipPoints : false) || // вип очки
  4246. (reward?.fragmentHero ? true : false) // душы героев
  4247. );
  4248. if (isFarmLetter) {
  4249. lettersIds.push(~~letter.id);
  4250. }
  4251. }
  4252. if (lettersIds.length) {
  4253. sendGetLetters = getLetters.replace('#letterIds#', lettersIds.join())
  4254. send(sendGetLetters, function(res) {
  4255. lettersIds = res?.results[0]?.result?.response;
  4256. if (lettersIds) {
  4257. countLetters = Object.keys(lettersIds).length;
  4258. setProgress('Получено ' + countLetters + ' писем', true);
  4259. console.log('mailGetAll', lettersIds);
  4260. }
  4261. });
  4262. } else {
  4263. setProgress('Нечего собирать', true);
  4264. }
  4265. });
  4266. }
  4267. })();
  4268.  
  4269. /**
  4270. * TODO:
  4271. * Автосбор дара валькирий и других ежедневных наград
  4272. * Получение всех уровней при сборе всех наград (квест на титанит и на энку)
  4273. * Возможность указать любое число при открытии артефактных сундуков
  4274. * Добивание на арене титанов
  4275. */