HeroWarsHelper

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

目前为 2023-05-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HeroWarsHelper
  3. // @name:en HeroWarsHelper
  4. // @namespace HeroWarsHelper
  5. // @version 2.064
  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. const questsInfo = {};
  34. /** Загружены ли данные игры */
  35. let isLoadGame = false;
  36. /** Заголовки последнего запроса */
  37. let lastHeaders = {};
  38. /** Информация об отправленных подарках */
  39. let freebieCheckInfo = null;
  40. /** Данные пользователя */
  41. let userInfo;
  42. /** Оригинальные методы для работы с AJAX */
  43. const original = {
  44. open: XMLHttpRequest.prototype.open,
  45. send: XMLHttpRequest.prototype.send,
  46. setRequestHeader: XMLHttpRequest.prototype.setRequestHeader,
  47. };
  48. /** Декодер для перобразования байтовых данных в JSON строку */
  49. const decoder = new TextDecoder("utf-8");
  50. /** Хранит историю запросов */
  51. let requestHistory = {};
  52. /** URL для запросов к API */
  53. let apiUrl = '';
  54.  
  55. /** Подключение к коду игры */
  56. this.cheats = new hackGame();
  57. /** Функция расчета результатов боя */
  58. this.BattleCalc = cheats.BattleCalc;
  59. /** Отправка запроса доступная через консоль */
  60. this.SendRequest = send;
  61. /** Простой расчет боя доступный через консоль */
  62. this.Calc = function (data) {
  63. const type = getBattleType(data?.type);
  64. return new Promise((resolve, reject) => {
  65. try {
  66. BattleCalc(data, type, resolve);
  67. } catch (e) {
  68. reject(e);
  69. }
  70. })
  71. }
  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. cancelBattleBan: {
  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. /** Костыль чтоб получать поле до получения id персонажа */
  142. default: (() => {
  143. $result = false;
  144. try {
  145. $result = JSON.parse(localStorage[GM_info.script.name + ':noOfferDonat'])
  146. } catch(e) {
  147. $result = false;
  148. }
  149. return $result || false;
  150. })(),
  151. },
  152. dailyQuests: {
  153. label: 'Ежедневные квесты',
  154. cbox: null,
  155. title: 'Выполнять ежедневные квесты',
  156. default: false
  157. }
  158. /*
  159. getAnswer: {
  160. label: 'АвтоВикторина',
  161. cbox: null,
  162. title: 'Автоматическое получение возможно правильных ответов на вопросы викторины',
  163. default: false
  164. }
  165. */
  166. };
  167. /** Получить состояние чекбокса */
  168. function isChecked(checkBox) {
  169. return checkboxes[checkBox].cbox?.checked;
  170. }
  171. /** Поля ввода */
  172. const inputs = {
  173. countTitanit: {
  174. input: null,
  175. title: 'Сколько фармим титанита',
  176. default: 150,
  177. },
  178. speedBattle: {
  179. input: null,
  180. title: 'Множитель ускорения боя',
  181. default: 5,
  182. },
  183. countTestBattle: {
  184. input: null,
  185. title: 'Количество тестовых боев',
  186. default: 10,
  187. },
  188. countAutoBattle: {
  189. input: null,
  190. title: 'Количество попыток автобоев',
  191. default: 10,
  192. }
  193. }
  194. /** Поплучить данные поля ввода */
  195. function getInput(inputName) {
  196. return inputs[inputName].input.value;
  197. }
  198. /** Список кнопочек */
  199. const buttons = {
  200. getOutland: {
  201. name: 'Сделать все',
  202. title: 'Выполнить несколько действий',
  203. func: testDoYourBest,
  204. },
  205. /*
  206. getOutland: {
  207. name: 'Запределье',
  208. title: 'Собрать Запределье',
  209. func: function () {
  210. confShow('Запустить скрипт Запределье?', getOutland);
  211. },
  212. },
  213. */
  214. testTitanArena: {
  215. name: 'Турнир Стихий',
  216. title: 'Автопрохождение Турнира Стихий',
  217. func: function () {
  218. confShow('Запустить скрипт Турнир Стихий?', testTitanArena);
  219. },
  220. },
  221. testDungeon: {
  222. name: 'Подземелье',
  223. title: 'Автопрохождение подземелья',
  224. func: function () {
  225. confShow('Запустить скрипт Подземелье?', testDungeon);
  226. },
  227. },
  228. /*
  229. testTower: {
  230. name: 'Башня',
  231. title: 'Автопрохождение башни',
  232. func: function () {
  233. confShow('Запустить скрипт Башня?', testTower);
  234. },
  235. },
  236. */
  237. sendExpedition: {
  238. name: 'Экспедиции',
  239. title: 'Отправка и сбор экспедиций',
  240. func: function () {
  241. confShow('Запустить скрипт Экспедиции?', checkExpedition);
  242. },
  243. },
  244. newDay: {
  245. name: 'Синхронизация',
  246. title: 'Частичная синхронизация данных игры без перезагрузки сатраницы',
  247. func: function () {
  248. confShow('Запустить скрипт Синхронизация?', cheats.refreshGame);
  249. },
  250. },
  251. /*
  252. bossRatingEvent: {
  253. name: 'Архидемон',
  254. title: 'Набивает килы и собирает награду',
  255. func: function () {
  256. confShow('Запустить скрипт Архидемон?', bossRatingEvent);
  257. },
  258. },
  259. */
  260. /*
  261. offerFarmAllReward: {
  262. name: 'Пасхалки',
  263. title: 'Собрать все пасхалки или награды',
  264. func: function () {
  265. confShow('Запустить скрипт Пасхалки?', offerFarmAllReward);
  266. },
  267. },
  268. */
  269. questAllFarm: {
  270. name: 'Награды',
  271. title: 'Собрать все награды за задания',
  272. func: function () {
  273. confShow('Запустить скрипт Награды?', questAllFarm);
  274. },
  275. },
  276. mailGetAll: {
  277. name: 'Почта',
  278. title: 'Собрать всю почту, кроме писем с энергией и зарядами портала',
  279. func: function () {
  280. confShow('Запустить скрипт Почта?', mailGetAll);
  281. },
  282. },
  283. testRaidNodes: {
  284. name: 'Прислужники',
  285. title: 'Атакует прислужников сохраннеными пачками',
  286. func: function () {
  287. confShow('Запустить скрипт Прислужники?', testRaidNodes);
  288. },
  289. },
  290. testAdventure: {
  291. name: 'Приключение',
  292. title: 'Проходит приключение по указанному маршруту',
  293. func: () => {
  294. testAdventure();
  295. },
  296. },
  297. /*
  298. testSoloAdventure: {
  299. name: 'Буря',
  300. title: 'Проходит Бурю по указанному маршруту',
  301. func: () => {
  302. testAdventure('solo');
  303. },
  304. },
  305. */
  306. goToSanctuary: {
  307. name: 'Святилище',
  308. title: 'Быстрый переход к Святилищу',
  309. func: cheats.goSanctuary,
  310. },
  311. goToClanWar: {
  312. name: 'Война гильдий',
  313. title: 'Быстрый переход к Войне гильдий',
  314. func: cheats.goClanWar,
  315. },
  316. }
  317. /** Вывести кнопочки */
  318. function addControlButtons() {
  319. for (let name in buttons) {
  320. button = buttons[name];
  321. button['button'] = scriptMenu.addButton(button.name, button.func, button.title);
  322. }
  323. }
  324. /** Добавляет ссылки */
  325. function addBottomUrls() {
  326. scriptMenu.addHeader('<a href="https://t.me/+q6gAGCRpwyFkNTYy" target="_blank">tg</a> <a href="https://vk.com/invite/YNPxKGX" target="_blank">vk</a>');
  327. }
  328. /** Остановить повтор миссии */
  329. let isStopSendMission = false;
  330. /** Идет повтор миссии */
  331. let isSendsMission = false;
  332. /** Данные о прошедшей мисии */
  333. let lastMissionStart = {}
  334.  
  335. /** Данные о прошедшей атаке на босса */
  336. let lastBossBattle = {}
  337. /** Данные для расчете последнего боя с боссом */
  338. let lastBossBattleInfo = null;
  339. /** Возможность отменить бой в Астгарде */
  340. let isCancalBossBattle = true;
  341. /** Данные о прошедшей битве */
  342. let lastBattleArg = {}
  343. /** Имя функции начала боя */
  344. let nameFuncStartBattle = '';
  345. /** Имя функции конца боя */
  346. let nameFuncEndBattle = '';
  347. /** Данные для расчете последнего боя */
  348. let lastBattleInfo = null;
  349. /** Возможность отменить бой */
  350. let isCancalBattle = true;
  351.  
  352. /** Идетификатор последней открытой матрешки */
  353. let lastRussianDollId = null;
  354. /** Отменить обучающее руководство */
  355. this.isCanceledTutorial = false;
  356.  
  357. /** Данные последнего вопроса викторины */
  358. let lastQuestion = null;
  359. /** Ответ на последний вопрос викторины */
  360. let lastAnswer = null;
  361. /** Флаг открытия ключей или сфер артефактов титанов */
  362. let artifactChestOpen = false;
  363. /** Имя функции открытия ключей или сфер артефактов титанов */
  364. let artifactChestOpenCallName = '';
  365.  
  366. /**
  367. * Копирует тест в буфер обмена
  368. * @param {*} text копируемый текст
  369. */
  370. function copyText(text) {
  371. let copyTextarea = document.createElement("textarea");
  372. copyTextarea.style.opacity = "0";
  373. copyTextarea.textContent = text;
  374. document.body.appendChild(copyTextarea);
  375. copyTextarea.select();
  376. document.execCommand("copy");
  377. document.body.removeChild(copyTextarea);
  378. delete copyTextarea;
  379. }
  380. /** Возвращает историю запросов */
  381. this.getRequestHistory = function() {
  382. return requestHistory;
  383. }
  384. /** Гененирует случайное целое число от min до max */
  385. const random = function (min, max) {
  386. return Math.floor(Math.random() * (max - min + 1) + min);
  387. }
  388. /** Очистка истоии запросов */
  389. setInterval(function () {
  390. let now = Date.now();
  391. for (let i in requestHistory) {
  392. if (now - i > 300000) {
  393. delete requestHistory[i];
  394. }
  395. }
  396. }, 300000);
  397. /** Событие загрузки DOM дерева страницы */
  398. document.addEventListener("DOMContentLoaded", () => {
  399. /** Возвращаем нормальный размер игровому окну */
  400. const style = document.createElement('style');
  401. style.innerText = "#flash-wrapper{max-width:1000px !important;max-height:640px !important;}";
  402. document.head.appendChild(style);
  403. /** Создание интерфеса скрипта */
  404. createInterface();
  405. });
  406. /** Сбор и отправка кодов подарков */
  407. function sendCodes() {
  408. let codes = [], count = 0;
  409. if (!localStorage['giftSendIds']) {
  410. localStorage['giftSendIds'] = '';
  411. }
  412. document.querySelectorAll('a[target="_blank"]').forEach(e => {
  413. let url = e?.href;
  414. if (!url) return;
  415. url = new URL(url);
  416. let giftId = url.searchParams.get('gift_id');
  417. if (!giftId || localStorage['giftSendIds'].includes(giftId)) return;
  418. localStorage['giftSendIds'] += ';' + giftId;
  419. codes.push(giftId);
  420. count++;
  421. });
  422.  
  423. if (codes.length) {
  424. localStorage['giftSendIds'] = localStorage['giftSendIds'].split(';').splice(-50).join(';');
  425. sendGiftsCodes(codes);
  426. }
  427.  
  428. if (!count) {
  429. setTimeout(sendCodes, 2000);
  430. }
  431. }
  432. /** Проверка отправленных кодов */
  433. function checkSendGifts() {
  434. if (!freebieCheckInfo) {
  435. return;
  436. }
  437.  
  438. let giftId = freebieCheckInfo.args.giftId;
  439. let valName = 'giftSendIds_' + userInfo.id;
  440. localStorage[valName] = localStorage[valName] ?? '';
  441. if (!localStorage[valName].includes(giftId)) {
  442. localStorage[valName] += ';' + giftId;
  443. sendGiftsCodes([giftId]);
  444. }
  445. }
  446. /** Отправка кодов */
  447. function sendGiftsCodes(codes) {
  448. fetch('https://zingery.ru/heroes/setGifts.php', {
  449. method: 'POST',
  450. body: JSON.stringify(codes)
  451. }).then(
  452. response => response.json()
  453. ).then(
  454. data => {
  455. if (data.result) {
  456. console.log('Подарки отправлены!');
  457. }
  458. }
  459. )
  460. }
  461. /** Отображает диалоговое окно */
  462. function confShow(message, yesCallback, noCallback) {
  463. let buts = [];
  464. message = message || "Вы действительно хотите это сделать?";
  465. noCallback = noCallback || (() => {});
  466. if (yesCallback) {
  467. buts = [
  468. {msg: 'Запускай!', result: true},
  469. {msg: 'Отмена', result: false},
  470. ]
  471. } else {
  472. yesCallback = () => {};
  473. buts = [
  474. {msg: 'Ок', result: true},
  475. ];
  476. }
  477. popup.confirm(message, buts).then((e) => {
  478. if (e) {
  479. yesCallback();
  480. } else {
  481. noCallback();
  482. }
  483. });
  484. }
  485. /** Переопределяем/проксируем метод создания Ajax запроса */
  486. XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  487. this.uniqid = Date.now();
  488. this.errorRequest = false;
  489. if (method == 'POST' && url.includes('.nextersglobal.com/api/') && /api\/$/.test(url)) {
  490. if (!apiUrl) {
  491. apiUrl = url;
  492. socialInfo = /heroes-(.+?)\./.exec(apiUrl);
  493. sNetwork = socialInfo ? socialInfo[1] : 'vk';
  494. }
  495. requestHistory[this.uniqid] = {
  496. method,
  497. url,
  498. error: [],
  499. headers: {},
  500. request: null,
  501. response: null,
  502. signature: [],
  503. calls: {},
  504. };
  505. } else if (method == 'POST' && url.includes('error.nextersglobal.com/client/')) {
  506. this.errorRequest = true;
  507. }
  508. return original.open.call(this, method, url, async, user, password);
  509. };
  510. /** Переопределяем/проксируем метод установки заголовков для AJAX запроса */
  511. XMLHttpRequest.prototype.setRequestHeader = function (name, value, check) {
  512. if (this.uniqid in requestHistory) {
  513. requestHistory[this.uniqid].headers[name] = value;
  514. } else {
  515. check = true;
  516. }
  517.  
  518. if (name == 'X-Auth-Signature') {
  519. requestHistory[this.uniqid].signature.push(value);
  520. if (!check) {
  521. return;
  522. }
  523. }
  524.  
  525. return original.setRequestHeader.call(this, name, value);
  526. };
  527. /** Переопределяем/проксируем метод отправки AJAX запроса */
  528. XMLHttpRequest.prototype.send = async function (sourceData) {
  529. if (this.uniqid in requestHistory) {
  530. let tempData = null;
  531. if (getClass(sourceData) == "ArrayBuffer") {
  532. tempData = decoder.decode(sourceData);
  533. } else {
  534. tempData = sourceData;
  535. }
  536. requestHistory[this.uniqid].request = tempData;
  537. let headers = requestHistory[this.uniqid].headers;
  538. lastHeaders = Object.assign({}, headers);
  539. /** Событие загрузки игры */
  540. if (headers["X-Request-Id"] > 2 && !isLoadGame) {
  541. isLoadGame = true;
  542. await openOrMigrateDatabase(userInfo.id);
  543. addControls();
  544. addControlButtons();
  545. addBottomUrls();
  546.  
  547. if (isChecked('sendExpedition')) {
  548. checkExpedition();
  549. }
  550. if (isChecked('getAutoGifts')) {
  551. checkSendGifts();
  552. getAutoGifts();
  553. }
  554. cheats.activateHacks();
  555. justInfo();
  556. if (isChecked('dailyQuests')) {
  557. testDailyQuests();
  558. }
  559. }
  560. /** Обработка данных исходящего запроса */
  561. sourceData = await checkChangeSend.call(this, sourceData, tempData);
  562. /** Обработка данных входящего запроса */
  563. const oldReady = this.onreadystatechange;
  564. this.onreadystatechange = function (e) {
  565. if(this.readyState == 4 && this.status == 200) {
  566. isTextResponse = this.responseType != "json";
  567. let response = isTextResponse ? this.responseText : this.response;
  568. requestHistory[this.uniqid].response = response;
  569. /** Заменна данных входящего запроса */
  570. if (isTextResponse) {
  571. checkChangeResponse.call(this, response);
  572. }
  573. /** Функция запускаемая после выполения запроса */
  574. if (typeof this.onReadySuccess == 'function') {
  575. setTimeout(this.onReadySuccess, 500);
  576. }
  577. }
  578. if (oldReady) {
  579. return oldReady.apply(this, arguments);
  580. }
  581. }
  582. }
  583. if (this.errorRequest) {
  584. const oldReady = this.onreadystatechange;
  585. this.onreadystatechange = function () {
  586. Object.defineProperty(this, 'status', {
  587. writable: true
  588. });
  589. this.status = 200;
  590. Object.defineProperty(this, 'readyState', {
  591. writable: true
  592. });
  593. this.readyState = 4;
  594. Object.defineProperty(this, 'responseText', {
  595. writable: true
  596. });
  597. this.responseText = JSON.stringify({
  598. "result": true
  599. });
  600. return oldReady.apply(this, arguments);
  601. }
  602. this.onreadystatechange();
  603. } else {
  604. return original.send.call(this, sourceData);
  605. }
  606. };
  607. /** Обработка и подмена исходящих данных */
  608. async function checkChangeSend(sourceData, tempData) {
  609. try {
  610. /** Функция заменяющая данные боя на неверные для отмены боя */
  611. const fixBattle = function (heroes) {
  612. for (const ids in heroes) {
  613. hero = heroes[ids];
  614. hero.energy = random(1, 999);
  615. if (hero.hp > 0) {
  616. hero.hp = random(1, hero.hp);
  617. }
  618. }
  619. }
  620. /** Диалоговое окно */
  621. const showMsg = async function (msg, ansF, ansS) {
  622. if (typeof popup == 'object') {
  623. return await popup.confirm(msg, [
  624. {msg: ansF, result: false},
  625. {msg: ansS, result: true},
  626. ]);
  627. } else {
  628. return !confirm(msg + "\n" + ansF + " (Ок)\n" + ansS + " (Отмена)");
  629. }
  630. }
  631. /** Диалоговое окно */
  632. const showMsgs = async function (msg, ansF, ansS, ansT) {
  633. return await popup.confirm(msg, [
  634. {msg: ansF, result: 0},
  635. {msg: ansS, result: 1},
  636. {msg: ansT, result: 2},
  637. ]);
  638. }
  639.  
  640. let changeRequest = false;
  641. testData = JSON.parse(tempData);
  642. for (const call of testData.calls) {
  643. if (!artifactChestOpen) {
  644. requestHistory[this.uniqid].calls[call.name] = call.ident;
  645. }
  646. /** Отмена боя в приключениях, на ВГ и с прислужниками Асгарда */
  647. if ((call.name == 'adventure_endBattle' ||
  648. call.name == 'adventureSolo_endBattle' ||
  649. call.name == 'clanWarEndBattle' && isChecked('cancelBattleBan') ||
  650. call.name == 'crossClanWar_endBattle' && isChecked('cancelBattleBan') ||
  651. call.name == 'brawl_endBattle' ||
  652. call.name == 'towerEndBattle' ||
  653. call.name == 'clanRaid_endNodeBattle') &&
  654. isCancalBattle) {
  655. nameFuncEndBattle = call.name;
  656. if (!call.args.result.win) {
  657. let resultPopup = false;
  658. if (call.name == 'adventure_endBattle' ||
  659. call.name == 'adventureSolo_endBattle') {
  660. resultPopup = await showMsgs('Вы потерпели поражение!', 'Хорошо', 'Отменить', 'Авто');
  661. } else {
  662. resultPopup = await showMsg('Вы потерпели поражение!', 'Хорошо', 'Отменить');
  663. }
  664. if (resultPopup) {
  665. fixBattle(call.args.progress[0].attackers.heroes);
  666. fixBattle(call.args.progress[0].defenders.heroes);
  667. changeRequest = true;
  668. if (resultPopup > 1) {
  669. this.onReadySuccess = testAutoBattle;
  670. // setTimeout(bossBattle, 1000);
  671. }
  672. }
  673. }
  674. }
  675. /** Отмена боя в Асгарде */
  676. if (call.name == 'clanRaid_endBossBattle' &&
  677. isCancalBossBattle &&
  678. isChecked('cancelBattleBan')) {
  679. bossDamage = call.args.progress[0].defenders.heroes[1].extra;
  680. sumDamage = bossDamage.damageTaken + bossDamage.damageTakenNextLevel;
  681. let resultPopup = await showMsgs(
  682. 'Вы нанесли ' + sumDamage.toLocaleString() + ' урона.',
  683. 'Хорошо', 'Отменить', 'Отменить и показать Статистику')
  684. if (resultPopup) {
  685. fixBattle(call.args.progress[0].attackers.heroes);
  686. fixBattle(call.args.progress[0].defenders.heroes);
  687. changeRequest = true;
  688. if (resultPopup > 1) {
  689. this.onReadySuccess = testBossBattle;
  690. // setTimeout(bossBattle, 1000);
  691. }
  692. }
  693. }
  694. /** Сохраняем пачку для атаки босса Асгарда */
  695. if (call.name == 'clanRaid_startBossBattle') {
  696. lastBossBattle = call.args;
  697. }
  698. /** Сохранение запроса начала последнего боя */
  699. if (call.name == 'clanWarAttack' ||
  700. call.name == 'crossClanWar_startBattle' ||
  701. call.name == 'adventure_turnStartBattle') {
  702. nameFuncStartBattle = call.name;
  703. lastBattleArg = call.args;
  704. }
  705. /** Отключить трату карт предсказаний */
  706. if (call.name == 'dungeonEndBattle') {
  707. if (isChecked('endlessCards') && call.args.isRaid) {
  708. delete call.args.isRaid;
  709. changeRequest = true;
  710. }
  711. }
  712. /** Ответ на викторину */
  713. if (call.name == 'quizAnswer') {
  714. /** Автоматически меняет ответ на правильный если он есть */
  715. if (lastAnswer && isChecked('getAnswer')) {
  716. call.args.answerId = lastAnswer;
  717. lastAnswer = null;
  718. changeRequest = true;
  719. }
  720. }
  721. /** Подарки */
  722. if (call.name == 'freebieCheck' && isChecked('getAutoGifts')) {
  723. freebieCheckInfo = call;
  724. }
  725. /** Получение данных миссии для автоповтора */
  726. if (isChecked('repeatMission') &&
  727. call.name == 'missionEnd') {
  728. let missionInfo = {
  729. id: call.args.id,
  730. result: call.args.result,
  731. heroes: call.args.progress[0].attackers.heroes,
  732. count: 0,
  733. }
  734. setTimeout(async () => {
  735. if (!isSendsMission && await popup.confirm('Повторить миссию?', [
  736. {msg: 'Повторить', result: true},
  737. {msg: 'Нет', result: false},
  738. ])) {
  739. isStopSendMission = false;
  740. isSendsMission = true;
  741. sendsMission(missionInfo);
  742. }
  743. }, 0);
  744. }
  745. /** Получение данных миссии */
  746. if (call.name == 'missionStart') {
  747. lastMissionStart = call.args;
  748. }
  749. /** Указать количество для сфер титанов и яиц петов */
  750. if (isChecked('countControl') &&
  751. (call.name == 'pet_chestOpen' ||
  752. call.name == 'titanUseSummonCircle') &&
  753. call.args.amount > 1) {
  754. call.args.amount = 1;
  755. const result = await popup.confirm('Указать количество:', [
  756. {msg: 'Открыть', isInput: true, default: call.args.amount},
  757. ]);
  758. if (result) {
  759. call.args.amount = result;
  760. changeRequest = true;
  761. }
  762. }
  763. /** Указать колличество для ключей и сфер артефактов титанов */
  764. if (isChecked('countControl') &&
  765. (call.name == 'artifactChestOpen' ||
  766. call.name == 'titanArtifactChestOpen') &&
  767. call.args.amount > 1 &&
  768. !changeRequest) {
  769. artifactChestOpenCallName = call.name;
  770. let result = await popup.confirm('Указать колличество:', [
  771. { msg: 'Открыть', isInput: true, default: call.args.amount },
  772. ]);
  773. if (result) {
  774. let sphere = result < 10 ? 1 : 10;
  775.  
  776. call.args.amount = sphere;
  777. result -= sphere;
  778.  
  779. for (let count = result; count > 0; count -= sphere) {
  780. if (count < 10) sphere = 1;
  781. const ident = artifactChestOpenCallName + "_" + count;
  782. testData.calls.push({
  783. name: artifactChestOpenCallName,
  784. args: {
  785. amount: sphere,
  786. free: true,
  787. },
  788. ident: ident
  789. });
  790. if (!Array.isArray(requestHistory[this.uniqid].calls[call.name])) {
  791. requestHistory[this.uniqid].calls[call.name] = [requestHistory[this.uniqid].calls[call.name]];
  792. }
  793. requestHistory[this.uniqid].calls[call.name].push(ident);
  794. }
  795.  
  796. artifactChestOpen = true;
  797. changeRequest = true;
  798. }
  799. }
  800. if (call.name == 'consumableUseLootBox') {
  801. lastRussianDollId = call.args.libId;
  802. /** Указать количество для золотых шкатулок */
  803. if (isChecked('countControl') &&
  804. call.args.libId == 148 &&
  805. call.args.amount > 1) {
  806. const result = await popup.confirm('Указать количество:', [
  807. {msg: 'Открыть', isInput: true, default: call.args.amount},
  808. ]);
  809. call.args.amount = result;
  810. changeRequest = true;
  811. }
  812. }
  813. }
  814.  
  815. let headers = requestHistory[this.uniqid].headers;
  816. if (changeRequest) {
  817. sourceData = JSON.stringify(testData);
  818. headers['X-Auth-Signature'] = getSignature(headers, sourceData);
  819. }
  820.  
  821. let signature = headers['X-Auth-Signature'];
  822. if (signature) {
  823. this.setRequestHeader('X-Auth-Signature', signature, true);
  824. }
  825. } catch (err) {
  826. console.log("Request(send, " + this.uniqid + "):\n", sourceData, "Error:\n", err);
  827. }
  828. return sourceData;
  829. }
  830. /** Обработка и подмена входящих данных */
  831. async function checkChangeResponse(response) {
  832. try {
  833. isChange = false;
  834. let nowTime = Math.round(Date.now() / 1000);
  835. callsIdent = requestHistory[this.uniqid].calls;
  836. respond = JSON.parse(response);
  837. /** Если запрос вернул ошибку удаляет ошибку (убирает ошибки синхронизации) */
  838. if (respond.error) {
  839. isChange = true;
  840. console.error(respond.error);
  841. delete respond.error;
  842. respond.results = [];
  843. }
  844. let mainReward = null;
  845. const allReward = {};
  846. for (const call of respond.results) {
  847. /** Получение идетификатора пользователя */
  848. if (call.ident == callsIdent['registration']) {
  849. userId = call.result.response.userId;
  850. }
  851. /** Потасовка */
  852. if (call.ident == callsIdent['brawl_getInfo']) {
  853. brawl = call.result.response;
  854. if (brawl) {
  855. brawl.boughtEndlessLivesToday = 1;
  856. isChange = true;
  857. }
  858. }
  859. /** Скрываем предложения доната */
  860. if (call.ident == callsIdent['billingGetAll'] && getSaveVal('noOfferDonat')) {
  861. const billings = call.result.response?.billings;
  862. const bundle = call.result.response?.bundle;
  863. if (billings && bundle) {
  864. call.result.response.billings = [];
  865. call.result.response.bundle = [];
  866. isChange = true;
  867. }
  868. }
  869. /** Скрываем предложения доната */
  870. if (call.ident == callsIdent['offerGetAll'] && getSaveVal('noOfferDonat')) {
  871. const offers = call.result.response;
  872. if (offers) {
  873. call.result.response = offers.filter(e => !['addBilling', 'bundleCarousel'].includes(e.type));
  874. isChange = true;
  875. }
  876. }
  877. /** Копирует вопрос викторины в буфер обмена и получает на него ответ если есть */
  878. if (call.ident == callsIdent['quizGetNewQuestion']) {
  879. let quest = call.result.response;
  880. console.log(quest.question);
  881. copyText(quest.question);
  882. setProgress('Вопрос скопирован в буфер обмена', true);
  883. lastQuestion = quest;
  884. if (isChecked('getAnswer')) {
  885. const answer = await getAnswer(lastQuestion);
  886. if (answer) {
  887. lastAnswer = answer;
  888. console.log(answer);
  889. setProgress('Ответ известен: ' + answer, true);
  890. } else {
  891. setProgress('ВНИМАНИЕ ОТВЕТ НЕ ИЗВЕСТЕН', true);
  892. }
  893. }
  894. }
  895. /** Отправляет вопрос с ответом в базу данных */
  896. if (call.ident == callsIdent['quizAnswer']) {
  897. const answer = call.result.response;
  898. if (lastQuestion) {
  899. const answerInfo = {
  900. answer,
  901. question: lastQuestion
  902. }
  903. lastQuestion = null;
  904. setTimeout(sendAnswerInfo, 0, answerInfo);
  905. }
  906. }
  907. /** Получить даныне пользователя */
  908. if (call.ident == callsIdent['userGetInfo']) {
  909. let user = call.result.response;
  910. userInfo = Object.assign({}, user);
  911. delete userInfo.refillable;
  912. if (!questsInfo['userGetInfo']) {
  913. questsInfo['userGetInfo'] = user;
  914. }
  915. }
  916. /** Начало боя для прерасчета */
  917. if ((call.ident == callsIdent['clanWarAttack'] ||
  918. call.ident == callsIdent['crossClanWar_startBattle'] ||
  919. call.ident == callsIdent['battleGetReplay'] ||
  920. call.ident == callsIdent['adventure_turnStartBattle']) &&
  921. isChecked('preCalcBattle')) {
  922. setProgress('Идет прерасчет боя');
  923. let battle = call.result.response.battle || call.result.response.replay;
  924. lastBattleInfo = battle;
  925. console.log(battle.type);
  926. function getBattleInfo(battle, isRandSeed) {
  927. return new Promise(function (resolve) {
  928. if (isRandSeed) {
  929. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  930. }
  931. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  932. });
  933. }
  934. let actions = [getBattleInfo(battle, false)]
  935. const countTestBattle = getInput('countTestBattle');
  936. for (let i = 0; i < countTestBattle; i++) {
  937. actions.push(getBattleInfo(battle, true));
  938. }
  939. Promise.all(actions)
  940. .then(e => {
  941. let firstBattle = e.shift();
  942. let countWin = e.reduce((w, s) => w + s);
  943. setProgress((firstBattle ? 'Победа' : 'Поражение') + ' ' + countWin + '/' + e.length + ' X', false, hideProgress)
  944. });
  945. }
  946. /** Начало боя с боссом Асгарда */
  947. if (call.ident == callsIdent['clanRaid_startBossBattle']) {
  948. lastBossBattleInfo = call.result.response.battle;
  949. }
  950. /** Отмена туториала */
  951. if (isCanceledTutorial && call.ident == callsIdent['tutorialGetInfo']) {
  952. let chains = call.result.response.chains;
  953. for (let n in chains) {
  954. chains[n] = 9999;
  955. }
  956. isChange = true;
  957. }
  958. /** Открытие ключей и сфер артефактов титанов */
  959. if (artifactChestOpen &&
  960. (call.ident == callsIdent[artifactChestOpenCallName] ||
  961. (callsIdent[artifactChestOpenCallName] && callsIdent[artifactChestOpenCallName].includes(call.ident)))) {
  962. let reward = call.result.response[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'];
  963.  
  964. reward.forEach(e => {
  965. for (let f in e) {
  966. if (!allReward[f]) {
  967. allReward[f] = {};
  968. }
  969. for (let o in e[f]) {
  970. if (!allReward[f][o]) {
  971. allReward[f][o] = e[f][o];
  972. } else {
  973. allReward[f][o] += e[f][o];
  974. }
  975. }
  976. }
  977. });
  978.  
  979. if (!call.ident.includes(artifactChestOpenCallName)) {
  980. mainReward = call.result.response;
  981. }
  982. }
  983. /** АвтоПовтор открытия матрешек */
  984. if (isChecked('countControl') && call.ident == callsIdent['consumableUseLootBox']) {
  985. let lootBox = call.result.response;
  986. let newCount = 0;
  987. for (let n of lootBox) {
  988. if (n?.consumable && n.consumable[lastRussianDollId]) {
  989. newCount += n.consumable[lastRussianDollId]
  990. }
  991. }
  992. if (newCount && await popup.confirm('Открыть ' + newCount + ' матрешек рекурсивно?', [
  993. {msg: 'Повторить', result: true},
  994. {msg: 'Нет', result: false},
  995. ])) {
  996. openRussianDoll(lastRussianDollId, newCount);
  997. }
  998. }
  999. /** Получение данных по квестам */
  1000. if (call.ident == callsIdent['questGetAll']) {
  1001. if (!questsInfo['questGetAll']) {
  1002. questsInfo['questGetAll'] = call.result.response;
  1003. }
  1004. }
  1005. /** Получение данных инвентаря для квестов */
  1006. if (call.ident == callsIdent['inventoryGet']) {
  1007. if (!questsInfo['inventoryGet']) {
  1008. questsInfo['inventoryGet'] = call.result.response;
  1009. }
  1010. }
  1011. /** Получение данных героев для квестов */
  1012. if (call.ident == callsIdent['heroGetAll']) {
  1013. if (!questsInfo['heroGetAll']) {
  1014. questsInfo['heroGetAll'] = call.result.response;
  1015. }
  1016. }
  1017. /** Получение данных титанов для квестов */
  1018. if (call.ident == callsIdent['titanGetAll']) {
  1019. if (!questsInfo['titanGetAll']) {
  1020. questsInfo['titanGetAll'] = call.result.response;
  1021. }
  1022. }
  1023. }
  1024.  
  1025. if (mainReward && artifactChestOpen) {
  1026. console.log(allReward);
  1027. mainReward[artifactChestOpenCallName == 'artifactChestOpen' ? 'chestReward' : 'reward'] = [allReward];
  1028. artifactChestOpen = false;
  1029. artifactChestOpenCallName = '';
  1030. isChange = true;
  1031. }
  1032. } catch(err) {
  1033. console.log("Request(response, " + this.uniqid + "):\n", "Error:\n", response, err);
  1034. }
  1035.  
  1036. if (isChange) {
  1037. Object.defineProperty(this, 'responseText', {
  1038. writable: true
  1039. });
  1040. this.responseText = JSON.stringify(respond);
  1041. }
  1042. }
  1043.  
  1044. /** Запрос ответа на вопрос */
  1045. async function getAnswer(question) {
  1046. return new Promise((resolve, reject) => {
  1047. fetch('https://zingery.ru/heroes/getAnswer.php', {
  1048. method: 'POST',
  1049. body: JSON.stringify(question)
  1050. }).then(
  1051. response => response.json()
  1052. ).then(
  1053. data => {
  1054. if (data.result) {
  1055. resolve(data.result);
  1056. } else {
  1057. resolve(false);
  1058. }
  1059. }
  1060. ).catch((error) => {
  1061. console.error(error);
  1062. resolve(false);
  1063. });
  1064. })
  1065. }
  1066.  
  1067. /** Отправка вопроса и ответа в базу данных */
  1068. function sendAnswerInfo(answerInfo) {
  1069. fetch('https://zingery.ru/heroes/setAnswer.php', {
  1070. method: 'POST',
  1071. body: JSON.stringify(answerInfo)
  1072. }).then(
  1073. response => response.json()
  1074. ).then(
  1075. data => {
  1076. if (data.result) {
  1077. console.log('Вопрос отправлен');
  1078. }
  1079. }
  1080. )
  1081. }
  1082.  
  1083. /** Возвращает тип боя по типу пресета */
  1084. function getBattleType(strBattleType) {
  1085. switch (strBattleType) {
  1086. case "invasion":
  1087. return "get_invasion";
  1088. case "titan_pvp_manual":
  1089. return "get_titanPvpManual";
  1090. case "titan_pvp":
  1091. return "get_titanPvp";
  1092. case "titan_clan_pvp":
  1093. case "clan_pvp_titan":
  1094. case "clan_global_pvp_titan":
  1095. case "challenge_titan":
  1096. return "get_titanClanPvp";
  1097. case "clan_raid": // Босс асгарда
  1098. case "adventure": // Приключения
  1099. case "clan_global_pvp":
  1100. case "clan_pvp":
  1101. case "challenge":
  1102. case "grand":
  1103. case "arena":
  1104. return "get_clanPvp";
  1105. case "titan_tower":
  1106. return "get_titan";
  1107. case "tower":
  1108. return "get_tower";
  1109. case "pve":
  1110. return "get_pve";
  1111. case "pvp_manual":
  1112. return "get_pvpManual";
  1113. case "pvp":
  1114. return "get_pvp";
  1115. case "core":
  1116. return "get_core";
  1117. default:
  1118. return "get_clanPvp";
  1119. }
  1120. }
  1121. /** Возвращает название класса переданного объекта */
  1122. function getClass(obj) {
  1123. return {}.toString.call(obj).slice(8, -1);
  1124. }
  1125. /** Расчитывает сигнатуру запроса */
  1126. this.getSignature = function(headers, data) {
  1127. let signatureStr = [headers["X-Request-Id"], headers["X-Auth-Token"], headers["X-Auth-Session-Id"], data, 'LIBRARY-VERSION=1'].join(':');
  1128. return md5(signatureStr);
  1129. }
  1130. /** Создает интерфейс */
  1131. function createInterface() {
  1132. scriptMenu.init({
  1133. showMenu: true
  1134. });
  1135. scriptMenu.addHeader(GM_info.script.name, justInfo);
  1136. scriptMenu.addHeader('v' + GM_info.script.version);
  1137. }
  1138.  
  1139. function addControls() {
  1140. const checkboxDetails = scriptMenu.addDetails('Настройки');
  1141. for (let name in checkboxes) {
  1142. checkboxes[name].cbox = scriptMenu.addCheckbox(checkboxes[name].label, checkboxes[name].title, checkboxDetails);
  1143. /** Получаем состояние чекбоксов из storage */
  1144. let val = storage.get(name, null);
  1145. if (val != null) {
  1146. checkboxes[name].cbox.checked = val;
  1147. } else {
  1148. storage.set(name, checkboxes[name].default);
  1149. checkboxes[name].cbox.checked = checkboxes[name].default;
  1150. }
  1151. /** Отсеживание события изменения чекбокса для записи в storage */
  1152. checkboxes[name].cbox.dataset['name'] = name;
  1153. checkboxes[name].cbox.addEventListener('change', async function (event) {
  1154. const nameCheckbox = this.dataset['name'];
  1155. if (this.checked && nameCheckbox == 'cancelBattleBan') {
  1156. this.checked = false;
  1157. if (await popup.confirm('<p style="color:red;">Использование этой функции может привести к бану.</p> Продолжить?', [
  1158. { msg: 'Нет, я отказываюсь от этого!', result: true },
  1159. { msg: 'Да, я беру на себя все риски!', result: false },
  1160. ])) {
  1161. return;
  1162. }
  1163. this.checked = true;
  1164. }
  1165. storage.set(nameCheckbox, this.checked);
  1166. })
  1167. }
  1168.  
  1169. const inputDetails = scriptMenu.addDetails('Значения');
  1170. for (let name in inputs) {
  1171. inputs[name].input = scriptMenu.addInputText(inputs[name].title, false, inputDetails);
  1172. /** Получаем состояние inputText из storage */
  1173. let val = storage.get(name, null);
  1174. if (val != null) {
  1175. inputs[name].input.value = val;
  1176. } else {
  1177. storage.set(name, inputs[name].default);
  1178. inputs[name].input.value = inputs[name].default;
  1179. }
  1180. /** Отсеживание события изменения поля для записи в storage */
  1181. inputs[name].input.dataset['name'] = name;
  1182. inputs[name].input.addEventListener('input', function () {
  1183. const inputName = this.dataset['name'];
  1184. let value = +this.value;
  1185. if (!value || Number.isNaN(value)) {
  1186. value = storage.get(inputName, inputs[inputName].default);
  1187. inputs[name].input.value = value;
  1188. }
  1189. storage.set(inputName, value);
  1190. })
  1191. }
  1192. }
  1193. /** Расчитывает HASH MD5 из строки */
  1194. 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}
  1195. /** Скрипт для красивых диалоговых окошек */
  1196. const popup = new (function () {
  1197. this.popUp,
  1198. this.downer,
  1199. this.middle,
  1200. this.msgText,
  1201. this.buttons = [];
  1202. this.checkboxes = [];
  1203.  
  1204. function init() {
  1205. addStyle();
  1206. addBlocks();
  1207. }
  1208.  
  1209. const addStyle = () => {
  1210. let style = document.createElement('style');
  1211. style.innerText = `
  1212. .PopUp_ {
  1213. position: absolute;
  1214. min-width: 300px;
  1215. max-width: 500px;
  1216. max-height: 400px;
  1217. background-color: #190e08e6;
  1218. z-index: 10001;
  1219. top: 169px;
  1220. left: 345px;
  1221. border: 3px #ce9767 solid;
  1222. border-radius: 10px;
  1223. display: flex;
  1224. flex-direction: column;
  1225. justify-content: space-around;
  1226. padding: 15px 12px;
  1227. }
  1228.  
  1229. .PopUp_back {
  1230. position: absolute;
  1231. background-color: #00000066;
  1232. width: 100%;
  1233. height: 100%;
  1234. z-index: 10000;
  1235. top: 0;
  1236. left: 0;
  1237. }
  1238.  
  1239. .PopUp_blocks {
  1240. width: 100%;
  1241. height: 50%;
  1242. display: flex;
  1243. justify-content: space-evenly;
  1244. align-items: center;
  1245. flex-wrap: wrap;
  1246. justify-content: center;
  1247. }
  1248.  
  1249. .PopUp_blocks:last-child {
  1250. margin-top: 25px;
  1251. }
  1252.  
  1253. .PopUp_buttons {
  1254. display: flex;
  1255. margin: 10px 12px;
  1256. flex-direction: column;
  1257. }
  1258.  
  1259. .PopUp_button {
  1260. background-color: #52A81C;
  1261. border-radius: 5px;
  1262. box-shadow: inset 0px -4px 10px, inset 0px 3px 2px #99fe20, 0px 0px 4px, 0px -3px 1px #d7b275, 0px 0px 0px 3px #ce9767;
  1263. cursor: pointer;
  1264. padding: 5px 18px 8px;
  1265. }
  1266.  
  1267. .PopUp_input {
  1268. text-align: center;
  1269. font-size: 16px;
  1270. height: 27px;
  1271. border: 1px solid #cf9250;
  1272. border-radius: 9px 9px 0px 0px;
  1273. background: transparent;
  1274. color: #fce1ac;
  1275. padding: 1px 10px;
  1276. box-sizing: border-box;
  1277. box-shadow: 0px 0px 4px, 0px 0px 0px 3px #ce9767;
  1278. }
  1279.  
  1280. .PopUp_checkboxes {
  1281. display: flex;
  1282. flex-direction: column;
  1283. margin: 15px 15px -5px 15px;
  1284. align-items: flex-start;
  1285. }
  1286.  
  1287. .PopUp_ContCheckbox {
  1288. margin: 2px 0px;
  1289. }
  1290.  
  1291. .PopUp_checkbox {
  1292. position: absolute;
  1293. z-index: -1;
  1294. opacity: 0;
  1295. }
  1296. .PopUp_checkbox+label {
  1297. display: inline-flex;
  1298. align-items: center;
  1299. user-select: none;
  1300.  
  1301. font-size: 15px;
  1302. font-family: sans-serif;
  1303. font-weight: 600;
  1304. font-stretch: condensed;
  1305. letter-spacing: 1px;
  1306. color: #fce1ac;
  1307. text-shadow: 0px 0px 1px;
  1308. }
  1309. .PopUp_checkbox+label::before {
  1310. content: '';
  1311. display: inline-block;
  1312. width: 20px;
  1313. height: 20px;
  1314. border: 1px solid #cf9250;
  1315. border-radius: 7px;
  1316. margin-right: 7px;
  1317. }
  1318. .PopUp_checkbox:checked+label::before {
  1319. 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");
  1320. }
  1321.  
  1322. .PopUp_input::placeholder {
  1323. color: #fce1ac75;
  1324. }
  1325.  
  1326. .PopUp_input:focus {
  1327. outline: 0;
  1328. }
  1329.  
  1330. .PopUp_input + .PopUp_button {
  1331. border-radius: 0px 0px 5px 5px;
  1332. padding: 2px 18px 5px;
  1333. }
  1334.  
  1335. .PopUp_button:hover {
  1336. filter: brightness(1.2);
  1337. }
  1338.  
  1339. .PopUp_text {
  1340. font-size: 22px;
  1341. font-family: sans-serif;
  1342. font-weight: 600;
  1343. font-stretch: condensed;
  1344. letter-spacing: 1px;
  1345. text-align: center;
  1346. }
  1347.  
  1348. .PopUp_buttonText {
  1349. color: #E4FF4C;
  1350. text-shadow: 0px 1px 2px black;
  1351. }
  1352.  
  1353. .PopUp_msgText {
  1354. color: #FDE5B6;
  1355. text-shadow: 0px 0px 2px;
  1356. }
  1357.  
  1358. .PopUp_hideBlock {
  1359. display: none;
  1360. }
  1361. `;
  1362. document.head.appendChild(style);
  1363. }
  1364.  
  1365. const addBlocks = () => {
  1366. this.back = document.createElement('div');
  1367. this.back.classList.add('PopUp_back');
  1368. this.back.classList.add('PopUp_hideBlock');
  1369. document.body.append(this.back);
  1370.  
  1371. this.popUp = document.createElement('div');
  1372. this.popUp.classList.add('PopUp_');
  1373. this.back.append(this.popUp);
  1374.  
  1375. let upper = document.createElement('div')
  1376. upper.classList.add('PopUp_blocks');
  1377. this.popUp.append(upper);
  1378.  
  1379. this.middle = document.createElement('div')
  1380. this.middle.classList.add('PopUp_blocks');
  1381. this.middle.classList.add('PopUp_checkboxes');
  1382. this.popUp.append(this.middle);
  1383.  
  1384. this.downer = document.createElement('div')
  1385. this.downer.classList.add('PopUp_blocks');
  1386. this.popUp.append(this.downer);
  1387.  
  1388. this.msgText = document.createElement('div');
  1389. this.msgText.classList.add('PopUp_text', 'PopUp_msgText');
  1390. upper.append(this.msgText);
  1391. }
  1392.  
  1393. this.showBack = function () {
  1394. this.back.classList.remove('PopUp_hideBlock');
  1395. }
  1396.  
  1397. this.hideBack = function () {
  1398. this.back.classList.add('PopUp_hideBlock');
  1399. }
  1400.  
  1401. this.show = function () {
  1402. if (this.checkboxes.length) {
  1403. this.middle.classList.remove('PopUp_hideBlock');
  1404. }
  1405. this.showBack();
  1406. this.popUp.classList.remove('PopUp_hideBlock');
  1407. this.popUp.style.left = (window.innerWidth - this.popUp.offsetWidth) / 2 + 'px';
  1408. this.popUp.style.top = (window.innerHeight - this.popUp.offsetHeight) / 3 + 'px';
  1409. }
  1410.  
  1411. this.hide = function () {
  1412. this.hideBack();
  1413. this.popUp.classList.add('PopUp_hideBlock');
  1414. }
  1415.  
  1416. this.addButton = (option, buttonClick) => {
  1417. const contButton = document.createElement('div');
  1418. contButton.classList.add('PopUp_buttons');
  1419. this.downer.append(contButton);
  1420.  
  1421. let inputField = {
  1422. value: option.result || option.default
  1423. }
  1424. if (option.isInput) {
  1425. inputField = document.createElement('input');
  1426. inputField.type = 'text';
  1427. if (option.placeholder) {
  1428. inputField.placeholder = option.placeholder;
  1429. }
  1430. if (option.default) {
  1431. inputField.value = option.default;
  1432. }
  1433. inputField.classList.add('PopUp_input');
  1434. contButton.append(inputField);
  1435. }
  1436.  
  1437. const button = document.createElement('div');
  1438. button.classList.add('PopUp_button');
  1439. contButton.append(button);
  1440.  
  1441. button.addEventListener('click', () => {
  1442. let result = '';
  1443. if (option.isInput) {
  1444. result = inputField.value;
  1445. }
  1446. buttonClick(result);
  1447. });
  1448.  
  1449. const buttonText = document.createElement('div');
  1450. buttonText.classList.add('PopUp_text', 'PopUp_buttonText');
  1451. buttonText.innerText = option.msg;
  1452. button.append(buttonText);
  1453.  
  1454. this.buttons.push(contButton);
  1455. }
  1456.  
  1457. this.clearButtons = () => {
  1458. while (this.buttons.length) {
  1459. this.buttons.pop().remove();
  1460. }
  1461. }
  1462.  
  1463. this.addCheckBox = (checkBox) => {
  1464. const contCheckbox = document.createElement('div');
  1465. contCheckbox.classList.add('PopUp_ContCheckbox');
  1466. this.middle.append(contCheckbox);
  1467.  
  1468. const checkbox = document.createElement('input');
  1469. checkbox.type = 'checkbox';
  1470. checkbox.id = 'PopUpCheckbox' + this.checkboxes.length;
  1471. checkbox.dataset.name = checkBox.name;
  1472. checkbox.checked = checkBox.checked;
  1473. checkbox.label = checkBox.label;
  1474. checkbox.classList.add('PopUp_checkbox');
  1475. contCheckbox.appendChild(checkbox)
  1476.  
  1477. const checkboxLabel = document.createElement('label');
  1478. checkboxLabel.innerText = checkBox.label;
  1479. checkboxLabel.setAttribute('for', checkbox.id);
  1480. contCheckbox.appendChild(checkboxLabel);
  1481.  
  1482. this.checkboxes.push(checkbox);
  1483. }
  1484.  
  1485. this.clearCheckBox = () => {
  1486. this.middle.classList.add('PopUp_hideBlock');
  1487. while (this.checkboxes.length) {
  1488. this.checkboxes.pop().parentNode.remove();
  1489. }
  1490. }
  1491.  
  1492. this.setMsgText = (text) => {
  1493. this.msgText.innerHTML = text;
  1494. }
  1495.  
  1496. this.getCheckBoxes = () => {
  1497. const checkBoxes = [];
  1498.  
  1499. for (const checkBox of this.checkboxes) {
  1500. checkBoxes.push({
  1501. name: checkBox.dataset.name,
  1502. label: checkBox.label,
  1503. checked: checkBox.checked
  1504. });
  1505. }
  1506.  
  1507. return checkBoxes;
  1508. }
  1509.  
  1510. this.confirm = async (msg, buttOpt, checkBoxes = []) => {
  1511. this.clearButtons();
  1512. this.clearCheckBox();
  1513. return new Promise((complete, failed) => {
  1514. this.setMsgText(msg);
  1515. if (!buttOpt) {
  1516. buttOpt = [{ msg: 'Ок', result: true, isInput: false }];
  1517. }
  1518. for (const checkBox of checkBoxes) {
  1519. this.addCheckBox(checkBox);
  1520. }
  1521. for (let butt of buttOpt) {
  1522. this.addButton(butt, (result) => {
  1523. result = result || butt.result;
  1524. complete(result);
  1525. popup.hide();
  1526. });
  1527. }
  1528. this.show();
  1529. });
  1530. }
  1531.  
  1532. document.addEventListener('DOMContentLoaded', init);
  1533. });
  1534. /** Панель управления скриптом */
  1535. const scriptMenu = new (function () {
  1536.  
  1537. this.mainMenu,
  1538. this.buttons = [],
  1539. this.checkboxes = [];
  1540. this.option = {
  1541. showMenu: false,
  1542. showDetails: {}
  1543. };
  1544.  
  1545. this.init = function (option = {}) {
  1546. this.option = Object.assign(this.option, option);
  1547. this.option.showDetails = this.loadShowDetails();
  1548. addStyle();
  1549. addBlocks();
  1550. }
  1551.  
  1552. const addStyle = () => {
  1553. style = document.createElement('style');
  1554. style.innerText = `
  1555. .scriptMenu_status {
  1556. position: absolute;
  1557. z-index: 10001;
  1558. /* max-height: 30px; */
  1559. top: -1px;
  1560. left: 30%;
  1561. cursor: pointer;
  1562. border-radius: 0px 0px 10px 10px;
  1563. background: #190e08e6;
  1564. border: 1px #ce9767 solid;
  1565. font-size: 18px;
  1566. font-family: sans-serif;
  1567. font-weight: 600;
  1568. font-stretch: condensed;
  1569. letter-spacing: 1px;
  1570. color: #fce1ac;
  1571. text-shadow: 0px 0px 1px;
  1572. transition: 0.5s;
  1573. padding: 2px 10px 3px;
  1574. }
  1575. .scriptMenu_statusHide {
  1576. top: -35px;
  1577. height: 30px;
  1578. overflow: hidden;
  1579. }
  1580. .scriptMenu_label {
  1581. position: absolute;
  1582. top: 30%;
  1583. left: -4px;
  1584. z-index: 9999;
  1585. cursor: pointer;
  1586. width: 30px;
  1587. height: 30px;
  1588. background: radial-gradient(circle, #47a41b 0%, #1a2f04 100%);
  1589. border: 1px solid #1a2f04;
  1590. border-radius: 5px;
  1591. box-shadow:
  1592. inset 0px 2px 4px #83ce26,
  1593. inset 0px -4px 6px #1a2f04,
  1594. 0px 0px 2px black,
  1595. 0px 0px 0px 2px #ce9767;
  1596. }
  1597. .scriptMenu_label:hover {
  1598. filter: brightness(1.2);
  1599. }
  1600. .scriptMenu_arrowLabel {
  1601. width: 100%;
  1602. height: 100%;
  1603. background-size: 75%;
  1604. background-position: center;
  1605. background-repeat: no-repeat;
  1606. 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");
  1607. box-shadow: 0px 1px 2px #000;
  1608. border-radius: 5px;
  1609. filter: drop-shadow(0px 1px 2px #000D);
  1610. }
  1611. .scriptMenu_main {
  1612. position: absolute;
  1613. max-width: 285px;
  1614. z-index: 9999;
  1615. top: 50%;
  1616. transform: translateY(-50%);
  1617. background: #190e08e6;
  1618. border: 1px #ce9767 solid;
  1619. border-radius: 0px 10px 10px 0px;
  1620. border-left: none;
  1621. padding: 5px 10px 5px 5px;
  1622. box-sizing: border-box;
  1623. font-size: 15px;
  1624. font-family: sans-serif;
  1625. font-weight: 600;
  1626. font-stretch: condensed;
  1627. letter-spacing: 1px;
  1628. color: #fce1ac;
  1629. text-shadow: 0px 0px 1px;
  1630. transition: 1s;
  1631. display: flex;
  1632. flex-direction: column;
  1633. flex-wrap: nowrap;
  1634. }
  1635. .scriptMenu_showMenu {
  1636. display: none;
  1637. }
  1638. .scriptMenu_showMenu:checked~.scriptMenu_main {
  1639. left: 0px;
  1640. }
  1641. .scriptMenu_showMenu:not(:checked)~.scriptMenu_main {
  1642. left: -300px;
  1643. }
  1644. .scriptMenu_divInput {
  1645. margin: 2px;
  1646. }
  1647. .scriptMenu_divInputText {
  1648. margin: 2px;
  1649. align-self: center;
  1650. display: flex;
  1651. }
  1652. .scriptMenu_checkbox {
  1653. position: absolute;
  1654. z-index: -1;
  1655. opacity: 0;
  1656. }
  1657. .scriptMenu_checkbox+label {
  1658. display: inline-flex;
  1659. align-items: center;
  1660. user-select: none;
  1661. }
  1662. .scriptMenu_checkbox+label::before {
  1663. content: '';
  1664. display: inline-block;
  1665. width: 20px;
  1666. height: 20px;
  1667. border: 1px solid #cf9250;
  1668. border-radius: 7px;
  1669. margin-right: 7px;
  1670. }
  1671. .scriptMenu_checkbox:checked+label::before {
  1672. 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");
  1673. }
  1674. .scriptMenu_close {
  1675. width: 40px;
  1676. height: 40px;
  1677. position: absolute;
  1678. right: -18px;
  1679. top: -18px;
  1680. border: 3px solid #c18550;
  1681. border-radius: 20px;
  1682. background: radial-gradient(circle, rgba(190,30,35,1) 0%, rgba(0,0,0,1) 100%);
  1683. background-position-y: 3px;
  1684. box-shadow: -1px 1px 3px black;
  1685. cursor: pointer;
  1686. box-sizing: border-box;
  1687. }
  1688. .scriptMenu_close:hover {
  1689. filter: brightness(1.2);
  1690. }
  1691. .scriptMenu_crossClose {
  1692. width: 100%;
  1693. height: 100%;
  1694. background-size: 65%;
  1695. background-position: center;
  1696. background-repeat: no-repeat;
  1697. 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")
  1698. }
  1699. .scriptMenu_button {
  1700. user-select: none;
  1701. border-radius: 5px;
  1702. cursor: pointer;
  1703. padding: 5px 14px 8px;
  1704. margin: 4px;
  1705. background: radial-gradient(circle, rgba(165,120,56,1) 80%, rgba(0,0,0,1) 110%);
  1706. box-shadow: inset 0px -4px 6px #442901, inset 0px 1px 6px #442901, inset 0px 0px 6px, 0px 0px 4px, 0px 0px 0px 2px #ce9767;
  1707. }
  1708. .scriptMenu_button:hover {
  1709. filter: brightness(1.2);
  1710. }
  1711. .scriptMenu_buttonText {
  1712. color: #fce5b7;
  1713. text-shadow: 0px 1px 2px black;
  1714. text-align: center;
  1715. }
  1716. .scriptMenu_header {
  1717. text-align: center;
  1718. align-self: center;
  1719. font-size: 15px;
  1720. margin: 0px 15px;
  1721. }
  1722. .scriptMenu_header a {
  1723. color: #fce5b7;
  1724. text-decoration: none;
  1725. }
  1726. .scriptMenu_InputText {
  1727. text-align: center;
  1728. width: 130px;
  1729. height: 24px;
  1730. border: 1px solid #cf9250;
  1731. border-radius: 9px;
  1732. background: transparent;
  1733. color: #fce1ac;
  1734. padding: 0px 10px;
  1735. box-sizing: border-box;
  1736. }
  1737. .scriptMenu_InputText:focus {
  1738. filter: brightness(1.2);
  1739. outline: 0;
  1740. }
  1741. .scriptMenu_InputText::placeholder {
  1742. color: #fce1ac75;
  1743. }
  1744. .scriptMenu_Summary {
  1745. cursor: pointer;
  1746. margin-left: 7px;
  1747. }
  1748. .scriptMenu_Details {
  1749. align-self: center;
  1750. }
  1751. `;
  1752. document.head.appendChild(style);
  1753. }
  1754.  
  1755. const addBlocks = () => {
  1756. const main = document.createElement('div');
  1757. document.body.appendChild(main);
  1758.  
  1759. this.status = document.createElement('div');
  1760. this.status.classList.add('scriptMenu_status');
  1761. this.setStatus('');
  1762. main.appendChild(this.status);
  1763.  
  1764. const label = document.createElement('label');
  1765. label.classList.add('scriptMenu_label');
  1766. label.setAttribute('for', 'checkbox_showMenu');
  1767. main.appendChild(label);
  1768.  
  1769. const arrowLabel = document.createElement('div');
  1770. arrowLabel.classList.add('scriptMenu_arrowLabel');
  1771. label.appendChild(arrowLabel);
  1772.  
  1773. const checkbox = document.createElement('input');
  1774. checkbox.type = 'checkbox';
  1775. checkbox.id = 'checkbox_showMenu';
  1776. checkbox.checked = this.option.showMenu;
  1777. checkbox.classList.add('scriptMenu_showMenu');
  1778. main.appendChild(checkbox);
  1779.  
  1780. this.mainMenu = document.createElement('div');
  1781. this.mainMenu.classList.add('scriptMenu_main');
  1782. main.appendChild(this.mainMenu);
  1783.  
  1784. const closeButton = document.createElement('label');
  1785. closeButton.classList.add('scriptMenu_close');
  1786. closeButton.setAttribute('for', 'checkbox_showMenu');
  1787. this.mainMenu.appendChild(closeButton);
  1788.  
  1789. const crossClose = document.createElement('div');
  1790. crossClose.classList.add('scriptMenu_crossClose');
  1791. closeButton.appendChild(crossClose);
  1792. }
  1793.  
  1794. this.setStatus = (text, onclick) => {
  1795. if (!text) {
  1796. this.status.classList.add('scriptMenu_statusHide');
  1797. } else {
  1798. this.status.classList.remove('scriptMenu_statusHide');
  1799. this.status.innerHTML = text;
  1800. }
  1801.  
  1802. if (typeof onclick == 'function') {
  1803. this.status.addEventListener("click", onclick, {
  1804. once: true
  1805. });
  1806. }
  1807. }
  1808.  
  1809. /**
  1810. * Добавление текстового элемента
  1811. * @param {String} text текст
  1812. * @param {Function} func функция по клику
  1813. * @param {HTMLDivElement} main родитель
  1814. */
  1815. this.addHeader = (text, func, main) => {
  1816. main = main || this.mainMenu;
  1817. const header = document.createElement('div');
  1818. header.classList.add('scriptMenu_header');
  1819. header.innerHTML = text;
  1820. if (typeof func == 'function') {
  1821. header.addEventListener('click', func);
  1822. }
  1823. main.appendChild(header);
  1824. }
  1825.  
  1826. /**
  1827. * Добавление кнопки
  1828. * @param {String} text
  1829. * @param {Function} func
  1830. * @param {String} title
  1831. * @param {HTMLDivElement} main родитель
  1832. */
  1833. this.addButton = (text, func, title, main) => {
  1834. main = main || this.mainMenu;
  1835. const button = document.createElement('div');
  1836. button.classList.add('scriptMenu_button');
  1837. button.title = title;
  1838. button.addEventListener('click', func);
  1839. main.appendChild(button);
  1840.  
  1841. const buttonText = document.createElement('div');
  1842. buttonText.classList.add('scriptMenu_buttonText');
  1843. buttonText.innerText = text;
  1844. button.appendChild(buttonText);
  1845. this.buttons.push(button);
  1846.  
  1847. return button;
  1848. }
  1849.  
  1850. /**
  1851. * Добавление чекбокса
  1852. * @param {String} label
  1853. * @param {String} title
  1854. * @param {HTMLDivElement} main родитель
  1855. * @returns
  1856. */
  1857. this.addCheckbox = (label, title, main) => {
  1858. main = main || this.mainMenu;
  1859. const divCheckbox = document.createElement('div');
  1860. divCheckbox.classList.add('scriptMenu_divInput');
  1861. divCheckbox.title = title;
  1862. main.appendChild(divCheckbox);
  1863.  
  1864. const checkbox = document.createElement('input');
  1865. checkbox.type = 'checkbox';
  1866. checkbox.id = 'scriptMenuCheckbox' + this.checkboxes.length;
  1867. checkbox.classList.add('scriptMenu_checkbox');
  1868. divCheckbox.appendChild(checkbox)
  1869.  
  1870. const checkboxLabel = document.createElement('label');
  1871. checkboxLabel.innerText = label;
  1872. checkboxLabel.setAttribute('for', checkbox.id);
  1873. divCheckbox.appendChild(checkboxLabel);
  1874.  
  1875. this.checkboxes.push(checkbox);
  1876. return checkbox;
  1877. }
  1878.  
  1879. /**
  1880. * Добавление поля ввода
  1881. * @param {String} title
  1882. * @param {String} placeholder
  1883. * @param {HTMLDivElement} main родитель
  1884. * @returns
  1885. */
  1886. this.addInputText = (title, placeholder, main) => {
  1887. main = main || this.mainMenu;
  1888. const divInputText = document.createElement('div');
  1889. divInputText.classList.add('scriptMenu_divInputText');
  1890. divInputText.title = title;
  1891. main.appendChild(divInputText);
  1892.  
  1893. const newInputText = document.createElement('input');
  1894. newInputText.type = 'text';
  1895. if (placeholder) {
  1896. newInputText.placeholder = placeholder;
  1897. }
  1898. newInputText.classList.add('scriptMenu_InputText');
  1899. divInputText.appendChild(newInputText)
  1900. return newInputText;
  1901. }
  1902.  
  1903. /**
  1904. * Добавляет раскрывающийся блок
  1905. * @param {String} summary
  1906. * @param {String} name
  1907. * @returns
  1908. */
  1909. this.addDetails = (summaryText, name = null) => {
  1910. const details = document.createElement('details');
  1911. details.classList.add('scriptMenu_Details');
  1912. this.mainMenu.appendChild(details);
  1913.  
  1914. const summary = document.createElement('summary');
  1915. summary.classList.add('scriptMenu_Summary');
  1916. summary.innerText = summaryText;
  1917. if (name) {
  1918. const self = this;
  1919. details.open = this.option.showDetails[name];
  1920. details.dataset.name = name;
  1921. summary.addEventListener('click', () => {
  1922. self.option.showDetails[details.dataset.name] = !details.open;
  1923. self.saveShowDetails(self.option.showDetails);
  1924. });
  1925. }
  1926. details.appendChild(summary);
  1927.  
  1928. return details;
  1929. }
  1930.  
  1931. /**
  1932. * Сохранение состояния развенутости блоков details
  1933. * @param {*} value
  1934. */
  1935. this.saveShowDetails = (value) => {
  1936. localStorage.setItem('scriptMenu_showDetails', JSON.stringify(value));
  1937. }
  1938.  
  1939. /**
  1940. * Загрузка состояния развенутости блоков details
  1941. * @returns
  1942. */
  1943. this.loadShowDetails = () => {
  1944. let showDetails = localStorage.getItem('scriptMenu_showDetails');
  1945.  
  1946. if (!showDetails) {
  1947. return {};
  1948. }
  1949.  
  1950. try {
  1951. showDetails = JSON.parse(showDetails);
  1952. } catch (e) {
  1953. return {};
  1954. }
  1955.  
  1956. return showDetails;
  1957. }
  1958. });
  1959. /** База данных */
  1960. class Database {
  1961. constructor(dbName, storeName) {
  1962. this.dbName = dbName;
  1963. this.storeName = storeName;
  1964. this.db = null;
  1965. }
  1966.  
  1967. async open() {
  1968. return new Promise((resolve, reject) => {
  1969. const request = indexedDB.open(this.dbName);
  1970.  
  1971. request.onerror = () => {
  1972. reject(new Error(`Failed to open database ${this.dbName}`));
  1973. };
  1974.  
  1975. request.onsuccess = () => {
  1976. this.db = request.result;
  1977. resolve();
  1978. };
  1979.  
  1980. request.onupgradeneeded = (event) => {
  1981. const db = event.target.result;
  1982. if (!db.objectStoreNames.contains(this.storeName)) {
  1983. db.createObjectStore(this.storeName);
  1984. }
  1985. };
  1986. });
  1987. }
  1988.  
  1989. async set(key, value) {
  1990. return new Promise((resolve, reject) => {
  1991. const transaction = this.db.transaction([this.storeName], 'readwrite');
  1992. const store = transaction.objectStore(this.storeName);
  1993. const request = store.put(value, key);
  1994.  
  1995. request.onerror = () => {
  1996. reject(new Error(`Failed to save value with key ${key}`));
  1997. };
  1998.  
  1999. request.onsuccess = () => {
  2000. resolve();
  2001. };
  2002. });
  2003. }
  2004.  
  2005. async get(key, def) {
  2006. return new Promise((resolve, reject) => {
  2007. const transaction = this.db.transaction([this.storeName], 'readonly');
  2008. const store = transaction.objectStore(this.storeName);
  2009. const request = store.get(key);
  2010.  
  2011. request.onerror = () => {
  2012. resolve(def);
  2013. };
  2014.  
  2015. request.onsuccess = () => {
  2016. resolve(request.result);
  2017. };
  2018. });
  2019. }
  2020.  
  2021. async delete(key) {
  2022. return new Promise((resolve, reject) => {
  2023. const transaction = this.db.transaction([this.storeName], 'readwrite');
  2024. const store = transaction.objectStore(this.storeName);
  2025. const request = store.delete(key);
  2026.  
  2027. request.onerror = () => {
  2028. reject(new Error(`Failed to delete value with key ${key}`));
  2029. };
  2030.  
  2031. request.onsuccess = () => {
  2032. resolve();
  2033. };
  2034. });
  2035. }
  2036. }
  2037. /** Возвращает сохраненное значение */
  2038. function getSaveVal(saveName, def) {
  2039. const result = storage.get(saveName, def);
  2040. return result;
  2041. }
  2042. /** Сохраняет значение */
  2043. function setSaveVal(saveName, value) {
  2044. storage.set(saveName, value);
  2045. }
  2046. /** Инициализация базы данных */
  2047. const db = new Database(GM_info.script.name, 'settings');
  2048. /** Хранилище данных */
  2049. const storage = {
  2050. userId: 0,
  2051. /** Значения по умолчанию */
  2052. values: [
  2053. ...Object.entries(checkboxes).map(e => ({ [e[0]]: e[1].default })),
  2054. ...Object.entries(inputs).map(e => ({ [e[0]]: e[1].default })),
  2055. ].reduce((acc, obj) => ({ ...acc, ...obj }), {}),
  2056. name: GM_info.script.name,
  2057. get: function (key, def) {
  2058. if (key in this.values) {
  2059. return this.values[key];
  2060. }
  2061. return def;
  2062. },
  2063. set: function (key, value) {
  2064. this.values[key] = value;
  2065. db.set(this.userId, this.values).catch(
  2066. e => null
  2067. );
  2068. localStorage[this.name + ':' + key] = value;
  2069. },
  2070. delete: function (key) {
  2071. delete this.values[key];
  2072. db.set(this.userId, this.values);
  2073. delete localStorage[this.name + ':' + key];
  2074. }
  2075. }
  2076. /** Возвращает все ключи из localStorage которые начинаются с prefix (для миграции) */
  2077. function getAllValuesStartingWith(prefix) {
  2078. const values = [];
  2079. for (let i = 0; i < localStorage.length; i++) {
  2080. const key = localStorage.key(i);
  2081. if (key.startsWith(prefix)) {
  2082. const val = localStorage.getItem(key);
  2083. const keyValue = key.split(':')[1];
  2084. values.push({ key: keyValue, val });
  2085. }
  2086. }
  2087. return values;
  2088. }
  2089. /** Открывает или мигрирует в базу данных */
  2090. async function openOrMigrateDatabase(userId) {
  2091. storage.userId = userId;
  2092. try {
  2093. await db.open();
  2094. } catch(e) {
  2095. return;
  2096. }
  2097. let settings = await db.get(userId, false);
  2098.  
  2099. if (settings) {
  2100. storage.values = settings;
  2101. return;
  2102. }
  2103.  
  2104. const values = getAllValuesStartingWith(GM_info.script.name);
  2105. for (const value of values) {
  2106. let val = null;
  2107. try {
  2108. val = JSON.parse(value.val);
  2109. } catch {
  2110. break;
  2111. }
  2112. storage.values[value.key] = val;
  2113. }
  2114. await db.set(userId, storage.values);
  2115. }
  2116. /** Отправка экспедиций */
  2117. function checkExpedition() {
  2118. return new Promise((resolve, reject) => {
  2119. const expedition = new Expedition(resolve, reject);
  2120. expedition.start();
  2121. });
  2122. }
  2123.  
  2124. class Expedition {
  2125. checkExpedInfo = {
  2126. calls: [{
  2127. name: "expeditionGet",
  2128. args: {},
  2129. ident: "expeditionGet"
  2130. }, {
  2131. name: "heroGetAll",
  2132. args: {},
  2133. ident: "heroGetAll"
  2134. }]
  2135. }
  2136.  
  2137. constructor(resolve, reject) {
  2138. this.resolve = resolve;
  2139. this.reject = reject;
  2140. }
  2141.  
  2142. async start() {
  2143. const data = await Send(JSON.stringify(this.checkExpedInfo));
  2144.  
  2145. const expedInfo = data.results[0].result.response;
  2146. const dataHeroes = data.results[1].result.response;
  2147. const dataExped = { useHeroes: [], exped: [] };
  2148. const calls = [];
  2149.  
  2150. /** Добавляем экспедиции для сбора */
  2151. for (var n in expedInfo) {
  2152. const exped = expedInfo[n];
  2153. const dateNow = (Date.now() / 1000);
  2154. if (exped.status == 2 && exped.endTime != 0 && dateNow > exped.endTime) {
  2155. calls.push({
  2156. name: "expeditionFarm",
  2157. args: { expeditionId: exped.id },
  2158. ident: "expeditionFarm_" + exped.id
  2159. });
  2160. } else {
  2161. dataExped.useHeroes = dataExped.useHeroes.concat(exped.heroes);
  2162. }
  2163. if (exped.status == 1) {
  2164. dataExped.exped.push({ id: exped.id, power: exped.power });
  2165. }
  2166. }
  2167. dataExped.exped = dataExped.exped.sort((a, b) => (b.power - a.power));
  2168.  
  2169. /** Собираем список героев */
  2170. const heroesArr = [];
  2171. for (let n in dataHeroes) {
  2172. const hero = dataHeroes[n];
  2173. if (hero.xp > 0 && !dataExped.useHeroes.includes(hero.id)) {
  2174. heroesArr.push({ id: hero.id, power: hero.power })
  2175. }
  2176. }
  2177.  
  2178. /** Добавляем экспедиции для отправки */
  2179. heroesArr.sort((a, b) => (a.power - b.power));
  2180. for (const exped of dataExped.exped) {
  2181. let heroesIds = this.selectionHeroes(heroesArr, exped.power);
  2182. if (heroesIds && heroesIds.length > 4) {
  2183. for (let q in heroesArr) {
  2184. if (heroesIds.includes(heroesArr[q].id)) {
  2185. delete heroesArr[q];
  2186. }
  2187. }
  2188. calls.push({
  2189. name: "expeditionSendHeroes",
  2190. args: {
  2191. expeditionId: exped.id,
  2192. heroes: heroesIds
  2193. },
  2194. ident: "expeditionSendHeroes_" + exped.id
  2195. });
  2196. }
  2197. }
  2198.  
  2199. await Send(JSON.stringify({ calls }));
  2200. this.end();
  2201. }
  2202.  
  2203. /** Подбор героев для экспедиций */
  2204. selectionHeroes(heroes, power) {
  2205. const resultHeroers = [];
  2206. const heroesIds = [];
  2207. for (let q = 0; q < 5; q++) {
  2208. for (let i in heroes) {
  2209. let hero = heroes[i];
  2210. if (heroesIds.includes(hero.id)) {
  2211. continue;
  2212. }
  2213.  
  2214. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  2215. const need = Math.round((power - summ) / (5 - resultHeroers.length));
  2216. if (hero.power > need) {
  2217. resultHeroers.push(hero);
  2218. heroesIds.push(hero.id);
  2219. break;
  2220. }
  2221. }
  2222. }
  2223.  
  2224. const summ = resultHeroers.reduce((acc, hero) => acc + hero.power, 0);
  2225. if (summ < power) {
  2226. return false;
  2227. }
  2228. return heroesIds;
  2229. }
  2230.  
  2231. /** Завершает скрипт экспедиции */
  2232. end() {
  2233. setProgress('Экспедиции отправлены', true);
  2234. this.resolve()
  2235. }
  2236. }
  2237. // Отправка запроса
  2238. function send(json, callback, pr) {
  2239. /** Получаем заголовки предыдущего перехваченого запроса */
  2240. let headers = lastHeaders;
  2241. /** Увеличиваем заголовок идетификатора запроса на 1 */
  2242. headers["X-Request-Id"]++;
  2243. /** Расчитываем заголовок с сигнатурой */
  2244. headers["X-Auth-Signature"] = getSignature(headers, json);
  2245. /** Создаем новый AJAX запрос */
  2246. let xhr = new XMLHttpRequest;
  2247. /** Указываем ранее сохраненный URL для API запросов */
  2248. xhr.open('POST', apiUrl, true);
  2249. /** Добавляем функцию к событию смены статуса запроса */
  2250. xhr.onreadystatechange = function() {
  2251. /** Если результат запроса получен вызываем колбек функцию */
  2252. if(xhr.readyState == 4) {
  2253. let randTimeout = Math.random() * 200 + 200;
  2254. setTimeout(callback, randTimeout, xhr.response, pr);
  2255. }
  2256. };
  2257. /** Указываем тип запроса */
  2258. xhr.responseType = 'json';
  2259. /** Задаем заголовки запроса */
  2260. for(let nameHeader in headers) {
  2261. let head = headers[nameHeader];
  2262. xhr.setRequestHeader(nameHeader, head);
  2263. }
  2264. /** Отправляем запрос */
  2265. xhr.send(json);
  2266. }
  2267.  
  2268. function testDungeon() {
  2269. return new Promise((resolve, reject) => {
  2270. const dung = new executeDungeon(resolve, reject);
  2271. const titanit = getInput('countTitanit');
  2272. dung.start(titanit);
  2273. });
  2274. }
  2275.  
  2276. /** Прохождение подземелья */
  2277. function executeDungeon(resolve, reject) {
  2278. dungeonActivity = 0;
  2279. maxDungeonActivity = 150;
  2280.  
  2281. titanGetAll = [];
  2282.  
  2283. teams = {
  2284. heroes: [],
  2285. earth: [],
  2286. fire: [],
  2287. neutral: [],
  2288. water: [],
  2289. }
  2290.  
  2291. titanStats = [];
  2292.  
  2293. titansStates = {};
  2294.  
  2295. callsExecuteDungeon = {
  2296. calls: [{
  2297. name: "dungeonGetInfo",
  2298. args: {},
  2299. ident: "dungeonGetInfo"
  2300. }, {
  2301. name: "teamGetAll",
  2302. args: {},
  2303. ident: "teamGetAll"
  2304. }, {
  2305. name: "teamGetFavor",
  2306. args: {},
  2307. ident: "teamGetFavor"
  2308. }, {
  2309. name: "clanGetInfo",
  2310. args: {},
  2311. ident: "clanGetInfo"
  2312. }, {
  2313. name: "titanGetAll",
  2314. args: {},
  2315. ident: "titanGetAll"
  2316. }]
  2317. }
  2318.  
  2319. this.start = function(titanit) {
  2320. maxDungeonActivity = titanit || 75;
  2321. send(JSON.stringify(callsExecuteDungeon), startDungeon);
  2322. }
  2323.  
  2324. /** Получаем данные по подземелью */
  2325. function startDungeon(e) {
  2326. res = e.results;
  2327. dungeonGetInfo = res[0].result.response;
  2328. if (!dungeonGetInfo) {
  2329. endDungeon('noDungeon', res);
  2330. return;
  2331. }
  2332. teamGetAll = res[1].result.response;
  2333. teamGetFavor = res[2].result.response;
  2334. dungeonActivity = res[3].result.response.stat.todayDungeonActivity;
  2335. titanGetAll = Object.values(res[4].result.response);
  2336.  
  2337. teams.hero = {
  2338. favor: teamGetFavor.dungeon_hero,
  2339. heroes: teamGetAll.dungeon_hero.filter(id => id < 6000),
  2340. teamNum: 0,
  2341. }
  2342. heroPet = teamGetAll.dungeon_hero.filter(id => id >= 6000).pop();
  2343. if (heroPet) {
  2344. teams.hero.pet = heroPet;
  2345. }
  2346.  
  2347. teams.neutral = {
  2348. favor: {},
  2349. heroes: getTitanTeam(titanGetAll, 'neutral'),
  2350. teamNum: 0,
  2351. };
  2352. teams.water = {
  2353. favor: {},
  2354. heroes: getTitanTeam(titanGetAll, 'water'),
  2355. teamNum: 0,
  2356. };
  2357. teams.fire = {
  2358. favor: {},
  2359. heroes: getTitanTeam(titanGetAll, 'fire'),
  2360. teamNum: 0,
  2361. };
  2362. teams.earth = {
  2363. favor: {},
  2364. heroes: getTitanTeam(titanGetAll, 'earth'),
  2365. teamNum: 0,
  2366. };
  2367.  
  2368.  
  2369. checkFloor(dungeonGetInfo);
  2370. }
  2371.  
  2372. function getTitanTeam(titans, type) {
  2373. switch (type) {
  2374. case 'neutral':
  2375. return titans.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  2376. case 'water':
  2377. return titans.filter(e => e.id.toString().slice(2, 3) == '0').map(e => e.id);
  2378. case 'fire':
  2379. return titans.filter(e => e.id.toString().slice(2, 3) == '1').map(e => e.id);
  2380. case 'earth':
  2381. return titans.filter(e => e.id.toString().slice(2, 3) == '2').map(e => e.id);
  2382. }
  2383. }
  2384.  
  2385. function fixTitanTeam(titans) {
  2386. titans.heroes = titans.heroes.filter(e => !titansStates[e]?.isDead);
  2387. return titans;
  2388. }
  2389.  
  2390. /** Проверяем этаж */
  2391. function checkFloor(dungeonInfo) {
  2392. if (!('floor' in dungeonInfo) || dungeonInfo.floor?.state == 2) {
  2393. saveProgress();
  2394. return;
  2395. }
  2396. // console.log(dungeonInfo, dungeonActivity);
  2397. setProgress('Dungeon: Титанит ' + dungeonActivity + '/' + maxDungeonActivity);
  2398. if (dungeonActivity >= maxDungeonActivity) {
  2399. endDungeon('endDungeon');
  2400. return;
  2401. }
  2402. titansStates = dungeonInfo.states.titans;
  2403. titanStats = titanObjToArray(titansStates);
  2404. floorChoices = dungeonInfo.floor.userData;
  2405. floorType = dungeonInfo.floorType;
  2406. primeElement = dungeonInfo.elements.prime;
  2407. if (floorType == "battle") {
  2408. promises = [];
  2409. for (let teamNum in floorChoices) {
  2410. attackerType = floorChoices[teamNum].attackerType;
  2411. promises.push(startBattle(teamNum, attackerType));
  2412. }
  2413. Promise.all(promises)
  2414. .then(processingPromises);
  2415. }
  2416. }
  2417.  
  2418. function processingPromises(results) {
  2419. selectInfo = results[0];
  2420. if (results.length < 2) {
  2421. // console.log(selectInfo);
  2422. endBattle(selectInfo);
  2423. return;
  2424. }
  2425.  
  2426. selectInfo = false;
  2427. minRes = 1e10;
  2428. for (let info of results) {
  2429. diffXP = diffTitanXP(info.progress[0].attackers.heroes);
  2430. diffRes = diffXP;
  2431. if (info.attackerType == 'neutral') {
  2432. diffRes /= 2;
  2433. diffRes -= 4;
  2434. }
  2435. if (info.attackerType == primeElement) {
  2436. diffRes /= 2;
  2437. diffRes -= 5;
  2438. }
  2439. info.diffXP = diffXP
  2440. info.diffRes = diffRes
  2441. if (!info.result.win) {
  2442. continue;
  2443. }
  2444. if (diffRes < minRes) {
  2445. selectInfo = info;
  2446. minRes = diffRes;
  2447. }
  2448. }
  2449. // console.log(selectInfo.teamNum, results);
  2450. if (!selectInfo) {
  2451. endDungeon('dungeonEndBattle\n', results);
  2452. return;
  2453. }
  2454.  
  2455. startBattle(selectInfo.teamNum, selectInfo.attackerType)
  2456. .then(endBattle);
  2457. }
  2458.  
  2459. /** Начинаем бой */
  2460. function startBattle(teamNum, attackerType) {
  2461. return new Promise(function (resolve, reject) {
  2462. args = fixTitanTeam(teams[attackerType]);
  2463. args.teamNum = teamNum;
  2464. startBattleCall = {
  2465. calls: [{
  2466. name: "dungeonStartBattle",
  2467. args,
  2468. ident: "body"
  2469. }]
  2470. }
  2471. send(JSON.stringify(startBattleCall), resultBattle, {
  2472. resolve,
  2473. teamNum,
  2474. attackerType
  2475. });
  2476. });
  2477. }
  2478. /** Возращает резульат боя в промис */
  2479. function resultBattle(resultBattles, args) {
  2480. battleData = resultBattles.results[0].result.response;
  2481. battleType = "get_tower";
  2482. if (battleData.type == "dungeon_titan") {
  2483. battleType = "get_titan";
  2484. }
  2485. BattleCalc(battleData, battleType, function (result) {
  2486. result.teamNum = args.teamNum;
  2487. result.attackerType = args.attackerType;
  2488. args.resolve(result);
  2489. });
  2490. }
  2491. /** Заканчиваем бой */
  2492. function endBattle(battleInfo) {
  2493. if (battleInfo.result.win) {
  2494. endBattleCall = {
  2495. calls: [{
  2496. name: "dungeonEndBattle",
  2497. args: {
  2498. result: battleInfo.result,
  2499. progress: battleInfo.progress,
  2500. },
  2501. ident: "body"
  2502. }]
  2503. }
  2504. send(JSON.stringify(endBattleCall), resultEndBattle);
  2505. } else {
  2506. endDungeon('dungeonEndBattle win: false\n', battleInfo);
  2507. }
  2508. }
  2509.  
  2510. /** Получаем и обрабатываем результаты боя */
  2511. function resultEndBattle(e) {
  2512. battleResult = e.results[0].result.response;
  2513. if ('error' in battleResult) {
  2514. endDungeon('errorBattleResult', battleResult);
  2515. return;
  2516. }
  2517. dungeonGetInfo = battleResult.dungeon ?? battleResult;
  2518. dungeonActivity += battleResult.reward.dungeonActivity ?? 0;
  2519. checkFloor(dungeonGetInfo);
  2520. }
  2521.  
  2522. /** Возвращает разницу между максимальными ХП титанов и переданными */
  2523. function diffTitanXP(titans) {
  2524. sumCurrentXp = 0;
  2525. for (let i in titans) {
  2526. sumCurrentXp += titans[i].hp
  2527. }
  2528. titanIds = Object.getOwnPropertyNames(titans);
  2529. maxHP = titanStats.reduce((n, e) =>
  2530. titanIds.includes(e.id.toString()) ? n + e.hp : n
  2531. , 0);
  2532. return maxHP < sumCurrentXp ? 0 : maxHP - sumCurrentXp;
  2533. }
  2534.  
  2535. /** Преобразует объект с идетификаторами в массив с идетификаторами*/
  2536. function titanObjToArray(obj) {
  2537. let titans = [];
  2538. for (let id in obj) {
  2539. obj[id].id = id;
  2540. titans.push(obj[id]);
  2541. }
  2542. return titans;
  2543. }
  2544.  
  2545. function saveProgress() {
  2546. let saveProgressCall = {
  2547. calls: [{
  2548. name: "dungeonSaveProgress",
  2549. args: {},
  2550. ident: "body"
  2551. }]
  2552. }
  2553. send(JSON.stringify(saveProgressCall), resultEndBattle);
  2554. }
  2555.  
  2556. function endDungeon(reason, info) {
  2557. console.log(reason, info);
  2558. setProgress('Подземелье завершено', true);
  2559. resolve();
  2560. }
  2561. }
  2562.  
  2563. function testTower() {
  2564. return new Promise((resolve, reject) => {
  2565. tower = new executeTower(resolve, reject);
  2566. tower.start();
  2567. });
  2568. }
  2569.  
  2570. /** Прохождение башни */
  2571. function executeTower(resolve, reject) {
  2572. lastTowerInfo = {};
  2573.  
  2574. scullCoin = 0;
  2575.  
  2576. heroGetAll = [];
  2577.  
  2578. heroesStates = {};
  2579.  
  2580. argsBattle = {
  2581. heroes: [],
  2582. favor: {},
  2583. };
  2584.  
  2585. callsExecuteTower = {
  2586. calls: [{
  2587. name: "towerGetInfo",
  2588. args: {},
  2589. ident: "towerGetInfo"
  2590. }, {
  2591. name: "teamGetAll",
  2592. args: {},
  2593. ident: "teamGetAll"
  2594. }, {
  2595. name: "teamGetFavor",
  2596. args: {},
  2597. ident: "teamGetFavor"
  2598. }, {
  2599. name: "inventoryGet",
  2600. args: {},
  2601. ident: "inventoryGet"
  2602. }, {
  2603. name: "heroGetAll",
  2604. args: {},
  2605. ident: "heroGetAll"
  2606. }]
  2607. }
  2608.  
  2609. buffIds = [
  2610. { id: 0, cost: 0, isBuy: false }, // заглушка
  2611. { id: 1, cost: 1, isBuy: true }, // 3% атака
  2612. { id: 2, cost: 6, isBuy: true }, // 2% атака
  2613. { id: 3, cost: 16, isBuy: true }, // 4% атака
  2614. { id: 4, cost: 40, isBuy: true }, // 8% атака
  2615. { id: 5, cost: 1, isBuy: true }, // 10% броня
  2616. { id: 6, cost: 6, isBuy: true }, // 5% броня
  2617. { id: 7, cost: 16, isBuy: true }, // 10% броня
  2618. { id: 8, cost: 40, isBuy: true }, // 20% броня
  2619. { id: 9, cost: 1, isBuy: true }, // 10% защита от магии
  2620. { id: 10, cost: 6, isBuy: true }, // 5% защита от магии
  2621. { id: 11, cost: 16, isBuy: true }, // 10% защита от магии
  2622. { id: 12, cost: 40, isBuy: true }, // 20% защита от магии
  2623. { id: 13, cost: 1, isBuy: false }, // 40% здоровья герою
  2624. { id: 14, cost: 6, isBuy: false }, // 40% здоровья герою
  2625. { id: 15, cost: 16, isBuy: false }, // 80% здоровья герою
  2626. { id: 16, cost: 40, isBuy: false }, // 40% здоровья всем героям
  2627. { id: 17, cost: 1, isBuy: false }, // 40% энергии герою
  2628. { id: 18, cost: 3, isBuy: false }, // 40% энергии герою
  2629. { id: 19, cost: 8, isBuy: false }, // 80% энергии герою
  2630. { id: 20, cost: 20, isBuy: false }, // 40% энергии всем героям
  2631. { id: 21, cost: 40, isBuy: false }, // Воскрешение героя
  2632. ]
  2633.  
  2634. this.start = function () {
  2635. send(JSON.stringify(callsExecuteTower), startTower);
  2636. }
  2637.  
  2638. /** Получаем данные по подземелью */
  2639. function startTower(e) {
  2640. res = e.results;
  2641. towerGetInfo = res[0].result.response;
  2642. if (!towerGetInfo) {
  2643. endTower('noTower', res);
  2644. return;
  2645. }
  2646. teamGetAll = res[1].result.response;
  2647. teamGetFavor = res[2].result.response;
  2648. inventoryGet = res[3].result.response;
  2649. heroGetAll = Object.values(res[4].result.response);
  2650.  
  2651. scullCoin = inventoryGet.coin[7] ?? 0;
  2652.  
  2653. argsBattle.favor = teamGetFavor.tower;
  2654. argsBattle.heroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);;
  2655. pet = teamGetAll.tower.filter(id => id >= 6000).pop();
  2656. if (pet) {
  2657. argsBattle.pet = pet;
  2658. }
  2659.  
  2660. checkFloor(towerGetInfo);
  2661. }
  2662.  
  2663. function fixHeroesTeam(argsBattle) {
  2664. let fixHeroes = argsBattle.heroes.filter(e => !heroesStates[e]?.isDead);
  2665. if (fixHeroes.length < 5) {
  2666. heroGetAll = heroGetAll.filter(e => !heroesStates[e.id]?.isDead);
  2667. fixHeroes = heroGetAll.sort((a, b) => b.power - a.power).slice(0, 5).map(e => e.id);
  2668. Object.keys(argsBattle.favor).forEach(e => {
  2669. if (!fixHeroes.includes(+e)) {
  2670. delete argsBattle.favor[e];
  2671. }
  2672. })
  2673. }
  2674. argsBattle.heroes = fixHeroes;
  2675. return argsBattle;
  2676. }
  2677.  
  2678. /** Проверяем этаж */
  2679. function checkFloor(towerInfo) {
  2680. lastTowerInfo = towerInfo;
  2681. maySkipFloor = +towerInfo.maySkipFloor;
  2682. floorNumber = +towerInfo.floorNumber;
  2683. heroesStates = towerInfo.states.heroes;
  2684. floorInfo = towerInfo.floor;
  2685.  
  2686. /** Открыт ли на этаже хоть один сундук */
  2687. isOpenChest = false;
  2688. if (towerInfo.floorType == "chest") {
  2689. isOpenChest = towerInfo.floor.chests.reduce((n, e) => n + e.opened, 0);
  2690. }
  2691.  
  2692. setProgress('Башня: Этаж ' + floorNumber);
  2693. if (floorNumber > 49) {
  2694. if (isOpenChest) {
  2695. endTower('alreadyOpenChest 50 floor', floorNumber);
  2696. return;
  2697. }
  2698. }
  2699. // Если сундук открыт и можно скипать этажи, то переходим дальше
  2700. if (towerInfo.mayFullSkip && +towerInfo.teamLevel == 130) {
  2701. if (isOpenChest) {
  2702. nextOpenChest(floorNumber);
  2703. } else {
  2704. nextChestOpen(floorNumber);
  2705. }
  2706. return;
  2707. }
  2708.  
  2709. // console.log(towerInfo, scullCoin);
  2710. switch (towerInfo.floorType) {
  2711. case "battle":
  2712. if (floorNumber <= maySkipFloor) {
  2713. skipFloor();
  2714. return;
  2715. }
  2716. if (floorInfo.state == 2) {
  2717. nextFloor();
  2718. return;
  2719. }
  2720. startBattle().then(endBattle);
  2721. return;
  2722. case "buff":
  2723. checkBuff(towerInfo);
  2724. return;
  2725. case "chest":
  2726. openChest(floorNumber);
  2727. return;
  2728. default:
  2729. console.log('!', towerInfo.floorType, towerInfo);
  2730. break;
  2731. }
  2732. }
  2733.  
  2734. /** Начинаем бой */
  2735. function startBattle() {
  2736. return new Promise(function (resolve, reject) {
  2737. towerStartBattle = {
  2738. calls: [{
  2739. name: "towerStartBattle",
  2740. args: fixHeroesTeam(argsBattle),
  2741. ident: "body"
  2742. }]
  2743. }
  2744. send(JSON.stringify(towerStartBattle), resultBattle, resolve);
  2745. });
  2746. }
  2747. /** Возращает резульат боя в промис */
  2748. function resultBattle(resultBattles, resolve) {
  2749. battleData = resultBattles.results[0].result.response;
  2750. battleType = "get_tower";
  2751. BattleCalc(battleData, battleType, function (result) {
  2752. resolve(result);
  2753. });
  2754. }
  2755. /** Заканчиваем бой */
  2756. function endBattle(battleInfo) {
  2757. if (battleInfo.result.win) {
  2758. endBattleCall = {
  2759. calls: [{
  2760. name: "towerEndBattle",
  2761. args: {
  2762. result: battleInfo.result,
  2763. progress: battleInfo.progress,
  2764. },
  2765. ident: "body"
  2766. }]
  2767. }
  2768. send(JSON.stringify(endBattleCall), resultEndBattle);
  2769. } else {
  2770. endTower('towerEndBattle win: false\n', battleInfo);
  2771. }
  2772. }
  2773.  
  2774. /** Получаем и обрабатываем результаты боя */
  2775. function resultEndBattle(e) {
  2776. battleResult = e.results[0].result.response;
  2777. if ('error' in battleResult) {
  2778. endTower('errorBattleResult', battleResult);
  2779. return;
  2780. }
  2781. if ('reward' in battleResult) {
  2782. scullCoin += battleResult.reward?.coin[7] ?? 0;
  2783. }
  2784. nextFloor();
  2785. }
  2786.  
  2787. function nextFloor() {
  2788. nextFloorCall = {
  2789. calls: [{
  2790. name: "towerNextFloor",
  2791. args: {},
  2792. ident: "body"
  2793. }]
  2794. }
  2795. send(JSON.stringify(nextFloorCall), checkDataFloor);
  2796. }
  2797.  
  2798. function openChest(floorNumber) {
  2799. floorNumber = floorNumber || 0;
  2800. openChestCall = {
  2801. calls: [{
  2802. name: "towerOpenChest",
  2803. args: {
  2804. num: 2
  2805. },
  2806. ident: "body"
  2807. }]
  2808. }
  2809. send(JSON.stringify(openChestCall), floorNumber < 50 ? nextFloor : lastChest);
  2810. }
  2811.  
  2812. function lastChest() {
  2813. endTower('openChest 50 floor', floorNumber);
  2814. }
  2815.  
  2816. function skipFloor() {
  2817. skipFloorCall = {
  2818. calls: [{
  2819. name: "towerSkipFloor",
  2820. args: {},
  2821. ident: "body"
  2822. }]
  2823. }
  2824. send(JSON.stringify(skipFloorCall), checkDataFloor);
  2825. }
  2826.  
  2827. function checkBuff(towerInfo) {
  2828. buffArr = towerInfo.floor;
  2829. promises = [];
  2830. for (let buff of buffArr) {
  2831. buffInfo = buffIds[buff.id];
  2832. if (buffInfo.isBuy && buffInfo.cost <= scullCoin) {
  2833. scullCoin -= buffInfo.cost;
  2834. promises.push(buyBuff(buff.id));
  2835. }
  2836. }
  2837. Promise.all(promises).then(nextFloor);
  2838. }
  2839.  
  2840. function buyBuff(buffId) {
  2841. return new Promise(function (resolve, reject) {
  2842. buyBuffCall = {
  2843. calls: [{
  2844. name: "towerBuyBuff",
  2845. args: {
  2846. buffId
  2847. },
  2848. ident: "body"
  2849. }]
  2850. }
  2851. send(JSON.stringify(buyBuffCall), resolve);
  2852. });
  2853. }
  2854.  
  2855. function checkDataFloor(result) {
  2856. towerInfo = result.results[0].result.response;
  2857. if ('reward' in towerInfo && towerInfo.reward?.coin) {
  2858. scullCoin += towerInfo.reward?.coin[7] ?? 0;
  2859. }
  2860. if ('tower' in towerInfo) {
  2861. towerInfo = towerInfo.tower;
  2862. }
  2863. if ('skullReward' in towerInfo) {
  2864. scullCoin += towerInfo.skullReward?.coin[7] ?? 0;
  2865. }
  2866. checkFloor(towerInfo);
  2867. }
  2868. /** Получаем награды башни */
  2869. function farmTowerRewards(reason) {
  2870. let { pointRewards, points } = lastTowerInfo;
  2871. let pointsAll = Object.getOwnPropertyNames(pointRewards);
  2872. let farmPoints = pointsAll.filter(e => +e <= +points && !pointRewards[e]);
  2873. if (!farmPoints.length) {
  2874. return;
  2875. }
  2876. let farmTowerRewardsCall = {
  2877. calls: [{
  2878. name: "tower_farmPointRewards",
  2879. args: {
  2880. points: farmPoints
  2881. },
  2882. ident: "tower_farmPointRewards"
  2883. }]
  2884. }
  2885.  
  2886. if (scullCoin > 0 && reason == 'openChest 50 floor') {
  2887. farmTowerRewardsCall.calls.push({
  2888. name: "tower_farmSkullReward",
  2889. args: {},
  2890. ident: "tower_farmSkullReward"
  2891. });
  2892. }
  2893.  
  2894. send(JSON.stringify(farmTowerRewardsCall), () => { });
  2895. }
  2896.  
  2897. function fullSkipTower() {
  2898. /** Следующий сундук */
  2899. function nextChest(n) {
  2900. return {
  2901. name: "towerNextChest",
  2902. args: {},
  2903. ident: "group_" + n + "_body"
  2904. }
  2905. }
  2906. /** Открыть сундук */
  2907. function openChest(n) {
  2908. return {
  2909. name: "towerOpenChest",
  2910. args: {
  2911. "num": 2
  2912. },
  2913. ident: "group_" + n + "_body"
  2914. }
  2915. }
  2916.  
  2917. const fullSkipTowerCall = {
  2918. calls: []
  2919. }
  2920.  
  2921. let n = 0;
  2922. for (let i = 0; i < 15; i++) {
  2923. fullSkipTowerCall.calls.push(nextChest(++n));
  2924. fullSkipTowerCall.calls.push(openChest(++n));
  2925. }
  2926.  
  2927. send(JSON.stringify(fullSkipTowerCall), data => {
  2928. data.results[0] = data.results[28];
  2929. checkDataFloor(data);
  2930. });
  2931. }
  2932.  
  2933. function nextChestOpen(floorNumber) {
  2934. const calls = [{
  2935. name: "towerOpenChest",
  2936. args: {
  2937. num: 2
  2938. },
  2939. ident: "towerOpenChest"
  2940. }];
  2941.  
  2942. Send(JSON.stringify({ calls })).then(e => {
  2943. nextOpenChest(floorNumber);
  2944. });
  2945. }
  2946.  
  2947. function nextOpenChest(floorNumber) {
  2948. if (floorNumber > 49) {
  2949. endTower('openChest 50 floor', floorNumber);
  2950. return;
  2951. }
  2952. if (floorNumber == 1) {
  2953. fullSkipTower();
  2954. return;
  2955. }
  2956.  
  2957. let nextOpenChestCall = {
  2958. calls: [{
  2959. name: "towerNextChest",
  2960. args: {},
  2961. ident: "towerNextChest"
  2962. }, {
  2963. name: "towerOpenChest",
  2964. args: {
  2965. num: 2
  2966. },
  2967. ident: "towerOpenChest"
  2968. }]
  2969. }
  2970. send(JSON.stringify(nextOpenChestCall), checkDataFloor);
  2971. }
  2972.  
  2973. function endTower(reason, info) {
  2974. console.log(reason, info);
  2975. if (reason != 'noTower') {
  2976. farmTowerRewards(reason);
  2977. }
  2978. setProgress('Башня выполнена!', true);
  2979. resolve();
  2980. }
  2981.  
  2982. }
  2983.  
  2984. function testTitanArena() {
  2985. return new Promise((resolve, reject) => {
  2986. titAren = new executeTitanArena(resolve, reject);
  2987. titAren.start();
  2988. });
  2989. }
  2990.  
  2991. /** Прохождение арены титанов */
  2992. function executeTitanArena(resolve, reject) {
  2993. let titan_arena = [];
  2994. let finishListBattle = [];
  2995. /** Идетификатор текущей пачки */
  2996. let currentRival = 0;
  2997. /** Количество попыток добития пачки */
  2998. let attempts = 0;
  2999. /** Была ли попытка добития текущего тира */
  3000. let isCheckCurrentTier = false;
  3001. /** Текущий тир */
  3002. let currTier = 0;
  3003. /** Количество битв на текущем тире */
  3004. let countRivalsTier = 0;
  3005.  
  3006. let callsStart = {
  3007. calls: [{
  3008. name: "titanArenaGetStatus",
  3009. args: {},
  3010. ident: "titanArenaGetStatus"
  3011. }, {
  3012. name: "teamGetAll",
  3013. args: {},
  3014. ident: "teamGetAll"
  3015. }]
  3016. }
  3017.  
  3018. this.start = function () {
  3019. send(JSON.stringify(callsStart), startTitanArena);
  3020. }
  3021.  
  3022. function startTitanArena(data) {
  3023. let titanArena = data.results[0].result.response;
  3024. if (titanArena.status == 'disabled') {
  3025. endTitanArena('disabled', titanArena);
  3026. return;
  3027. }
  3028.  
  3029. let teamGetAll = data.results[1].result.response;
  3030. titan_arena = teamGetAll.titan_arena;
  3031.  
  3032. checkTier(titanArena)
  3033. }
  3034.  
  3035. function checkTier(titanArena) {
  3036. if (titanArena.status == "peace_time") {
  3037. endTitanArena('Peace_time', titanArena);
  3038. return;
  3039. }
  3040. currTier = titanArena.tier;
  3041. if (currTier) {
  3042. setProgress('Турнир Стихий: Уровень ' + currTier);
  3043. }
  3044.  
  3045. if (titanArena.status == "completed_tier") {
  3046. titanArenaCompleteTier();
  3047. return;
  3048. }
  3049. /** Проверка на возможность рейда */
  3050. if (titanArena.canRaid) {
  3051. titanArenaStartRaid();
  3052. return;
  3053. }
  3054. /** Проверка была ли попытка добития текущего тира */
  3055. if (!isCheckCurrentTier) {
  3056. checkRivals(titanArena.rivals);
  3057. return;
  3058. }
  3059.  
  3060. endTitanArena('Done or not canRaid', titanArena);
  3061. }
  3062. /** Отправка информации о тире на проверку */
  3063. function checkResultInfo(data) {
  3064. let titanArena = data.results[0].result.response;
  3065. checkTier(titanArena);
  3066. }
  3067. /** Завершить текущий тир */
  3068. function titanArenaCompleteTier() {
  3069. isCheckCurrentTier = false;
  3070. let calls = [{
  3071. name: "titanArenaCompleteTier",
  3072. args: {},
  3073. ident: "body"
  3074. }];
  3075. send(JSON.stringify({calls}), checkResultInfo);
  3076. }
  3077. /** Собираем точки которые нужно добить */
  3078. function checkRivals(rivals) {
  3079. finishListBattle = [];
  3080. for (let n in rivals) {
  3081. if (rivals[n].attackScore < 250) {
  3082. finishListBattle.push(n);
  3083. }
  3084. }
  3085. console.log('checkRivals', finishListBattle);
  3086. countRivalsTier = finishListBattle.length;
  3087. roundRivals();
  3088. }
  3089. /** Выбор следующей точки для добития */
  3090. function roundRivals() {
  3091. let countRivals = finishListBattle.length;
  3092. if (!countRivals) {
  3093. // Весь тир проверен
  3094. isCheckCurrentTier = true;
  3095. titanArenaGetStatus();
  3096. return;
  3097. }
  3098. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + (countRivalsTier - countRivals + 1) + '/' + countRivalsTier);
  3099. currentRival = finishListBattle.pop();
  3100. attempts = +currentRival;
  3101. // console.log('roundRivals', currentRival);
  3102. titanArenaStartBattle(currentRival);
  3103. }
  3104. /** Начало одиночной битвы */
  3105. function titanArenaStartBattle(rivalId) {
  3106. let calls = [{
  3107. name: "titanArenaStartBattle",
  3108. args: {
  3109. rivalId: rivalId,
  3110. titans: titan_arena
  3111. },
  3112. ident: "body"
  3113. }];
  3114. send(JSON.stringify({calls}), calcResult);
  3115. }
  3116. /** Расчет результатов боя */
  3117. function calcResult(data) {
  3118. let battlesInfo = data.results[0].result.response.battle;
  3119. /** Если попытки равны номеру текущего боя делаем прерасчет */
  3120. if (attempts == currentRival) {
  3121. preCalcBattle(battlesInfo);
  3122. return;
  3123. }
  3124. /** Если попытки еще есть делаем расчет нового боя*/
  3125. if (attempts > 0) {
  3126. attempts--;
  3127. calcBattleResult(battlesInfo)
  3128. .then(resultCalcBattle);
  3129. return;
  3130. }
  3131. /** Иначе переходим к следующему сопернику */
  3132. roundRivals();
  3133. }
  3134. /** Обработка результатов расчета битвы */
  3135. function resultCalcBattle(resultBattle) {
  3136. // console.log('resultCalcBattle', currentRival, attempts, resultBattle.result.win);
  3137. /** Если текущий расчет победа или шансов нет или попытки кончились завершаем бой */
  3138. if (resultBattle.result.win || !attempts) {
  3139. titanArenaEndBattle({
  3140. progress: resultBattle.progress,
  3141. result: resultBattle.result,
  3142. rivalId: resultBattle.battleData.typeId
  3143. });
  3144. return;
  3145. }
  3146. /** Если не победа и есть попытки начинаем новый бой */
  3147. titanArenaStartBattle(resultBattle.battleData.typeId);
  3148. }
  3149. /** Возращает промис расчета результатов битвы */
  3150. function getBattleInfo(battle, isRandSeed) {
  3151. return new Promise(function (resolve) {
  3152. if (isRandSeed) {
  3153. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  3154. }
  3155. // console.log(battle.seed);
  3156. BattleCalc(battle, "get_titanClanPvp", e => resolve(e));
  3157. });
  3158. }
  3159. /** Прерасчтет битвы */
  3160. function preCalcBattle(battle) {
  3161. let actions = [getBattleInfo(battle, false)];
  3162. const countTestBattle = getInput('countTestBattle');
  3163. for (let i = 0; i < countTestBattle; i++) {
  3164. actions.push(getBattleInfo(battle, true));
  3165. }
  3166. Promise.all(actions)
  3167. .then(resultPreCalcBattle);
  3168. }
  3169. /** Обработка результатов прерасчета битвы */
  3170. function resultPreCalcBattle(e) {
  3171. let wins = e.map(n => n.result.win);
  3172. let firstBattle = e.shift();
  3173. let countWin = wins.reduce((w, s) => w + s);
  3174. let numReval = countRivalsTier - finishListBattle.length;
  3175. // setProgress('TitanArena: Уровень ' + currTier + ' Бои: ' + numReval + '/' + countRivalsTier + ' - ' + countWin + '/11');
  3176. console.log('resultPreCalcBattle', countWin + '/11' )
  3177. if (countWin > 0) {
  3178. attempts = getInput('countAutoBattle');
  3179. } else {
  3180. attempts = 0;
  3181. }
  3182. resultCalcBattle(firstBattle);
  3183. }
  3184.  
  3185. /** Завершить битву на арене */
  3186. function titanArenaEndBattle(args) {
  3187. let calls = [{
  3188. name: "titanArenaEndBattle",
  3189. args,
  3190. ident: "body"
  3191. }];
  3192. send(JSON.stringify({calls}), resultTitanArenaEndBattle);
  3193. }
  3194.  
  3195. function resultTitanArenaEndBattle(e) {
  3196. let attackScore = e.results[0].result.response.attackScore;
  3197. let numReval = countRivalsTier - finishListBattle.length;
  3198. setProgress('Турнир Стихий: Уровень ' + currTier + '</br>Бои: ' + numReval + '/' + countRivalsTier + ' - ' + attackScore);
  3199. /** TODO: Возможно стоит сделать улучшение результатов */
  3200. // console.log('resultTitanArenaEndBattle', e)
  3201. console.log('resultTitanArenaEndBattle', numReval + '/' + countRivalsTier, attempts)
  3202. roundRivals();
  3203. }
  3204. /** Состояние арены */
  3205. function titanArenaGetStatus() {
  3206. let calls = [{
  3207. name: "titanArenaGetStatus",
  3208. args: {},
  3209. ident: "body"
  3210. }];
  3211. send(JSON.stringify({calls}), checkResultInfo);
  3212. }
  3213. /** Запрос рейда арены */
  3214. function titanArenaStartRaid() {
  3215. let calls = [{
  3216. name: "titanArenaStartRaid",
  3217. args: {
  3218. titans: titan_arena
  3219. },
  3220. ident: "body"
  3221. }];
  3222. send(JSON.stringify({calls}), calcResults);
  3223. }
  3224.  
  3225. function calcResults(data) {
  3226. let battlesInfo = data.results[0].result.response;
  3227. let {attackers, rivals} = battlesInfo;
  3228.  
  3229. let promises = [];
  3230. for (let n in rivals) {
  3231. rival = rivals[n];
  3232. promises.push(calcBattleResult({
  3233. attackers: attackers,
  3234. defenders: [rival.team],
  3235. seed: rival.seed,
  3236. typeId: n,
  3237. }));
  3238. }
  3239.  
  3240. Promise.all(promises)
  3241. .then(results => {
  3242. const endResults = {};
  3243. for (let info of results) {
  3244. let id = info.battleData.typeId;
  3245. endResults[id] = {
  3246. progress: info.progress,
  3247. result: info.result,
  3248. }
  3249. }
  3250. titanArenaEndRaid(endResults);
  3251. });
  3252. }
  3253.  
  3254. function calcBattleResult(battleData) {
  3255. return new Promise(function (resolve, reject) {
  3256. BattleCalc(battleData, "get_titanClanPvp", resolve);
  3257. });
  3258. }
  3259.  
  3260. /** Отправка результатов рейда */
  3261. function titanArenaEndRaid(results) {
  3262. titanArenaEndRaidCall = {
  3263. calls: [{
  3264. name: "titanArenaEndRaid",
  3265. args: {
  3266. results
  3267. },
  3268. ident: "body"
  3269. }]
  3270. }
  3271. send(JSON.stringify(titanArenaEndRaidCall), checkRaidResults);
  3272. }
  3273.  
  3274. function checkRaidResults(data) {
  3275. results = data.results[0].result.response.results;
  3276. isSucsesRaid = true;
  3277. for (let i in results) {
  3278. isSucsesRaid &&= (results[i].attackScore >= 250);
  3279. }
  3280.  
  3281. if (isSucsesRaid) {
  3282. titanArenaCompleteTier();
  3283. } else {
  3284. titanArenaGetStatus();
  3285. }
  3286. }
  3287.  
  3288. function titanArenaFarmDailyReward() {
  3289. titanArenaFarmDailyRewardCall = {
  3290. calls: [{
  3291. name: "titanArenaFarmDailyReward",
  3292. args: {},
  3293. ident: "body"
  3294. }]
  3295. }
  3296. send(JSON.stringify(titanArenaFarmDailyRewardCall), () => {console.log('Done farm daily reward')});
  3297. }
  3298.  
  3299. function endTitanArena(reason, info) {
  3300. if (!['Peace_time', 'disabled'].includes(reason)) {
  3301. titanArenaFarmDailyReward();
  3302. }
  3303. console.log(reason, info);
  3304. setProgress('Турнир Стихий выполнен!', true);
  3305. resolve();
  3306. }
  3307. }
  3308. let hideTimeoutProgress = 0;
  3309. /** Скрыть прогресс */
  3310. function hideProgress(timeout) {
  3311. timeout = timeout || 0;
  3312. clearTimeout(hideTimeoutProgress);
  3313. hideTimeoutProgress = setTimeout(function () {
  3314. scriptMenu.setStatus('');
  3315. }, timeout);
  3316. }
  3317. /** Отображение прогресса */
  3318. function setProgress(text, hide, onclick) {
  3319. scriptMenu.setStatus(text, onclick);
  3320. hide = hide || false;
  3321. if (hide) {
  3322. hideProgress(3000);
  3323. }
  3324. }
  3325. function hackGame() {
  3326. selfGame = null;
  3327. bindId = 1e9;
  3328. /** Список соответствия используемых классов их названиям */
  3329. ObjectsList = [
  3330. {name:"BattlePresets", prop:"game.battle.controller.thread.BattlePresets"},
  3331. {name:"DataStorage", prop:"game.data.storage.DataStorage"},
  3332. {name:"BattleConfigStorage", prop:"game.data.storage.battle.BattleConfigStorage"},
  3333. {name:"BattleInstantPlay", prop:"game.battle.controller.instant.BattleInstantPlay"},
  3334. {name:"MultiBattleResult", prop:"game.battle.controller.MultiBattleResult"},
  3335.  
  3336. {name:"PlayerMissionData", prop:"game.model.user.mission.PlayerMissionData"},
  3337. {name:"PlayerMissionBattle", prop:"game.model.user.mission.PlayerMissionBattle"},
  3338. {name:"GameModel", prop:"game.model.GameModel"},
  3339. {name:"CommandManager", prop:"game.command.CommandManager"},
  3340. {name:"MissionCommandList", prop:"game.command.rpc.mission.MissionCommandList"},
  3341. {name:"RPCCommandBase", prop:"game.command.rpc.RPCCommandBase"},
  3342. {name:"PlayerTowerData", prop:"game.model.user.tower.PlayerTowerData"},
  3343. {name:"TowerCommandList", prop:"game.command.tower.TowerCommandList"},
  3344. {name:"PlayerHeroTeamResolver", prop:"game.model.user.hero.PlayerHeroTeamResolver"},
  3345. {name:"BattlePausePopup", prop:"game.view.popup.battle.BattlePausePopup"},
  3346. {name:"BattlePopup", prop:"game.view.popup.battle.BattlePopup"},
  3347. {name:"DisplayObjectContainer", prop:"starling.display.DisplayObjectContainer"},
  3348. {name:"GuiClipContainer", prop:"engine.core.clipgui.GuiClipContainer"},
  3349. {name:"BattlePausePopupClip", prop:"game.view.popup.battle.BattlePausePopupClip"},
  3350. {name:"ClipLabel", prop:"game.view.gui.components.ClipLabel"},
  3351. {name:"Translate", prop:"com.progrestar.common.lang.Translate"},
  3352. {name:"ClipButtonLabeledCentered", prop:"game.view.gui.components.ClipButtonLabeledCentered"},
  3353. {name:"BattlePausePopupMediator", prop:"game.mediator.gui.popup.battle.BattlePausePopupMediator"},
  3354. {name:"SettingToggleButton", prop:"game.view.popup.settings.SettingToggleButton"},
  3355. {name:"PlayerDungeonData", prop:"game.mechanics.dungeon.model.PlayerDungeonData"},
  3356. {name:"NextDayUpdatedManager", prop:"game.model.user.NextDayUpdatedManager"},
  3357. {name:"BattleController", prop:"game.battle.controller.BattleController"},
  3358. {name:"BattleSettingsModel", prop:"game.battle.controller.BattleSettingsModel"},
  3359. {name:"BooleanProperty", prop:"engine.core.utils.property.BooleanProperty"},
  3360. {name:"RuleStorage", prop:"game.data.storage.rule.RuleStorage"},
  3361. {name:"BattleConfig", prop:"battle.BattleConfig"},
  3362. {name:"SpecialShopModel", prop:"game.model.user.shop.SpecialShopModel"},
  3363. {name:"BattleGuiMediator", prop:"game.battle.gui.BattleGuiMediator"},
  3364. {name:"BooleanPropertyWriteable", prop:"engine.core.utils.property.BooleanPropertyWriteable"},
  3365. ];
  3366. /** Содержит классы игры необходимые для написания и подмены методов игры */
  3367. Game = {
  3368. /** Функция 'e' */
  3369. bindFunc: function (a, b) {
  3370. if (null == b)
  3371. return null;
  3372. null == b.__id__ && (b.__id__ = bindId++);
  3373. var c;
  3374. null == a.hx__closures__ ? a.hx__closures__ = {} :
  3375. c = a.hx__closures__[b.__id__];
  3376. null == c && (c = b.bind(a), a.hx__closures__[b.__id__] = c);
  3377. return c
  3378. },
  3379. };
  3380. /** Подключается к объектам игры через событие создания объекта */
  3381. function connectGame() {
  3382. for (let obj of ObjectsList) {
  3383. /**
  3384. * https: //stackoverflow.com/questions/42611719/how-to-intercept-and-modify-a-specific-property-for-any-object
  3385. */
  3386. Object.defineProperty(Object.prototype, obj.prop, {
  3387. set: function (value) {
  3388. if (!selfGame) {
  3389. selfGame = this;
  3390. }
  3391. if (!Game[obj.name]) {
  3392. Game[obj.name] = value;
  3393. }
  3394. // console.log('set ' + obj.prop, this, value);
  3395. this[obj.prop + '_'] = value;
  3396. },
  3397. get: function () {
  3398. // console.log('get ' + obj.prop, this);
  3399. return this[obj.prop + '_'];
  3400. }
  3401. });
  3402. }
  3403. }
  3404. /**
  3405. * Game.BattlePresets
  3406. * @param {bool} a isReplay
  3407. * @param {bool} b autoToggleable
  3408. * @param {bool} c auto On Start
  3409. * @param {object} d config
  3410. * @param {bool} f showBothTeams
  3411. */
  3412. /**
  3413. * Возвращает в функцию callback результаты боя
  3414. * @param {*} battleData данные боя
  3415. * @param {*} battleConfig тип конфигурации боя варианты:
  3416. * "get_invasion", "get_titanPvpManual", "get_titanPvp",
  3417. * "get_titanClanPvp","get_clanPvp","get_titan","get_boss",
  3418. * "get_tower","get_pve","get_pvpManual","get_pvp","get_core"
  3419. * Можно уточнить в классе game.assets.storage.BattleAssetStorage функция xYc
  3420. * @param {*} callback функция в которую вернуться результаты боя
  3421. */
  3422. this.BattleCalc = function (battleData, battleConfig, callback) {
  3423. // battleConfig = battleConfig || getBattleType(battleData.type)
  3424. if (!Game.BattlePresets) throw Error('Use connectGame');
  3425. battlePresets = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getF(Game.BattleConfigStorage, battleConfig)](), !1);
  3426. battleInstantPlay = new Game.BattleInstantPlay(battleData, battlePresets);
  3427. battleInstantPlay[getProtoFn(Game.BattleInstantPlay, 8)].add((battleInstant) => {
  3428. battleResult = battleInstant[getF(Game.BattleInstantPlay, 'get_result')]();
  3429. battleData = battleInstant[getF(Game.BattleInstantPlay, 'get_rawBattleInfo')]();
  3430. callback({
  3431. battleData,
  3432. progress: battleResult[getF(Game.MultiBattleResult, 'get_progress')](),
  3433. result: battleResult[getF(Game.MultiBattleResult, 'get_result')]()
  3434. })
  3435. });
  3436. battleInstantPlay.start();
  3437. }
  3438.  
  3439. /**
  3440. * Возвращает из класса функцию с указанным именем
  3441. * @param {Object} classF класс
  3442. * @param {String} nameF имя функции
  3443. * @param {String} pos порядок имени и псевдонима
  3444. * @returns
  3445. */
  3446. function getF(classF, nameF, pos) {
  3447. pos = pos || false;
  3448. let prop = Object.entries(classF.prototype.__properties__)
  3449. if (!pos) {
  3450. return prop.filter((e) => e[1] == nameF).pop()[0];
  3451. } else {
  3452. return prop.filter((e) => e[0] == nameF).pop()[1];
  3453. }
  3454. }
  3455.  
  3456. /**
  3457. * Возвращает из класса функцию с указанным именем
  3458. * @param {Object} classF класс
  3459. * @param {String} nameF имя функции
  3460. * @returns
  3461. */
  3462. function getFnP(classF, nameF) {
  3463. let prop = Object.entries(classF.__properties__)
  3464. return prop.filter((e) => e[1] == nameF).pop()[0];
  3465. }
  3466.  
  3467. /**
  3468. * Возвращает имя функции с указаным порядковым номером из класса
  3469. * @param {Object} classF класс
  3470. * @param {Number} nF порядковый номер функции
  3471. * @returns
  3472. */
  3473. function getFn(classF, nF) {
  3474. // let prop = Object.getOwnPropertyNames(classF);
  3475. let prop = Object.keys(classF);
  3476. // let nan = Object.keys(classF).indexOf(prop[nF]);
  3477. // if (nan != nF) {
  3478. // console.log(nan, prop[nF], nF);
  3479. // }
  3480. return prop[nF];
  3481. }
  3482.  
  3483. /**
  3484. * Возвращает имя функции с указаным порядковым номером из прототипа класса
  3485. * @param {Object} classF класс
  3486. * @param {Number} nF порядковый номер функции
  3487. * @returns
  3488. */
  3489. function getProtoFn(classF, nF) {
  3490. // let prop = Object.getOwnPropertyNames(classF.prototype);
  3491. let prop = Object.keys(classF.prototype);
  3492. // let nan = Object.keys(classF.prototype).indexOf(prop[nF]);
  3493. // if (nan != nF) {
  3494. // console.log(nan, prop[nF], nF);
  3495. // }
  3496. return prop[nF];
  3497. }
  3498. /** Описание подменяемых функций */
  3499. replaceFunction = {
  3500. company: function() {
  3501. let PMD_12 = getProtoFn(Game.PlayerMissionData, 12);
  3502. let oldSkipMisson = Game.PlayerMissionData.prototype[PMD_12];
  3503. Game.PlayerMissionData.prototype[PMD_12] = function (a, b, c) {
  3504. if (isChecked('passBattle')) {
  3505. this[getProtoFn(Game.PlayerMissionData, 9)] = new Game.PlayerMissionBattle(a, b, c);
  3506.  
  3507. var a = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage, 17)](), !1);
  3508. a = new Game.BattleInstantPlay(c, a);
  3509. a[getProtoFn(Game.BattleInstantPlay, 8)].add(Game.bindFunc(this, this.P$h));
  3510. a.start()
  3511. } else {
  3512. oldSkipMisson.call(this, a, b, c);
  3513. }
  3514. }
  3515.  
  3516. Game.PlayerMissionData.prototype.P$h = function (a) {
  3517. let GM_2 = getFn(Game.GameModel, 2);
  3518. let GM_P2 = getProtoFn(Game.GameModel, 2);
  3519. let CM_20 = getProtoFn(Game.CommandManager, 20);
  3520. let MCL_2 = getProtoFn(Game.MissionCommandList, 2);
  3521. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  3522. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  3523. let PMD_32 = getProtoFn(Game.PlayerMissionData, 32);
  3524. Game.GameModel[GM_2]()[GM_P2][CM_20][MCL_2](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PMD_32]))
  3525. }
  3526. },
  3527. tower: function() {
  3528. let PTD_67 = getProtoFn(Game.PlayerTowerData, 67);
  3529. let oldSkipTower = Game.PlayerTowerData.prototype[PTD_67];
  3530. Game.PlayerTowerData.prototype[PTD_67] = function (a) {
  3531. if (isChecked('passBattle')) {
  3532. var p = new Game.BattlePresets(!1, !1, !0, Game.DataStorage[getFn(Game.DataStorage, 22)][getProtoFn(Game.BattleConfigStorage,17)](), !1);
  3533. a = new Game.BattleInstantPlay(a, p);
  3534. a[getProtoFn(Game.BattleInstantPlay,8)].add(Game.bindFunc(this, this.P$h));
  3535. a.start()
  3536. } else {
  3537. oldSkipTower.call(this, a);;
  3538. }
  3539. }
  3540.  
  3541. Game.PlayerTowerData.prototype.P$h = function (a) {
  3542. let GM_2 = getFn(Game.GameModel, 2);
  3543. let GM_P2 = getProtoFn(Game.GameModel, 2);
  3544. let CM_29 = getProtoFn(Game.CommandManager, 29);
  3545. let TCL_5 = getProtoFn(Game.TowerCommandList, 5);
  3546. let MBR_15 = getProtoFn(Game.MultiBattleResult, 15);
  3547. let RPCCB_15 = getProtoFn(Game.RPCCommandBase, 15);
  3548. let PTD_78 = getProtoFn(Game.PlayerTowerData, 78);
  3549. Game.GameModel[GM_2]()[GM_P2][CM_29][TCL_5](a[MBR_15]())[RPCCB_15](Game.bindFunc(this, this[PTD_78]))
  3550. }
  3551. },
  3552. // skipSelectHero: function() {
  3553. // if (!HOST) throw Error('Use connectGame');
  3554. // Game.PlayerHeroTeamResolver.prototype[getProtoFn(Game.PlayerHeroTeamResolver, 3)] = () => false;
  3555. // },
  3556. passBattle: function() {
  3557. let BPP_4 = getProtoFn(Game.BattlePausePopup, 4);
  3558. let oldPassBattle = Game.BattlePausePopup.prototype[BPP_4];
  3559. Game.BattlePausePopup.prototype[BPP_4] = function (a) {
  3560. if (isChecked('passBattle')) {
  3561. Game.BattlePopup.prototype[getProtoFn(Game.BattlePausePopup, 4)].call(this, a);
  3562. this[getProtoFn(Game.BattlePausePopup, 3)]();
  3563. this[getProtoFn(Game.DisplayObjectContainer, 3)](this.clip[getProtoFn(Game.GuiClipContainer, 2)]());
  3564. this.clip[getProtoFn(Game.BattlePausePopupClip, 1)][getProtoFn(Game.ClipLabel, 9)](Game.Translate.translate("UI_POPUP_BATTLE_PAUSE"));
  3565.  
  3566. 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 */
  3567. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 2)](
  3568. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 12)](),
  3569. this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 11)]() ?
  3570. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) :
  3571. (q = this[getProtoFn(Game.BattlePausePopup, 1)], Game.bindFunc(q, q[getProtoFn(Game.BattlePausePopupMediator, 16)])) /** 15 > 16 */
  3572. );
  3573.  
  3574. this.clip[getProtoFn(Game.BattlePausePopupClip, 5)][getProtoFn(Game.ClipButtonLabeledCentered, 0)][getProtoFn(Game.ClipLabel, 23)]();
  3575. this.clip[getProtoFn(Game.BattlePausePopupClip, 3)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 8)]());
  3576. this.clip[getProtoFn(Game.BattlePausePopupClip, 4)][getProtoFn(Game.SettingToggleButton, 3)](this[getProtoFn(Game.BattlePausePopup, 1)][getProtoFn(Game.BattlePausePopupMediator, 9)]());
  3577. } else {
  3578. oldPassBattle.call(this, a);
  3579. }
  3580. }
  3581.  
  3582. let retreatButtonLabel = getF(Game.BattlePausePopupMediator, "get_retreatButtonLabel");
  3583. let oldFunc = Game.BattlePausePopupMediator.prototype[retreatButtonLabel];
  3584. Game.BattlePausePopupMediator.prototype[retreatButtonLabel] = function () {
  3585. if (isChecked('passBattle')) {
  3586. return 'ПРОПУСК';
  3587. } else {
  3588. return oldFunc.call(this);
  3589. }
  3590. }
  3591. },
  3592. endlessCards: function() {
  3593. let PDD_15 = getProtoFn(Game.PlayerDungeonData, 15);
  3594. let oldEndlessCards = Game.PlayerDungeonData.prototype[PDD_15];
  3595. Game.PlayerDungeonData.prototype[PDD_15] = function () {
  3596. if (isChecked('endlessCards')) {
  3597. return true;
  3598. } else {
  3599. return oldEndlessCards.call(this);
  3600. }
  3601. }
  3602. },
  3603. speedBattle: function () {
  3604. const get_timeScale = getF(Game.BattleController, "get_timeScale");
  3605. const oldSpeedBattle = Game.BattleController.prototype[get_timeScale];
  3606. Game.BattleController.prototype[get_timeScale] = function () {
  3607. const speedBattle = Number.parseFloat(getInput('speedBattle'));
  3608. if (speedBattle) {
  3609. const BC_11 = getProtoFn(Game.BattleController, 11);
  3610. const BSM_11 = getProtoFn(Game.BattleSettingsModel, 11);
  3611. const BP_get_value = getF(Game.BooleanProperty, "get_value");
  3612. if (this[BC_11][BSM_11][BP_get_value]()) {
  3613. return 0;
  3614. }
  3615. const BSM_2 = getProtoFn(Game.BattleSettingsModel, 2);
  3616. const BC_44 = getProtoFn(Game.BattleController, 44);
  3617. const BSM_1 = getProtoFn(Game.BattleSettingsModel, 1);
  3618. const BC_13 = getProtoFn(Game.BattleController, 13);
  3619. const BC_3 = getFn(Game.BattleController, 3);
  3620. if (this[BC_11][BSM_2][BP_get_value]()) {
  3621. var a = speedBattle * this[BC_44]();
  3622. } else {
  3623. a = this[BC_11][BSM_1][BP_get_value]();
  3624. //const multiple = a == 1 ? speedBattle : this[BC_13][a];
  3625. a = this[BC_13][a] * Game.BattleController[BC_3][BP_get_value]() * this[BC_44]();
  3626. }
  3627. const BSM_22 = getProtoFn(Game.BattleSettingsModel, 22);
  3628. a > this[BC_11][BSM_22][BP_get_value]() && (a = this[BC_11][BSM_22][BP_get_value]());
  3629. const DS_21 = getFn(Game.DataStorage, 21);
  3630. const get_battleSpeedMultiplier = getF(Game.RuleStorage, "get_battleSpeedMultiplier", true);
  3631. // const RS_167 = getProtoFn(Game.RuleStorage, 167); // get_battleSpeedMultiplier
  3632. var b = Game.DataStorage[DS_21][get_battleSpeedMultiplier]();
  3633. const R_1 = getFn(selfGame.Reflect, 1);
  3634. const BC_1 = getFn(Game.BattleController, 1);
  3635. const get_config = getF(Game.BattlePresets, "get_config");
  3636. // const BC_0 = getProtoFn(Game.BattleConfig, 0); // .ident
  3637. 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"));
  3638. return a
  3639. } else {
  3640. return oldSpeedBattle.call(this);
  3641. }
  3642. }
  3643. },
  3644. /** Удаление торговца редкими товарами */
  3645. removeWelcomeShop: function () {
  3646. let SSM_3 = getProtoFn(Game.SpecialShopModel, 3);
  3647. const oldWelcomeShop = Game.SpecialShopModel.prototype[SSM_3];
  3648. Game.SpecialShopModel.prototype[SSM_3] = function () {
  3649. if (isChecked('noOfferDonat')) {
  3650. return null;
  3651. } else {
  3652. return oldWelcomeShop.call(this);
  3653. }
  3654. }
  3655. },
  3656. /** Кнопка ускорения без Покровительства Валькирий */
  3657. battleFastKey: function () {
  3658. const BGM_37 = getProtoFn(Game.BattleGuiMediator, 37);
  3659. const oldBattleFastKey = Game.BattleGuiMediator.prototype[BGM_37];
  3660. Game.BattleGuiMediator.prototype[BGM_37] = function () {
  3661. if (true) {
  3662. const BGM_8 = getProtoFn(Game.BattleGuiMediator, 8);
  3663. const BGM_9 = getProtoFn(Game.BattleGuiMediator, 9);
  3664. const BPW_0 = getProtoFn(Game.BooleanPropertyWriteable, 0);
  3665. this[BGM_8][BPW_0](true);
  3666. this[BGM_9][BPW_0](true);
  3667. } else {
  3668. return oldBattleFastKey.call(this);
  3669. }
  3670. }
  3671. }
  3672. }
  3673. /** Запускает замену записанных функций */
  3674. this.activateHacks = function () {
  3675. if (!selfGame) throw Error('Use connectGame');
  3676. for (let func in replaceFunction) {
  3677. replaceFunction[func]();
  3678. }
  3679. }
  3680. /** Возвращает объект игры */
  3681. this.getSelfGame = function () {
  3682. return selfGame;
  3683. }
  3684. /** Обновляет данные игры */
  3685. this.refreshGame = function () {
  3686. (new Game.NextDayUpdatedManager)[getProtoFn(Game.NextDayUpdatedManager, 5)]();
  3687. }
  3688.  
  3689. /**
  3690. * Сменить экран игры на windowName
  3691. * Возможные варианты:
  3692. * 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
  3693. */
  3694. this.goNavigtor = function (windowName) {
  3695. let mechanicStorage = selfGame["game.data.storage.mechanic.MechanicStorage"];
  3696. let window = mechanicStorage[windowName];
  3697. let event = selfGame["game.mediator.gui.popup.PopupStashEventParams"]('');
  3698. let Game = selfGame['Game'];
  3699. let navigator = getF(Game, "get_navigator")
  3700. let navigate = getProtoFn(selfGame["game.screen.navigator.GameNavigator"], 15)
  3701. let instance = getFnP(Game, 'get_instance');
  3702. Game[instance]()[navigator]()[navigate](window, event);
  3703. }
  3704. /** Переместиться в святилище cheats.goSanctuary() */
  3705. this.goSanctuary = () => {
  3706. this.goNavigtor("SANCTUARY");
  3707. }
  3708. /** Перейти к Войне Гильдий */
  3709. this.goClanWar = function() {
  3710. let instance = getFnP(selfGame["game.model.GameModel"], 'get_instance')
  3711. let player = selfGame["game.model.GameModel"][instance]().A;
  3712. let clanWarSelect = selfGame["game.mechanics.cross_clan_war.popup.selectMode.CrossClanWarSelectModeMediator"];
  3713. new clanWarSelect(player).open();
  3714. }
  3715.  
  3716. connectGame();
  3717. }
  3718. /** Автосбор подарков */
  3719. function getAutoGifts() {
  3720. let valName = 'giftSendIds_' + userInfo.id;
  3721.  
  3722. if (!localStorage['clearGift' + userInfo.id]) {
  3723. localStorage[valName] = '';
  3724. localStorage['clearGift' + userInfo.id] = '+';
  3725. }
  3726.  
  3727. if (!localStorage[valName]) {
  3728. localStorage[valName] = '';
  3729. }
  3730.  
  3731. /** Отправка запроса для получения кодов подарков */
  3732. fetch('https://zingery.ru/heroes/getGifts.php', {
  3733. method: 'POST',
  3734. body: JSON.stringify({scriptInfo, userInfo})
  3735. }).then(
  3736. response => response.json()
  3737. ).then(
  3738. data => {
  3739. let freebieCheckCalls = {
  3740. calls: []
  3741. }
  3742. data.forEach((giftId, n) => {
  3743. if (localStorage[valName].includes(giftId)) return;
  3744. //localStorage[valName] += ';' + giftId;
  3745. freebieCheckCalls.calls.push({
  3746. name: "freebieCheck",
  3747. args: {
  3748. giftId
  3749. },
  3750. ident: giftId
  3751. });
  3752. });
  3753.  
  3754. if (!freebieCheckCalls.calls.length) {
  3755. return;
  3756. }
  3757.  
  3758. send(JSON.stringify(freebieCheckCalls), e => {
  3759. let countGetGifts = 0;
  3760. const gifts = [];
  3761. for (check of e.results) {
  3762. gifts.push(check.ident);
  3763. if (check.result.response != null) {
  3764. countGetGifts++;
  3765. }
  3766. }
  3767. const saveGifts = localStorage[valName].split(';');
  3768. localStorage[valName] = [...saveGifts, ...gifts].slice(-50).join(';');
  3769. setProgress('Подарки: ' + countGetGifts, true);
  3770. console.log('Подарки: ' + countGetGifts);
  3771. });
  3772. }
  3773. )
  3774. }
  3775. /** Набить килов в горниле душк */
  3776. async function bossRatingEvent() {
  3777. const topGet = await Send(JSON.stringify({ calls: [{ name: "topGet", args: { type: "bossRatingTop", extraId: 0 }, ident: "body" }] }));
  3778. if (!topGet) {
  3779. setProgress('Эвент завершен', true);
  3780. return;
  3781. }
  3782. const replayId = topGet.results[0].result.response[0].userData.replayId;
  3783. const result = await Send(JSON.stringify({
  3784. calls: [
  3785. { name: "battleGetReplay", args: { id: replayId }, ident: "battleGetReplay" },
  3786. { name: "heroGetAll", args: {}, ident: "heroGetAll" },
  3787. { name: "pet_getAll", args: {}, ident: "pet_getAll" },
  3788. { name: "offerGetAll", args: {}, ident: "offerGetAll" }
  3789. ]
  3790. }));
  3791. const bossEventInfo = result.results[3].result.response.find(e => e.offerType == "bossEvent");
  3792. if (!bossEventInfo) {
  3793. setProgress('Эвент завершен', true);
  3794. return;
  3795. }
  3796. const usedHeroes = bossEventInfo.progress.usedHeroes;
  3797. const party = Object.values(result.results[0].result.response.replay.attackers);
  3798. const availableHeroes = Object.values(result.results[1].result.response).map(e => e.id);
  3799. const availablePets = Object.values(result.results[2].result.response).map(e => e.id);
  3800. const calls = [];
  3801. /** Первая пачка */
  3802. const args = {
  3803. heroes: [],
  3804. favor: {}
  3805. }
  3806. for (let hero of party) {
  3807. if (hero.id >= 6000 && availablePets.includes(hero.id)) {
  3808. args.pet = hero.id;
  3809. continue;
  3810. }
  3811. if (!availableHeroes.includes(hero.id) || usedHeroes.includes(hero.id)) {
  3812. continue;
  3813. }
  3814. args.heroes.push(hero.id);
  3815. if (hero.favorPetId) {
  3816. args.favor[hero.id] = hero.favorPetId;
  3817. }
  3818. }
  3819. if (args.heroes.length) {
  3820. calls.push({
  3821. name: "bossRatingEvent_startBattle",
  3822. args,
  3823. ident: "body_0"
  3824. });
  3825. }
  3826. /** Другие пачки */
  3827. let heroes = [];
  3828. let count = 1;
  3829. while (heroId = availableHeroes.pop()) {
  3830. if (args.heroes.includes(heroId) || usedHeroes.includes(heroId)) {
  3831. continue;
  3832. }
  3833. heroes.push(heroId);
  3834. if (heroes.length == 5) {
  3835. calls.push({
  3836. name: "bossRatingEvent_startBattle",
  3837. args: {
  3838. heroes: [...heroes],
  3839. pet: availablePets[Math.floor(Math.random() * availablePets.length)]
  3840. },
  3841. ident: "body_" + count
  3842. });
  3843. heroes = [];
  3844. count++;
  3845. }
  3846. }
  3847.  
  3848. if (!calls.length) {
  3849. setProgress('Нет героев', true);
  3850. return;
  3851. }
  3852.  
  3853. const resultBattles = await Send(JSON.stringify({ calls }));
  3854. console.log(resultBattles);
  3855. rewardBossRatingEvent();
  3856. }
  3857. /** Сбор награды из Горнила Душ */
  3858. function rewardBossRatingEvent() {
  3859. let rewardBossRatingCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  3860. send(rewardBossRatingCall, function (data) {
  3861. let bossEventInfo = data.results[0].result.response.find(e => e.offerType == "bossEvent");
  3862. if (!bossEventInfo) {
  3863. setProgress('Эвент завершен', true);
  3864. return;
  3865. }
  3866.  
  3867. let farmedChests = bossEventInfo.progress.farmedChests;
  3868. let score = bossEventInfo.progress.score;
  3869. setProgress('Количество урона: ' + score);
  3870. let revard = bossEventInfo.reward;
  3871.  
  3872. let getRewardCall = {
  3873. calls: []
  3874. }
  3875.  
  3876. let count = 0;
  3877. for (let i = 1; i < 10; i++) {
  3878. if (farmedChests.includes(i)) {
  3879. continue;
  3880. }
  3881. if (score < revard[i].score) {
  3882. break;
  3883. }
  3884. getRewardCall.calls.push({
  3885. name: "bossRatingEvent_getReward",
  3886. args: {
  3887. rewardId: i
  3888. },
  3889. ident: "body_" + i
  3890. });
  3891. count++;
  3892. }
  3893. if (!count) {
  3894. setProgress('Нечего собирать', true);
  3895. return;
  3896. }
  3897.  
  3898. send(JSON.stringify(getRewardCall), e => {
  3899. console.log(e);
  3900. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  3901. });
  3902. });
  3903. }
  3904. /** Собрать пасхалки и награды событий */
  3905. function offerFarmAllReward() {
  3906. const offerGetAllCall = '{"calls":[{"name":"offerGetAll","args":{},"ident":"offerGetAll"}]}';
  3907. return Send(offerGetAllCall).then((data) => {
  3908. const offerGetAll = data.results[0].result.response.filter(e => e.type == "reward" && !e?.freeRewardObtained && e.reward);
  3909. if (!offerGetAll.length) {
  3910. setProgress('Нечего собирать', true);
  3911. return;
  3912. }
  3913.  
  3914. const calls = [];
  3915. for (let reward of offerGetAll) {
  3916. calls.push({
  3917. name: "offerFarmReward",
  3918. args: {
  3919. offerId: reward.id
  3920. },
  3921. ident: "offerFarmReward_" + reward.id
  3922. });
  3923. }
  3924.  
  3925. return Send(JSON.stringify({ calls })).then(e => {
  3926. console.log(e);
  3927. setProgress('Собрано ' + e?.results?.length + ' наград', true);
  3928. });
  3929. });
  3930. }
  3931. /** Собрать запределье */
  3932. function getOutland() {
  3933. return new Promise(function (resolve, reject) {
  3934. send('{"calls":[{"name":"bossGetAll","args":{},"ident":"bossGetAll"}]}', e => {
  3935. let bosses = e.results[0].result.response;
  3936.  
  3937. let bossRaidOpenChestCall = {
  3938. calls: []
  3939. };
  3940.  
  3941. for (let boss of bosses) {
  3942. if (boss.mayRaid) {
  3943. bossRaidOpenChestCall.calls.push({
  3944. name: "bossRaid",
  3945. args: {
  3946. bossId: boss.id
  3947. },
  3948. ident: "bossRaid_" + boss.id
  3949. });
  3950. bossRaidOpenChestCall.calls.push({
  3951. name: "bossOpenChest",
  3952. args: {
  3953. bossId: boss.id,
  3954. amount: 1,
  3955. starmoney: 0
  3956. },
  3957. ident: "bossOpenChest_" + boss.id
  3958. });
  3959. } else if (boss.chestId == 1) {
  3960. bossRaidOpenChestCall.calls.push({
  3961. name: "bossOpenChest",
  3962. args: {
  3963. bossId: boss.id,
  3964. amount: 1,
  3965. starmoney: 0
  3966. },
  3967. ident: "bossOpenChest_" + boss.id
  3968. });
  3969. }
  3970. }
  3971.  
  3972. if (!bossRaidOpenChestCall.calls.length) {
  3973. setProgress('Запределье уже было собрано', true);
  3974. resolve();
  3975. return;
  3976. }
  3977.  
  3978. send(JSON.stringify(bossRaidOpenChestCall), e => {
  3979. setProgress('Запределье собрано', true);
  3980. resolve();
  3981. });
  3982. });
  3983. });
  3984. }
  3985. /** Собрать все награды */
  3986. function questAllFarm() {
  3987. return new Promise(function (resolve, reject) {
  3988. let questGetAllCall = {
  3989. calls: [{
  3990. name: "questGetAll",
  3991. args: {},
  3992. ident: "body"
  3993. }]
  3994. }
  3995. send(JSON.stringify(questGetAllCall), function (data) {
  3996. let questGetAll = data.results[0].result.response;
  3997. const questAllFarmCall = {
  3998. calls: []
  3999. }
  4000. let number = 0;
  4001. for (let quest of questGetAll) {
  4002. if (quest.id < 1e6 && quest.state == 2) {
  4003. questAllFarmCall.calls.push({
  4004. name: "questFarm",
  4005. args: {
  4006. questId: quest.id
  4007. },
  4008. ident: `group_${number}_body`
  4009. });
  4010. number++;
  4011. }
  4012. }
  4013.  
  4014. if (!questAllFarmCall.calls.length) {
  4015. setProgress('Собрано наград: ' + number, true);
  4016. resolve();
  4017. return;
  4018. }
  4019.  
  4020. send(JSON.stringify(questAllFarmCall), function (res) {
  4021. console.log(res);
  4022. setProgress('Собрано наград: ' + number, true);
  4023. resolve();
  4024. });
  4025. });
  4026. })
  4027. }
  4028.  
  4029. /**
  4030. * Атака прислужников Асгарда
  4031. * @returns
  4032. */
  4033. function testRaidNodes() {
  4034. return new Promise((resolve, reject) => {
  4035. const tower = new executeRaidNodes(resolve, reject);
  4036. tower.start();
  4037. });
  4038. }
  4039.  
  4040. /** Атака прислужников Асгарда */
  4041. function executeRaidNodes(resolve, reject) {
  4042. let raidData = {
  4043. teams: [],
  4044. favor: {},
  4045. nodes: [],
  4046. attempts: 0,
  4047. countExecuteBattles: 0,
  4048. cancelBattle: 0,
  4049. }
  4050.  
  4051. callsExecuteRaidNodes = {
  4052. calls: [{
  4053. name: "clanRaid_getInfo",
  4054. args: {},
  4055. ident: "clanRaid_getInfo"
  4056. }, {
  4057. name: "teamGetAll",
  4058. args: {},
  4059. ident: "teamGetAll"
  4060. }, {
  4061. name: "teamGetFavor",
  4062. args: {},
  4063. ident: "teamGetFavor"
  4064. }]
  4065. }
  4066.  
  4067. this.start = function () {
  4068. send(JSON.stringify(callsExecuteRaidNodes), startRaidNodes);
  4069. }
  4070.  
  4071. function startRaidNodes(data) {
  4072. res = data.results;
  4073. clanRaidInfo = res[0].result.response;
  4074. teamGetAll = res[1].result.response;
  4075. teamGetFavor = res[2].result.response;
  4076.  
  4077. let index = 0;
  4078. for (let team of teamGetAll.clanRaid_nodes) {
  4079. raidData.teams.push({
  4080. data: {},
  4081. heroes: team.filter(id => id < 6000),
  4082. pet: team.filter(id => id >= 6000).pop(),
  4083. battleIndex: index++
  4084. });
  4085. }
  4086. raidData.favor = teamGetFavor.clanRaid_nodes;
  4087.  
  4088. raidData.nodes = clanRaidInfo.nodes;
  4089. raidData.attempts = clanRaidInfo.attempts;
  4090. isCancalBattle = false;
  4091.  
  4092. checkNodes();
  4093. }
  4094.  
  4095. function getAttackNode() {
  4096. for (let nodeId in raidData.nodes) {
  4097. let node = raidData.nodes[nodeId];
  4098. let points = 0
  4099. for (team of node.teams) {
  4100. points += team.points;
  4101. }
  4102. let now = Date.now() / 1000;
  4103. if (!points && now > node.timestamps.start && now < node.timestamps.end) {
  4104. let countTeam = node.teams.length;
  4105. delete raidData.nodes[nodeId];
  4106. return {
  4107. nodeId,
  4108. countTeam
  4109. };
  4110. }
  4111. }
  4112. return null;
  4113. }
  4114.  
  4115. function checkNodes() {
  4116. setProgress('Осталось попыток: ' + raidData.attempts);
  4117. let nodeInfo = getAttackNode();
  4118. if (nodeInfo && raidData.attempts) {
  4119. startNodeBattles(nodeInfo);
  4120. return;
  4121. }
  4122.  
  4123. endRaidNodes('EndRaidNodes');
  4124. }
  4125.  
  4126. function startNodeBattles(nodeInfo) {
  4127. let {nodeId, countTeam} = nodeInfo;
  4128. let teams = raidData.teams.slice(0, countTeam);
  4129. let heroes = raidData.teams.map(e => e.heroes).flat();
  4130. let favor = {...raidData.favor};
  4131. for (let heroId in favor) {
  4132. if (!heroes.includes(+heroId)) {
  4133. delete favor[heroId];
  4134. }
  4135. }
  4136.  
  4137. let calls = [{
  4138. name: "clanRaid_startNodeBattles",
  4139. args: {
  4140. nodeId,
  4141. teams,
  4142. favor
  4143. },
  4144. ident: "body"
  4145. }];
  4146.  
  4147. send(JSON.stringify({calls}), resultNodeBattles);
  4148. }
  4149.  
  4150. function resultNodeBattles(e) {
  4151. if (e['error']) {
  4152. endRaidNodes('nodeBattlesError', e['error']);
  4153. return;
  4154. }
  4155.  
  4156. console.log(e);
  4157. let battles = e.results[0].result.response.battles;
  4158. let promises = [];
  4159. let battleIndex = 0;
  4160. for (let battle of battles) {
  4161. battle.battleIndex = battleIndex++;
  4162. promises.push(calcBattleResult(battle));
  4163. }
  4164.  
  4165. Promise.all(promises)
  4166. .then(results => {
  4167. const endResults = {};
  4168. let isAllWin = true;
  4169. for (let r of results) {
  4170. isAllWin &&= r.result.win;
  4171. }
  4172. if (!isAllWin) {
  4173. cancelEndNodeBattle(results[0]);
  4174. return;
  4175. }
  4176. raidData.countExecuteBattles = results.length;
  4177. let timeout = 500;
  4178. for (let r of results) {
  4179. setTimeout(endNodeBattle, timeout, r);
  4180. timeout += 500;
  4181. }
  4182. });
  4183. }
  4184. /** Возвращает промис расчета боя */
  4185. function calcBattleResult(battleData) {
  4186. return new Promise(function (resolve, reject) {
  4187. BattleCalc(battleData, "get_clanPvp", resolve);
  4188. });
  4189. }
  4190. /** Отменяет бой */
  4191. function cancelEndNodeBattle(r) {
  4192. const fixBattle = function (heroes) {
  4193. for (const ids in heroes) {
  4194. hero = heroes[ids];
  4195. hero.energy = random(1, 999);
  4196. if (hero.hp > 0) {
  4197. hero.hp = random(1, hero.hp);
  4198. }
  4199. }
  4200. }
  4201. fixBattle(r.progress[0].attackers.heroes);
  4202. fixBattle(r.progress[0].defenders.heroes);
  4203. endNodeBattle(r);
  4204. }
  4205. /** Завершает бой */
  4206. function endNodeBattle(r) {
  4207. let nodeId = r.battleData.result.nodeId;
  4208. let battleIndex = r.battleData.battleIndex;
  4209. let calls = [{
  4210. name: "clanRaid_endNodeBattle",
  4211. args: {
  4212. nodeId,
  4213. battleIndex,
  4214. result: r.result,
  4215. progress: r.progress
  4216. },
  4217. ident: "body"
  4218. }]
  4219.  
  4220. SendRequest(JSON.stringify({calls}), battleResult);
  4221. }
  4222. /** Обработка результатов боя */
  4223. function battleResult(e) {
  4224. if (e['error']) {
  4225. endRaidNodes('missionEndError', e['error']);
  4226. return;
  4227. }
  4228. r = e.results[0].result.response;
  4229. if (r['error']) {
  4230. if (r.reason == "invalidBattle") {
  4231. raidData.cancelBattle++;
  4232. checkNodes();
  4233. } else {
  4234. endRaidNodes('missionEndError', e['error']);
  4235. }
  4236. return;
  4237. }
  4238.  
  4239. if (!(--raidData.countExecuteBattles)) {
  4240. raidData.attempts--;
  4241. checkNodes();
  4242. }
  4243. }
  4244. /** Завершение задачи */
  4245. function endRaidNodes(reason, info) {
  4246. isCancalBattle = true;
  4247. let textCancel = raidData.cancelBattle ? ' Битв отменено: ' + raidData.cancelBattle : '';
  4248. setProgress('Рейд прислужников завершен!' + textCancel, true);
  4249. console.log(reason, info);
  4250. resolve();
  4251. }
  4252. }
  4253. /**
  4254. * Автоповтор миссии
  4255. * isStopSendMission = false;
  4256. * isSendsMission = true;
  4257. **/
  4258. this.sendsMission = async function (param) {
  4259. if (isStopSendMission) {
  4260. isSendsMission = false;
  4261. console.log('Остановлено');
  4262. setProgress('');
  4263. await popup.confirm('Остановлено<br>Повторений: ' + param.count, [{
  4264. msg: 'Ok',
  4265. result: true
  4266. }, ])
  4267. return;
  4268. }
  4269.  
  4270. let missionStartCall = {
  4271. "calls": [{
  4272. "name": "missionStart",
  4273. "args": lastMissionStart,
  4274. "ident": "body"
  4275. }]
  4276. }
  4277. // Запрос на выполнение мисии
  4278. SendRequest(JSON.stringify(missionStartCall), async e => {
  4279. if (e['error']) {
  4280. isSendsMission = false;
  4281. console.log(e['error']);
  4282. setProgress('');
  4283. let msg = e['error'].name + ' ' + e['error'].description + '<br>Повторений: ' + param.count;
  4284. await popup.confirm(msg, [
  4285. {msg: 'Ok', result: true},
  4286. ])
  4287. return;
  4288. }
  4289. // Расчет данных мисии
  4290. BattleCalc(e.results[0].result.response, 'get_tower', async r => {
  4291.  
  4292. let missionEndCall = {
  4293. "calls": [{
  4294. "name": "missionEnd",
  4295. "args": {
  4296. "id": param.id,
  4297. "result": r.result,
  4298. "progress": r.progress
  4299. },
  4300. "ident": "body"
  4301. }]
  4302. }
  4303. // Запрос на завершение миссии
  4304. SendRequest(JSON.stringify(missionEndCall), async (e) => {
  4305. if (e['error']) {
  4306. isSendsMission = false;
  4307. console.log(e['error']);
  4308. setProgress('');
  4309. let msg = e['error'].name + ' ' + e['error'].description + '<br>Повторений: ' + param.count;
  4310. await popup.confirm(msg, [
  4311. {msg: 'Ok', result: true},
  4312. ])
  4313. return;
  4314. }
  4315. r = e.results[0].result.response;
  4316. if (r['error']) {
  4317. isSendsMission = false;
  4318. console.log(r['error']);
  4319. setProgress('');
  4320. await popup.confirm('Повторений: ' + param.count + ' 3 ' + r['error'], [
  4321. {msg: 'Ok', result: true},
  4322. ])
  4323. return;
  4324. }
  4325.  
  4326. param.count++;
  4327. setProgress('Миссий пройдено: ' + param.count + ' (остановить)', false, () => {
  4328. isStopSendMission = true;
  4329. });
  4330. setTimeout(sendsMission, 1, param);
  4331. });
  4332. })
  4333. });
  4334. }
  4335. /** Рекурсивное открытие матрешек */
  4336. function openRussianDoll(id, count, sum) {
  4337. sum = sum || 0;
  4338. sum += count;
  4339. send('{"calls":[{"name":"consumableUseLootBox","args":{"libId":'+id+',"amount":'+count+'},"ident":"body"}]}', e => {
  4340. setProgress('Открыто ' + count, true);
  4341. let result = e.results[0].result.response;
  4342. let newCount = 0;
  4343. for(let n of result) {
  4344. if (n?.consumable && n.consumable[id]) {
  4345. newCount += n.consumable[id]
  4346. }
  4347. }
  4348. if (newCount) {
  4349. openRussianDoll(id, newCount, sum);
  4350. } else {
  4351. popup.confirm('Всего открыто ' + sum);
  4352. }
  4353. })
  4354. }
  4355.  
  4356. function testBossBattle() {
  4357. return new Promise((resolve, reject) => {
  4358. const bossBattle = new executeBossBattle(resolve, reject);
  4359. bossBattle.start(lastBossBattle, lastBossBattleInfo);
  4360. });
  4361. }
  4362.  
  4363. /** Повтор атаки босса Асгарда */
  4364. function executeBossBattle(resolve, reject) {
  4365. let lastBossBattleArgs = {};
  4366. let reachDamage = 0;
  4367. let countBattle = 0;
  4368. let countMaxBattle = 10;
  4369. let lastDamage = 0;
  4370.  
  4371. this.start = function (battleArg, battleInfo) {
  4372. lastBossBattleArgs = battleArg;
  4373. preCalcBattle(battleInfo);
  4374. }
  4375.  
  4376. function getBattleInfo(battle) {
  4377. return new Promise(function (resolve) {
  4378. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  4379. BattleCalc(battle, getBattleType(battle.type), e => {
  4380. let extra = e.progress[0].defenders.heroes[1].extra;
  4381. resolve(extra.damageTaken + extra.damageTakenNextLevel);
  4382. });
  4383. });
  4384. }
  4385.  
  4386. function preCalcBattle(battle) {
  4387. let actions = [];
  4388. const countTestBattle = getInput('countTestBattle');
  4389. for (let i = 0; i < countTestBattle; i++) {
  4390. actions.push(getBattleInfo(battle, true));
  4391. }
  4392. Promise.all(actions)
  4393. .then(resultPreCalcBattle);
  4394. }
  4395.  
  4396. function fixDamage(damage) {
  4397. for (let i = 1e6; i > 1; i /= 10) {
  4398. if (damage > i) {
  4399. let n = i / 10;
  4400. damage = Math.ceil(damage / n) * n;
  4401. break;
  4402. }
  4403. }
  4404. return damage;
  4405. }
  4406.  
  4407. async function resultPreCalcBattle(damages) {
  4408. let maxDamage = 0;
  4409. let minDamage = 1e10;
  4410. let avgDamage = 0;
  4411. for (let damage of damages) {
  4412. avgDamage += damage
  4413. if (damage > maxDamage) {
  4414. maxDamage = damage;
  4415. }
  4416. if (damage < minDamage) {
  4417. minDamage = damage;
  4418. }
  4419. }
  4420. avgDamage /= damages.length;
  4421. console.log(damages.map(e => e.toLocaleString()).join('\n'), avgDamage, maxDamage);
  4422.  
  4423. reachDamage = fixDamage(avgDamage);
  4424. const result = await popup.confirm(
  4425. `Статистика урона за ${damages.length} боев:` +
  4426. '<br>Минимальный: ' + minDamage.toLocaleString() +
  4427. '<br>Максимальный: ' + maxDamage.toLocaleString() +
  4428. '<br>Средний: ' + avgDamage.toLocaleString()
  4429. /*+ '<br>Поиск урона больше чем ' + reachDamage.toLocaleString()*/
  4430. , [
  4431. {msg: 'Ок', result: 0},
  4432. /* {msg: 'Погнали', isInput: true, default: reachDamage}, */
  4433. ])
  4434. if (result) {
  4435. reachDamage = result;
  4436. isCancalBossBattle = false;
  4437. startBossBattle();
  4438. return;
  4439. }
  4440. endBossBattle('Отмена');
  4441. }
  4442.  
  4443. function startBossBattle() {
  4444. countBattle++;
  4445. countMaxBattle = getInput('countAutoBattle');
  4446. if (countBattle > countMaxBattle) {
  4447. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  4448. endBossBattle('Превышен лимит попыток: ' + countMaxBattle);
  4449. return;
  4450. }
  4451. let calls = [{
  4452. name: "clanRaid_startBossBattle",
  4453. args: lastBossBattleArgs,
  4454. ident: "body"
  4455. }];
  4456. send(JSON.stringify({calls}), calcResultBattle);
  4457. }
  4458.  
  4459. function calcResultBattle(e) {
  4460. BattleCalc(e.results[0].result.response.battle, "get_clanPvp", resultBattle);
  4461. }
  4462.  
  4463. async function resultBattle(e) {
  4464. let extra = e.progress[0].defenders.heroes[1].extra
  4465. resultDamage = extra.damageTaken + extra.damageTakenNextLevel
  4466. console.log(resultDamage);
  4467. scriptMenu.setStatus(countBattle + ') ' + resultDamage.toLocaleString());
  4468. lastDamage = resultDamage;
  4469. if (resultDamage > reachDamage && await popup.confirm(countBattle + ') Урон ' + resultDamage.toLocaleString(), [
  4470. {msg: 'Ок', result: true},
  4471. {msg: 'Не пойдет', result: false},
  4472. ])) {
  4473. endBattle(e, false);
  4474. return;
  4475. }
  4476. cancelEndBattle(e);
  4477. }
  4478.  
  4479. function cancelEndBattle (r) {
  4480. const fixBattle = function (heroes) {
  4481. for (const ids in heroes) {
  4482. hero = heroes[ids];
  4483. hero.energy = random(1, 999);
  4484. if (hero.hp > 0) {
  4485. hero.hp = random(1, hero.hp);
  4486. }
  4487. }
  4488. }
  4489. fixBattle(r.progress[0].attackers.heroes);
  4490. fixBattle(r.progress[0].defenders.heroes);
  4491. endBattle(r, true);
  4492. }
  4493.  
  4494. function endBattle(battleResult, isCancal) {
  4495. let calls = [{
  4496. name: "clanRaid_endBossBattle",
  4497. args: {
  4498. result: battleResult.result,
  4499. progress: battleResult.progress
  4500. },
  4501. ident: "body"
  4502. }];
  4503.  
  4504. send(JSON.stringify({calls}), e => {
  4505. console.log(e);
  4506. if (isCancal) {
  4507. startBossBattle();
  4508. return;
  4509. }
  4510. scriptMenu.setStatus('Босс пробит нанесен урон: ' + lastDamage);
  4511. setTimeout(() => {
  4512. scriptMenu.setStatus('');
  4513. }, 5000);
  4514. endBossBattle('Узпех!');
  4515. });
  4516. }
  4517.  
  4518. /** Завершение задачи */
  4519. function endBossBattle(reason, info) {
  4520. isCancalBossBattle = true;
  4521. console.log(reason, info);
  4522. resolve();
  4523. }
  4524. }
  4525.  
  4526. function testAutoBattle() {
  4527. return new Promise((resolve, reject) => {
  4528. const bossBattle = new executeAutoBattle(resolve, reject);
  4529. bossBattle.start(lastBattleArg, lastBattleInfo);
  4530. });
  4531. }
  4532.  
  4533. /** Автоповтор атаки */
  4534. function executeAutoBattle(resolve, reject) {
  4535. let battleArg = {};
  4536. let countBattle = 0;
  4537. let countMaxBattle = 10;
  4538.  
  4539. this.start = function (battleArgs, battleInfo) {
  4540. battleArg = battleArgs;
  4541. preCalcBattle(battleInfo);
  4542. }
  4543. /** Возвращает промис для прерасчета боя */
  4544. function getBattleInfo(battle) {
  4545. return new Promise(function (resolve) {
  4546. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  4547. BattleCalc(battle, getBattleType(battle.type), e => resolve(e.result.win));
  4548. });
  4549. }
  4550. /** Прерасчет боя */
  4551. function preCalcBattle(battle) {
  4552. let actions = [];
  4553. const countTestBattle = getInput('countTestBattle');
  4554. for (let i = 0; i < countTestBattle; i++) {
  4555. actions.push(getBattleInfo(battle));
  4556. }
  4557. Promise.all(actions)
  4558. .then(resultPreCalcBattle);
  4559. }
  4560. /** Обработка результатов прерасчета боя */
  4561. function resultPreCalcBattle(results) {
  4562. let countWin = results.reduce((w, s) => w + s);
  4563. setProgress(`Шансы ${countWin} к ${results.length}`, true);
  4564. if (countWin > 0) {
  4565. isCancalBattle = false;
  4566. startBattle();
  4567. return;
  4568. }
  4569. endAutoBattle('Не в этот раз');
  4570. }
  4571. /** Начало боя */
  4572. function startBattle() {
  4573. countBattle++;
  4574. countMaxBattle = getInput('countAutoBattle');
  4575. setProgress(countBattle + '/' + countMaxBattle);
  4576. if (countBattle > countMaxBattle) {
  4577. setProgress('Превышен лимит попыток: ' + countMaxBattle, true);
  4578. endAutoBattle('Превышен лимит попыток: ' + countMaxBattle)
  4579. return;
  4580. }
  4581. let calls = [{
  4582. name: nameFuncStartBattle,
  4583. args: battleArg,
  4584. ident: "body"
  4585. }];
  4586. send(JSON.stringify({
  4587. calls
  4588. }), calcResultBattle);
  4589. }
  4590. /** Расчет боя */
  4591. function calcResultBattle(e) {
  4592. let battle = e.results[0].result.response.battle
  4593. BattleCalc(battle, getBattleType(battle.type), resultBattle);
  4594. }
  4595. /** Обработка результатов боя */
  4596. function resultBattle(e) {
  4597. let isWin = e.result.win;
  4598. console.log(isWin);
  4599. if (isWin) {
  4600. endBattle(e, false);
  4601. return;
  4602. }
  4603. cancelEndBattle(e);
  4604. }
  4605. /** Отмена боя */
  4606. function cancelEndBattle(r) {
  4607. const fixBattle = function (heroes) {
  4608. for (const ids in heroes) {
  4609. hero = heroes[ids];
  4610. hero.energy = random(1, 999);
  4611. if (hero.hp > 0) {
  4612. hero.hp = random(1, hero.hp);
  4613. }
  4614. }
  4615. }
  4616. fixBattle(r.progress[0].attackers.heroes);
  4617. fixBattle(r.progress[0].defenders.heroes);
  4618. endBattle(r, true);
  4619. }
  4620. /** Завершение боя */
  4621. function endBattle(battleResult, isCancal) {
  4622. let calls = [{
  4623. name: nameFuncEndBattle,
  4624. args: {
  4625. result: battleResult.result,
  4626. progress: battleResult.progress
  4627. },
  4628. ident: "body"
  4629. }];
  4630.  
  4631. send(JSON.stringify({
  4632. calls
  4633. }), e => {
  4634. console.log(e);
  4635. if (isCancal) {
  4636. startBattle();
  4637. return;
  4638. }
  4639. scriptMenu.setStatus('Победа!');
  4640. setTimeout(() => {
  4641. scriptMenu.setStatus('');
  4642. }, 5000)
  4643. endAutoBattle('Успех!')
  4644. });
  4645. }
  4646. /** Завершение задачи */
  4647. function endAutoBattle(reason, info) {
  4648. isCancalBattle = true;
  4649. console.log(reason, info);
  4650. resolve();
  4651. }
  4652. }
  4653. /** Собрать всю почту, кроме писем с энергией и зарядами портала */
  4654. function mailGetAll() {
  4655. const getMailInfo = '{"calls":[{"name":"mailGetAll","args":{},"ident":"body"}]}';
  4656.  
  4657. return Send(getMailInfo).then(dataMail => {
  4658. const letters = dataMail.results[0].result.response.letters;
  4659. const letterIds = lettersFilter(letters);
  4660. if (!letterIds.length) {
  4661. setProgress('Нечего собирать', true);
  4662. return;
  4663. }
  4664.  
  4665. const calls = [
  4666. { name: "mailFarm", args: { letterIds }, ident: "body" }
  4667. ];
  4668.  
  4669. return Send(JSON.stringify({ calls })).then(res => {
  4670. const lettersIds = res.results[0].result.response;
  4671. if (lettersIds) {
  4672. const countLetters = Object.keys(lettersIds).length;
  4673. setProgress('Получено ' + countLetters + ' писем', true);
  4674. }
  4675. });
  4676. });
  4677. }
  4678. /** Фильтрует получаемые письма */
  4679. function lettersFilter(letters) {
  4680. const lettersIds = [];
  4681. for (let l in letters) {
  4682. letter = letters[l];
  4683. const reward = letter.reward;
  4684. /** Исключения на сбор писем */
  4685. const isFarmLetter = !(
  4686. (reward?.refillable ? reward.refillable[45] : false) || // сферы портала
  4687. (reward?.stamina ? reward.stamina : false) || // энергия
  4688. (reward?.buff ? true : false) || // ускорение набора энергии
  4689. (reward?.vipPoints ? reward.vipPoints : false) || // вип очки
  4690. (reward?.fragmentHero ? true : false) || // душы героев
  4691. (reward?.bundleHeroReward ? true : false) // герои
  4692. );
  4693. if (isFarmLetter) {
  4694. lettersIds.push(~~letter.id);
  4695. }
  4696. }
  4697. return lettersIds;
  4698. }
  4699. /** Отображение информации о сферах портала и попытках на ВГ */
  4700. async function justInfo() {
  4701. return new Promise(async (resolve, reject) => {
  4702. const calls = [{
  4703. name: "userGetInfo",
  4704. args: {},
  4705. ident: "userGetInfo"
  4706. },
  4707. {
  4708. name: "clanWarGetInfo",
  4709. args: {},
  4710. ident: "clanWarGetInfo"
  4711. }];
  4712. const result = await Send(JSON.stringify({ calls }));
  4713. const infos = result.results;
  4714. const portalSphere = infos[0].result.response.refillable.find(n => n.id == 45);
  4715. const clanWarMyTries = infos[1].result.response?.myTries ?? 0;
  4716. const sanctuaryButton = buttons['goToSanctuary'].button;
  4717. const clanWarButton = buttons['goToClanWar'].button;
  4718. if (portalSphere.amount) {
  4719. sanctuaryButton.style.color = portalSphere.amount >= 3 ? 'red' : 'brown';
  4720. sanctuaryButton.title = 'Святилище ' + portalSphere.amount + ' сферы портала';
  4721. } else {
  4722. sanctuaryButton.style.color = '';
  4723. sanctuaryButton.title = 'Святилище';
  4724. }
  4725. if (clanWarMyTries) {
  4726. clanWarButton.style.color = 'red';
  4727. clanWarButton.title = 'Война гильдий ' + clanWarMyTries + ' ударов';
  4728. } else {
  4729. clanWarButton.style.color = '';
  4730. clanWarButton.title = 'Война гильдий';
  4731. }
  4732. setProgress('<img src="https://zingery.ru/heroes/portal.png" style="height: 25px;position: relative;top: 5px;"> ' + portalSphere.amount + '</br>' + 'ВГ: ' + clanWarMyTries, true);
  4733. resolve();
  4734. });
  4735. }
  4736.  
  4737. function testDailyQuests() {
  4738. return new Promise((resolve, reject) => {
  4739. const bossBattle = new dailyQuests(resolve, reject, questsInfo);
  4740. bossBattle.start();
  4741. });
  4742. }
  4743. /** Автоматическое выполнение ежедневных квестов */
  4744. class dailyQuests {
  4745. /**
  4746. * Send(' {"calls":[{"name":"heroGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  4747. * Send(' {"calls":[{"name":"titanGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  4748. * Send(' {"calls":[{"name":"inventoryGet","args":{},"ident":"body"}]}').then(e => console.log(e))
  4749. * Send(' {"calls":[{"name":"questGetAll","args":{},"ident":"body"}]}').then(e => console.log(e))
  4750. */
  4751. dataQuests = {
  4752. 10001: {
  4753. description: 'Улучши умения героев 3 раза', // Смотреть героев и деньги
  4754. isWeCanDo: () => false,
  4755. },
  4756. 10002: {
  4757. description: 'Пройди 10 миссий', // --------------
  4758. isWeCanDo: () => false,
  4759. },
  4760. 10003: {
  4761. description: 'Пройди 3 героические миссии', // --------------
  4762. isWeCanDo: () => false,
  4763. },
  4764. 10004: {
  4765. description: 'Сразись 3 раза на Арене или Гранд Арене', // --------------
  4766. isWeCanDo: () => false,
  4767. },
  4768. 10006: {
  4769. description: 'Используй обмен изумрудов 1 раз',
  4770. doItCall: [{ name: "refillableAlchemyUse", args: { multi: false }, ident: "refillableAlchemyUse" }],
  4771. isWeCanDo: () => false,
  4772. },
  4773. 10007: {
  4774. description: 'Открой 1 сундук', // ++++++++++++++++
  4775. doItCall: [{ name: "chestBuy", args: { chest: "town", free: true, pack: false }, ident: "chestBuy" }],
  4776. isWeCanDo: (info) => {
  4777. const chestInfo = info['userGetInfo'].refillable.find(e => e.id == 37);
  4778. return chestInfo.amount > 0;
  4779. },
  4780. },
  4781. 10016: {
  4782. description: 'Отправь подарки согильдийцам', // ++++++++++++++++
  4783. doItCall: [{ name: "clanSendDailyGifts", args: {}, ident: "clanSendDailyGifts" }],
  4784. isWeCanDo: () => true,
  4785. },
  4786. 10018: {
  4787. description: 'Используй зелье опыта', // TODO: Смотреть героев, смотреть зелья (consumable 9, 10, 11, 12)
  4788. /** Тратит банку опыта на Галахарда */
  4789. doItCall: [{ name: "consumableUseHeroXp", args: { heroId: 2, libId: 10, amount: 1 }, ident: "consumableUseHeroXp" }],
  4790. isWeCanDo: () => false,
  4791. },
  4792. 10019: {
  4793. description: 'Открой 1 сундук в Башне',
  4794. doItFunc: testTower,
  4795. isWeCanDo: () => false,
  4796. },
  4797. 10020: {
  4798. description: 'Открой 3 сундука в Запределье',
  4799. isWeCanDo: () => false,
  4800. },
  4801. 10021: {
  4802. description: 'Собери 75 Титанита в Подземелье Гильдии',
  4803. isWeCanDo: () => false,
  4804. },
  4805. 10022: {
  4806. description: 'Собери 150 Титанита в Подземелье Гильдии',
  4807. doItFunc: testDungeon,
  4808. isWeCanDo: () => false,
  4809. },
  4810. 10023: {
  4811. description: 'Прокачай Дар Стихий на 1 уровень', // TODO: Смотреть героев, смотреть искры (consumable 24, 250 на 0 уровне и золото 7000)
  4812. /** Улучшение и сброс дара стихий Галахарду */
  4813. doItCall: [
  4814. { name: "heroTitanGiftLevelUp", args: { heroId: 2 }, ident: "heroTitanGiftLevelUp" },
  4815. { name: "heroTitanGiftDrop", args: { heroId: 2 }, ident: "heroTitanGiftDrop" }
  4816. ],
  4817. isWeCanDo: () => false,
  4818. },
  4819. 10024: {
  4820. description: 'Повысь уровень любого артефакта один раз', // Смотреть героев,
  4821. isWeCanDo: () => false,
  4822. },
  4823. 10025: {
  4824. description: 'Начни 1 Экспедицию',
  4825. doItFunc: checkExpedition,
  4826. isWeCanDo: () => false,
  4827. },
  4828. 10026: {
  4829. description: 'Начни 4 Экспедиции', // --------------
  4830. doItFunc: checkExpedition,
  4831. isWeCanDo: () => false,
  4832. },
  4833. 10027: {
  4834. description: 'Победи в 1 бою Турнира Стихий',
  4835. doItFunc: testTitanArena,
  4836. isWeCanDo: () => false,
  4837. },
  4838. 10028: {
  4839. description: 'Повысь уровень любого артефакта титанов', // TODO: Смотреть титанов, можно качать арты за золото если золота больше 5 лямов
  4840. isWeCanDo: () => false,
  4841. },
  4842. 10029: {
  4843. description: 'Открой сферу артефактов титанов', // ++++++++++++++++
  4844. doItCall: [{ name: "titanArtifactChestOpen", args: { amount: 1, free: true }, ident: "titanArtifactChestOpen" }],
  4845. isWeCanDo: (info) => {
  4846. return info['inventoryGet']?.consumable[55] > 0
  4847. },
  4848. },
  4849. 10030: {
  4850. description: 'Улучши облик любого героя 1 раз', // TODO: Смотреть героев
  4851. isWeCanDo: () => false,
  4852. },
  4853. 10031: {
  4854. description: 'Победи в 6 боях Турнира Стихий', // --------------
  4855. doItFunc: testTitanArena,
  4856. isWeCanDo: () => false,
  4857. },
  4858. 10043: {
  4859. description: 'Начни или присоеденись к Приключению', // --------------
  4860. isWeCanDo: () => false,
  4861. },
  4862. 10044: {
  4863. description: 'Воспользуйся призывом питомцев 1 раз', // ++++++++++++++++
  4864. doItCall: [{ name: "pet_chestOpen", args: { amount: 1, paid: false }, ident: "pet_chestOpen" }],
  4865. isWeCanDo: (info) => {
  4866. return info['inventoryGet']?.consumable[90] > 0
  4867. },
  4868. },
  4869. 10046: {
  4870. description: 'Открой 3 сундука в Приключениях', // TODO: Смотреть приключение
  4871. isWeCanDo: () => false,
  4872. },
  4873. 10047: {
  4874. description: 'Набери 150 очков активности в Гильдии', // TODO: Смотреть героев и руны consumable 1, 2, 3, 4
  4875. /** Прокачать руну Галахарду */
  4876. doItCall: [{ name: "heroEnchantRune", args: { heroId: 2, tier: 0, items: { consumable: { '1': 1 } } }, ident: "heroEnchantRune" }],
  4877. isWeCanDo: () => false,
  4878. },
  4879. };
  4880.  
  4881. constructor(resolve, reject, questInfo) {
  4882. this.resolve = resolve;
  4883. this.reject = reject;
  4884. this.questInfo = questInfo
  4885. }
  4886.  
  4887. async start() {
  4888. let countQuest = 0; // TODO возожно не нужна
  4889. const weCanDo = [];
  4890. const selectedActions = getSaveVal('selectedActions', {});
  4891. for (let quest of this.questInfo['questGetAll']) {
  4892. if (quest.id in this.dataQuests && quest.state == 1) {
  4893. if (!selectedActions[quest.id]) {
  4894. selectedActions[quest.id] = {
  4895. checked: false
  4896. }
  4897. }
  4898. if (!this.dataQuests[quest.id].isWeCanDo(this.questInfo)) {
  4899. continue;
  4900. }
  4901. weCanDo.push({
  4902. name: quest.id,
  4903. label: this.dataQuests[quest.id].description,
  4904. checked: selectedActions[quest.id].checked
  4905. });
  4906. countQuest++;
  4907. }
  4908. }
  4909.  
  4910. if (!weCanDo.length) {
  4911. this.end('Нечего выполнять');
  4912. return;
  4913. }
  4914.  
  4915. console.log(weCanDo);
  4916. const answer = await popup.confirm(`Можно выполнить квесты:`, [
  4917. { msg: 'Выполняй', result: true },
  4918. { msg: 'Отмена', result: false },
  4919. ], weCanDo);
  4920. if (!answer) {
  4921. this.end('');
  4922. return;
  4923. }
  4924. const taskList = popup.getCheckBoxes();
  4925. taskList.forEach(e => {
  4926. selectedActions[e.name].checked = e.checked;
  4927. });
  4928. setSaveVal('selectedActions', selectedActions);
  4929. const calls = [];
  4930. let countChecked = 0;
  4931. for (const task of taskList) {
  4932. if (task.checked) {
  4933. countChecked++;
  4934. const quest = this.dataQuests[task.name]
  4935. console.log(quest.description);
  4936.  
  4937. if (quest.doItCall) {
  4938. calls.push(...quest.doItCall);
  4939. }
  4940. }
  4941. }
  4942.  
  4943. if (!countChecked) {
  4944. this.end('Ни одного квеста не выполенно');
  4945. return;
  4946. }
  4947.  
  4948. await Send(JSON.stringify({ calls }));
  4949. this.end('Выполенно квестов: ' + countChecked);
  4950. }
  4951.  
  4952. errorHandling(error) {
  4953. //console.error(error);
  4954. let errorInfo = error.toString() + '\n';
  4955. try {
  4956. const errorStack = error.stack.split('\n');
  4957. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  4958. errorInfo += errorStack.slice(0, endStack).join('\n');
  4959. } catch (e) {
  4960. errorInfo += error.stack;
  4961. }
  4962. copyText(errorInfo);
  4963. }
  4964.  
  4965. end(status) {
  4966. setProgress(status, true);
  4967. this.resolve();
  4968. }
  4969. }
  4970.  
  4971. function testDoYourBest() {
  4972. return new Promise((resolve, reject) => {
  4973. const doIt = new doYourBest(resolve, reject);
  4974. doIt.start();
  4975. });
  4976. }
  4977. /** Кнопка сделать все */
  4978. class doYourBest {
  4979.  
  4980. funcList = [
  4981. {
  4982. name: 'getOutland',
  4983. label: 'Собрать Запределье',
  4984. checked: false
  4985. },
  4986. {
  4987. name: 'testTower',
  4988. label: 'Пройти башню',
  4989. checked: false
  4990. },
  4991. {
  4992. name: 'checkExpedition',
  4993. label: 'Проверить экспедиции',
  4994. checked: false
  4995. },
  4996. {
  4997. name: 'testTitanArena',
  4998. label: 'Пройти Турнир Стихий',
  4999. checked: false
  5000. },
  5001. {
  5002. name: 'testDungeon',
  5003. label: 'Пройти подземелье',
  5004. checked: false
  5005. },
  5006. {
  5007. name: 'mailGetAll',
  5008. label: 'Собрать почту',
  5009. checked: false
  5010. },
  5011. {
  5012. name: 'collectAllStuff',
  5013. label: 'Собрать пасхалки, камни облика, ключи и монеты арены',
  5014. checked: false
  5015. },
  5016. {
  5017. name: 'questAllFarm',
  5018. label: 'Собрать награды за квесты',
  5019. checked: false
  5020. },
  5021. {
  5022. name: 'synchronization',
  5023. label: 'Сделать синхронизацю',
  5024. checked: false
  5025. },
  5026. ];
  5027.  
  5028. functions = {
  5029. getOutland,
  5030. testTower,
  5031. checkExpedition,
  5032. testTitanArena,
  5033. testDungeon,
  5034. mailGetAll,
  5035. collectAllStuff: async () => {
  5036. await offerFarmAllReward();
  5037. await Send('{"calls":[{"name":"subscriptionFarm","args":{},"ident":"body"},{"name":"zeppelinGiftFarm","args":{},"ident":"zeppelinGiftFarm"},{"name":"grandFarmCoins","args":{},"ident":"grandFarmCoins"}]}');
  5038. },
  5039. questAllFarm,
  5040. synchronization: async () => {
  5041. cheats.refreshGame();
  5042. }
  5043. }
  5044.  
  5045. constructor(resolve, reject, questInfo) {
  5046. this.resolve = resolve;
  5047. this.reject = reject;
  5048. this.questInfo = questInfo
  5049. }
  5050.  
  5051. async start() {
  5052. const selectedDoIt = getSaveVal('selectedDoIt', {});
  5053.  
  5054. this.funcList.forEach(task => {
  5055. if (!selectedDoIt[task.name]) {
  5056. selectedDoIt[task.name] = {
  5057. checked: task.checked
  5058. }
  5059. } else {
  5060. task.checked = selectedDoIt[task.name].checked
  5061. }
  5062. });
  5063.  
  5064. const answer = await popup.confirm('Выполнить следующие функции?', [
  5065. { msg: 'Отмена', result: false },
  5066. { msg: 'Погнали!', result: true },
  5067. ], this.funcList);
  5068.  
  5069. if (!answer) {
  5070. this.end('');
  5071. return;
  5072. }
  5073.  
  5074. const taskList = popup.getCheckBoxes();
  5075. taskList.forEach(task => {
  5076. selectedDoIt[task.name].checked = task.checked;
  5077. });
  5078. setSaveVal('selectedDoIt', selectedDoIt);
  5079. for (const task of popup.getCheckBoxes()) {
  5080. if (task.checked) {
  5081. try {
  5082. setProgress(task.label + '<br>Выполняется!');
  5083. await this.functions[task.name]();
  5084. setProgress(task.label + '<br>Выполнено!');
  5085. } catch (error) {
  5086. if (await popup.confirm('Призошли ошибки при выполнении:<br>' + task.label + '<br>Скопировать в буфер информацию об ошибке?', [
  5087. { msg: 'Нет', result: false },
  5088. { msg: 'Да', result: true },
  5089. ])) {
  5090. this.errorHandling(error);
  5091. }
  5092. }
  5093. }
  5094. }
  5095. setTimeout((msg) => {
  5096. this.end(msg);
  5097. }, 2000, 'Все задачи выполнены');
  5098. return;
  5099. }
  5100.  
  5101. errorHandling(error) {
  5102. //console.error(error);
  5103. let errorInfo = error.toString() + '\n';
  5104. try {
  5105. const errorStack = error.stack.split('\n');
  5106. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testDoYourBest");
  5107. errorInfo += errorStack.slice(0, endStack).join('\n');
  5108. } catch (e) {
  5109. errorInfo += error.stack;
  5110. }
  5111. copyText(errorInfo);
  5112. }
  5113.  
  5114. end(status) {
  5115. setProgress(status, true);
  5116. this.resolve();
  5117. }
  5118. }
  5119.  
  5120. function testAdventure(type) {
  5121. return new Promise((resolve, reject) => {
  5122. const bossBattle = new executeAdventure(resolve, reject);
  5123. bossBattle.start(type);
  5124. });
  5125. }
  5126. /** Прохождение приключения по указанному маршруту */
  5127. class executeAdventure {
  5128.  
  5129. type = 'default';
  5130.  
  5131. actions = {
  5132. default: {
  5133. getInfo: "adventure_getInfo",
  5134. startBattle: 'adventure_turnStartBattle',
  5135. endBattle: 'adventure_endBattle',
  5136. collectBuff: 'adventure_turnCollectBuff'
  5137. },
  5138. solo: {
  5139. getInfo: "adventureSolo_getInfo",
  5140. startBattle: 'adventureSolo_turnStartBattle',
  5141. endBattle: 'adventureSolo_endBattle',
  5142. collectBuff: 'adventureSolo_turnCollectBuff'
  5143. }
  5144. }
  5145.  
  5146. terminatеReason = 'Неизвестно';
  5147. callAdventureInfo = {
  5148. name: "adventure_getInfo",
  5149. args: {},
  5150. ident: "adventure_getInfo"
  5151. }
  5152. callTeamGetAll = {
  5153. name: "teamGetAll",
  5154. args: {},
  5155. ident: "teamGetAll"
  5156. }
  5157. callTeamGetFavor = {
  5158. name: "teamGetFavor",
  5159. args: {},
  5160. ident: "teamGetFavor"
  5161. }
  5162. callStartBattle = {
  5163. name: "adventure_turnStartBattle",
  5164. args: {},
  5165. ident: "body"
  5166. }
  5167. callEndBattle = {
  5168. name: "adventure_endBattle",
  5169. args: {
  5170. result: {},
  5171. progress: {},
  5172. },
  5173. ident: "body"
  5174. }
  5175. callCollectBuff = {
  5176. name: "adventure_turnCollectBuff",
  5177. args: {},
  5178. ident: "body"
  5179. }
  5180.  
  5181. constructor(resolve, reject) {
  5182. this.resolve = resolve;
  5183. this.reject = reject;
  5184. }
  5185.  
  5186. async start(type) {
  5187. this.type = type || this.type;
  5188. this.path = await this.getPath();
  5189. if (!this.path) {
  5190. this.end();
  5191. return;
  5192. }
  5193. this.callAdventureInfo.name = this.actions[this.type].getInfo;
  5194. const data = await Send(JSON.stringify({
  5195. calls: [
  5196. this.callAdventureInfo,
  5197. this.callTeamGetAll,
  5198. this.callTeamGetFavor
  5199. ]
  5200. }));
  5201. return this.checkAdventureInfo(data.results);
  5202. }
  5203.  
  5204. async getPath() {
  5205. const answer = await popup.confirm('Введите путь приключения через запятые', [
  5206. {
  5207. msg: 'Начать приключение по этому пути!',
  5208. placeholder: '1,2,3,4,5,6',
  5209. isInput: true,
  5210. default: getSaveVal('adventurePath', '')
  5211. },
  5212. {
  5213. msg: 'Отмена',
  5214. result: false
  5215. },
  5216. ]);
  5217. if (!answer) {
  5218. this.terminatеReason = 'Отменено';
  5219. return false;
  5220. }
  5221. let path = answer.split(',');
  5222. if (path.length < 2) {
  5223. this.terminatеReason = 'Путь должен состоять минимум из 2х точек';
  5224. return false;
  5225. }
  5226.  
  5227. for (let p in path) {
  5228. path[p] = +path[p].trim()
  5229. if (Number.isNaN(path[p])) {
  5230. this.terminatеReason = 'Путь должен содержать только цифры и запятые';
  5231. return false;
  5232. }
  5233. }
  5234. setSaveVal('adventurePath', answer);
  5235. return path;
  5236. }
  5237.  
  5238. checkAdventureInfo(data) {
  5239. this.advInfo = data[0].result.response;
  5240. if (!this.advInfo) {
  5241. this.terminatеReason = 'Вы не в приключении';
  5242. return this.end();
  5243. }
  5244. const heroesTeam = data[1].result.response.adventure_hero;
  5245. const favor = data[2]?.result.response.adventure_hero;
  5246. const heroes = heroesTeam.slice(0, 5);
  5247. const pet = heroesTeam[5];
  5248. this.args = {
  5249. pet,
  5250. heroes,
  5251. favor,
  5252. path: [],
  5253. broadcast: false
  5254. }
  5255. const advUserInfo = this.advInfo.users[userInfo.id];
  5256. this.turnsLeft = advUserInfo.turnsLeft;
  5257. this.currentNode = advUserInfo.currentNode;
  5258. this.nodes = this.advInfo.nodes;
  5259. return this.loop();
  5260. }
  5261.  
  5262. async loop() {
  5263. const position = this.path.indexOf(+this.currentNode);
  5264. if (!(~position)) {
  5265. this.terminatеReason = 'Вашего местоположения нет на пути';
  5266. return this.end();
  5267. }
  5268. this.path = this.path.slice(position);
  5269. if ((this.path.length - 1) > this.turnsLeft &&
  5270. await popup.confirm('Ваших попыток не достаточно для завершения пути, продолжить?', [
  5271. { msg: 'Да, продолжай!', result: false },
  5272. { msg: 'Нет', result: true },
  5273. ])) {
  5274. this.terminatеReason = 'Попыток не достаточно';
  5275. return this.end();
  5276. }
  5277. const toPath = [];
  5278. for (const nodeId of this.path) {
  5279. if (!this.turnsLeft) {
  5280. this.terminatеReason = 'Попытки закончились';
  5281. return this.end();
  5282. }
  5283. toPath.push(nodeId);
  5284. console.log(toPath);
  5285. if (toPath.length > 1) {
  5286. setProgress(toPath.join(' > ') + ' Ходы: ' + this.turnsLeft);
  5287. }
  5288. if (nodeId == this.currentNode) {
  5289. continue;
  5290. }
  5291.  
  5292. const nodeInfo = this.getNodeInfo(nodeId);
  5293. if (nodeInfo.type == 'TYPE_COMBAT') {
  5294. if (nodeInfo.state == 'empty') {
  5295. this.turnsLeft--;
  5296. continue;
  5297. }
  5298.  
  5299. /** Отключаем штатную отменую боя */
  5300. isCancalBattle = false;
  5301. if (await this.battle(toPath)) {
  5302. this.turnsLeft--;
  5303. toPath.splice(0, toPath.indexOf(nodeId));
  5304. nodeInfo.state = 'empty';
  5305. isCancalBattle = true;
  5306. continue;
  5307. }
  5308. isCancalBattle = true;
  5309. return this.end()
  5310. }
  5311.  
  5312. if (nodeInfo.type == 'TYPE_PLAYERBUFF') {
  5313. const buff = this.checkBuff(nodeInfo);
  5314. if (buff == null) {
  5315. continue;
  5316. }
  5317.  
  5318. if (await this.collectBuff(buff, toPath)) {
  5319. this.turnsLeft--;
  5320. toPath.splice(0, toPath.indexOf(nodeId));
  5321. continue;
  5322. }
  5323. this.terminatеReason = 'Ошибка при получении бафа';
  5324. return this.end();
  5325. }
  5326. }
  5327. this.terminatеReason = 'Успех!';
  5328. return this.end();
  5329. }
  5330.  
  5331. /** Проведение боя */
  5332. async battle(path, preCalc = true) {
  5333. const data = await this.startBattle(path);
  5334. try {
  5335. const battle = data.results[0].result.response.battle;
  5336. const result = await Calc(battle);
  5337. if (result.result.win) {
  5338. const info = await this.endBattle(result);
  5339. if (info.results[0].result.response?.error) {
  5340. this.terminatеReason = 'Ошибка завершения боя';
  5341. return false;
  5342. }
  5343. } else {
  5344. await this.cancelBattle(result);
  5345.  
  5346. if (preCalc && await this.preCalcBattle(battle)) {
  5347. path = path.slice(-2);
  5348. for (let i = 1; i <= getInput('countAutoBattle'); i++) {
  5349. setProgress('АвтоБой: ' + i + '/' + getInput('countAutoBattle'));
  5350. const result = await this.battle(path, false);
  5351. if (result) {
  5352. setProgress('Победа');
  5353. return true;
  5354. }
  5355. }
  5356. this.terminatеReason = 'Не удалось победить в автобою';
  5357. return false;
  5358. }
  5359. return false;
  5360. }
  5361. } catch (error) {
  5362. console.error(error);
  5363. if (await popup.confirm('Призошли ошибка в процессе прохождения боя<br>Скопировать ошибку в буфер обмена?', [
  5364. { msg: 'Нет', result: false },
  5365. { msg: 'Да', result: true },
  5366. ])) {
  5367. this.errorHandling(error, data);
  5368. }
  5369. this.terminatеReason = 'Ошибка в процессе прохождения боя';
  5370. return false;
  5371. }
  5372. return true;
  5373. }
  5374.  
  5375. /** Прерасчтет битвы */
  5376. async preCalcBattle(battle) {
  5377. const countTestBattle = getInput('countTestBattle');
  5378. for (let i = 0; i < countTestBattle; i++) {
  5379. battle.seed = Math.floor(Date.now() / 1000) + random(0, 1e3);
  5380. const result = await Calc(battle);
  5381. if (result.result.win) {
  5382. console.log(i, countTestBattle);
  5383. return true;
  5384. }
  5385. }
  5386. this.terminatеReason = 'Нет шансов победить в этом бою: 0/' + countTestBattle;
  5387. return false;
  5388. }
  5389.  
  5390. /** Начинает бой */
  5391. startBattle(path) {
  5392. this.args.path = path;
  5393. this.callStartBattle.name = this.actions[this.type].startBattle;
  5394. this.callStartBattle.args = this.args
  5395. const calls = [this.callStartBattle];
  5396. return Send(JSON.stringify({ calls }));
  5397. }
  5398.  
  5399. cancelBattle(battle) {
  5400. const fixBattle = function (heroes) {
  5401. for (const ids in heroes) {
  5402. const hero = heroes[ids];
  5403. hero.energy = random(1, 999);
  5404. if (hero.hp > 0) {
  5405. hero.hp = random(1, hero.hp);
  5406. }
  5407. }
  5408. }
  5409. fixBattle(battle.progress[0].attackers.heroes);
  5410. fixBattle(battle.progress[0].defenders.heroes);
  5411. return this.endBattle(battle);
  5412. }
  5413.  
  5414. /** Заканчивает бой */
  5415. endBattle(battle) {
  5416. this.callEndBattle.name = this.actions[this.type].endBattle;
  5417. this.callEndBattle.args.result = battle.result
  5418. this.callEndBattle.args.progress = battle.progress
  5419. const calls = [this.callEndBattle];
  5420. return Send(JSON.stringify({ calls }));
  5421. }
  5422.  
  5423. /** Проверяет можно ли получить баф */
  5424. checkBuff(nodeInfo) {
  5425. let id = null;
  5426. let value = 0;
  5427. for (const buffId in nodeInfo.buffs) {
  5428. const buff = nodeInfo.buffs[buffId];
  5429. if (buff.owner == null && buff.value > value) {
  5430. id = buffId;
  5431. value = buff.value;
  5432. }
  5433. }
  5434. nodeInfo.buffs[id].owner = 'Я';
  5435. return id;
  5436. }
  5437.  
  5438. /** Собирает баф */
  5439. async collectBuff(buff, path) {
  5440. this.callCollectBuff.name = this.actions[this.type].collectBuff;
  5441. this.callCollectBuff.args = { buff, path };
  5442. const calls = [this.callCollectBuff];
  5443. return Send(JSON.stringify({ calls }));
  5444. }
  5445.  
  5446. getNodeInfo(nodeId) {
  5447. return this.nodes.find(node => node.id == nodeId);
  5448. }
  5449.  
  5450. errorHandling(error, data) {
  5451. //console.error(error);
  5452. let errorInfo = error.toString() + '\n';
  5453. try {
  5454. const errorStack = error.stack.split('\n');
  5455. const endStack = errorStack.map(e => e.split('@')[0]).indexOf("testAdventure");
  5456. errorInfo += errorStack.slice(0, endStack).join('\n');
  5457. } catch (e) {
  5458. errorInfo += error.stack;
  5459. }
  5460. if (data) {
  5461. errorInfo += '\nData: ' + JSON.stringify(data);
  5462. }
  5463. copyText(errorInfo);
  5464. }
  5465.  
  5466. end() {
  5467. isCancalBattle = true;
  5468. setProgress(this.terminatеReason, true);
  5469. console.log(this.terminatеReason);
  5470. this.resolve();
  5471. }
  5472. }
  5473. })();
  5474.  
  5475. /**
  5476. * TODO:
  5477. * Получение всех уровней при сборе всех наград (квест на титанит и на энку)
  5478. * Добивание на арене титанов
  5479. */