pid0r / Автоматические тренировки

// ==UserScript==
// @name         Автоматические тренировки
// @namespace    http://tampermonkey.net/
// @version      1.0.0.1
// @description  Тренируемся приятнее
// @author       pid0r
// @license      MIT; https://opensource.org/licenses/MIT
// @match        https://catwar.su/cw3/
// ==/UserScript==

(function() {
    'use strict';

    if (document.getElementById('menu')) {
        return;
    }

    let isLPressed = false;
    let CheckRotate = true;
    let intervalId;
    let arrowRedCheckIntervalId;
    let scriptRunning = false;
    let customId = 0; // дефолт айди
    let hitsCount = 4; // дефоли количество ударов
    let targetSelection = 'paws'; // лапы по умолчанию

    function get_rotate() {
        let arrow = document.getElementById('arrow' + customId);
        if (arrow) {
            let transform = arrow.style.transform;
            if (transform) {
                let match = transform.match(/rotate\((\d+(\.\d+)?)deg\)/);
                if (match && match[1]) {
                    return parseFloat(match[1]);
                }
            }
        }
        return null;
    }

    // рестарт на m
    function restartOnKeyPressM(event) {
        if (event.key === 'm') {
            restartScript();
        }
    }
    document.addEventListener('keydown', restartOnKeyPressM);

    function get_ared() {
        let arrow = document.getElementById('arrow' + customId);
        if (arrow) {
            let arrowRed = arrow.querySelector('.arrow_red');
            if (arrowRed) {
                let width = arrowRed.style.width;
                if (width) {
                    let value = parseFloat(width);
                    return isNaN(value) ? 0 : value;
                }
            }
        }
        return 0;
    }

    function pressKey(key, keyCode) {
        document.dispatchEvent(new KeyboardEvent('keydown', {
            key: key,
            keyCode: keyCode,
            which: keyCode
        }));
    }

    function releaseKey(key, keyCode) {
        document.dispatchEvent(new KeyboardEvent('keyup', {
            key: key,
            keyCode: keyCode,
            which: keyCode
        }));
    }

    function pressL() {
        if (!isLPressed) {
            isLPressed = true;
            pressKey('L', 76);
        }
    }

    function releaseL() {
        if (isLPressed) {
            isLPressed = false;
            releaseKey('L', 76);
        }
    }

    function press_i(times, callback) {
        let count = 0;
        function next_i() {
            if (count < times) {
                pressKey('I', 73);
                releaseKey('I', 73);
                count++;
                setTimeout(next_i, Math.random() * 300 + 400);
            } else if (callback) {
                callback();
            }
        }
        next_i();
    }

    function holdLUntilArrowRedChanges() {
        pressL();
        arrowRedCheckIntervalId = setInterval(() => {
            if (get_ared() > 0) {
                clearInterval(arrowRedCheckIntervalId);
                releaseL();
                setTimeout(() => {
                    pressLFor3000ms();
                }, 100);
            }
        }, 100);
    }

    function pressLFor3000ms() {
        pressL();
        setTimeout(() => {
            releaseL();
            setTimeout(() => {
                start_check_rotate();
            }, 100);
        }, 3000);
    }

    function startScript() {
        if (!scriptRunning) {
            scriptRunning = true;
            press_br();
            setTimeout(() => {
                holdLUntilArrowRedChanges();
            }, 200);
        }
    }

    function restartScript() {
        stopScript();
        startScript();
    }

    function stopScript() {
        scriptRunning = false;
        clearInterval(intervalId);
        clearInterval(arrowRedCheckIntervalId);
        releaseL();
        isLPressed = false;
        CheckRotate = true;
    }

    function press_br() {
        let button27 = document.querySelector('a[data-id="27"]');
        if (button27) {
            button27.click();
        }
    }

    function checkRotateAndHoldL() {
        let rotate = get_rotate();

        if (CheckRotate && rotate !== null) {
            let rotateMin, rotateMax;
            if (targetSelection === 'paws') {
                rotateMin = 185;
                rotateMax = 220;
            } else if (targetSelection === 'tail') {
                rotateMin = 305;
                rotateMax = 335;
            }

            if (rotate < rotateMin || rotate > rotateMax) {
                pressL();
            } else {
                releaseL();
                stop_check_rotate();
                setTimeout(() => {
                    press_i(hitsCount, () => {
                        holdLUntilArrowRedZero();
                    });
                }, Math.random() * 400 + 800);
            }
        }
    }

    function holdLUntilArrowRedZero() {
        pressL();
        arrowRedCheckIntervalId = setInterval(() => {
            if (get_ared() === 0) {
                clearInterval(arrowRedCheckIntervalId);
                releaseL();
                setTimeout(() => {
                    press_exit();
                }, Math.random() * 400 + 100);
            }
        }, 100);
    }

    function press_exit() {
        let button28 = document.querySelector('a[data-id="28"]');
        if (button28) {
            button28.click();
        }
    }

    function start_check_rotate() {
        CheckRotate = true;
        intervalId = setInterval(checkRotateAndHoldL, 100);
    }

    function stop_check_rotate() {
        clearInterval(intervalId);
        releaseL();
        CheckRotate = false;
    }

    function saveMenuPosition() {
        localStorage.setItem('menuPosition', JSON.stringify({
            top: menu.style.top,
            left: menu.style.left
        }));
    }

    function loadMenuPosition() {
        const savedPosition = localStorage.getItem('menuPosition');
        if (savedPosition) {
            const position = JSON.parse(savedPosition);
            menu.style.top = position.top;
            menu.style.left = position.left;
        }
    }

    function saveInputValues() {
        localStorage.setItem('customId', customId);
        localStorage.setItem('hitsCount', hitsCount);
        localStorage.setItem('targetSelection', targetSelection);
    }

    function loadInputValues() {
        const savedCustomId = localStorage.getItem('customId');
        const savedHitsCount = localStorage.getItem('hitsCount');
        const savedTargetSelection = localStorage.getItem('targetSelection');
        if (savedCustomId !== null) {
            customId = parseInt(savedCustomId, 10);
            idInput.value = customId;
        }
        if (savedHitsCount !== null) {
            hitsCount = parseInt(savedHitsCount, 10);
            hitsInput.value = hitsCount;
        }
        if (savedTargetSelection !== null) {
            targetSelection = savedTargetSelection;
            document.querySelector(input[name="target"][value="${targetSelection}"]).checked = true;
        }
    }

    function create_menu() {
        const menu = document.createElement('div');
        menu.id = 'menu';
        menu.style.position = 'fixed';
        menu.style.top = '10px';
        menu.style.left = '10px';
        menu.style.padding = '10px';
        menu.style.backgroundColor = 'rgb(34, 34, 34)';
        menu.style.borderRadius = '10px';
        menu.style.zIndex = 1000;
        menu.style.color = 'rgb(131, 131, 131)';
        menu.style.width = '160px';
        menu.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.3)';

        // Поле ввода "Ваш айди:"
        const idInputContainer = document.createElement('div');
        const idInputLabel = document.createElement('div');
        idInputLabel.textContent = 'Ваш айди:';
        idInputLabel.style.textAlign = 'center';
        idInputLabel.style.marginBottom = '5px';
        const idInput = document.createElement('input');
        idInput.type = 'text';
        idInput.placeholder = '(ввод)';
        idInput.style.width = 'calc(100%)';
        idInput.style.marginBottom = '5px';
        idInput.style.display = 'block';
        idInput.style.marginLeft = 'auto';
        idInput.style.marginRight = 'auto';
        idInputContainer.appendChild(idInputLabel);
        idInputContainer.appendChild(idInput);

        // Поле ввода "Количество ударов:"
        const hitsInputContainer = document.createElement('div');
        const hitsInputLabel = document.createElement('div');
        hitsInputLabel.textContent = 'Количество ударов:';
        hitsInputLabel.style.textAlign = 'center';
        hitsInputLabel.style.marginBottom = '5px';
        const hitsInput = document.createElement('input');
        hitsInput.type = 'number';
        hitsInput.placeholder = '(ввод)';
        hitsInput.style.width = 'calc(100%)';
        hitsInput.style.marginBottom = '5px';
        hitsInput.style.display = 'block';
        hitsInput.style.marginLeft = 'auto';
        hitsInput.style.marginRight = 'auto';
        hitsInputContainer.appendChild(hitsInputLabel);
        hitsInputContainer.appendChild(hitsInput);

        // удары из ввода
        hitsInput.addEventListener('input', function(event) {
            hitsCount = parseInt(event.target.value) || 4;
            saveInputValues();
        });

        // айди из ввода
        idInput.addEventListener('input', function(event) {
            customId = parseInt(event.target.value) || 0;
            saveInputValues();
        });

        // выбора лапы/хвост
        const targetContainer = document.createElement('div');
        const targetLabel = document.createElement('div');
        targetContainer.appendChild(targetLabel);

        const pawsInput = document.createElement('input');
        pawsInput.type = 'radio';
        pawsInput.name = 'target';
        pawsInput.value = 'paws';
        pawsInput.checked = true;
        pawsInput.id = 'targetPaws';
        const pawsLabel = document.createElement('label');
        pawsLabel.textContent = 'Лапы';
        pawsLabel.htmlFor = 'targetPaws';
        pawsLabel.style.marginRight = '10px';

        const tailInput = document.createElement('input');
        tailInput.type = 'radio';
        tailInput.name = 'target';
        tailInput.value = 'tail';
        tailInput.id = 'targetTail';
        const tailLabel = document.createElement('label');
        tailLabel.textContent = 'Хвост';
        tailLabel.htmlFor = 'targetTail';

        targetContainer.appendChild(pawsInput);
        targetContainer.appendChild(pawsLabel);
        targetContainer.appendChild(tailInput);
        targetContainer.appendChild(tailLabel);

        targetContainer.addEventListener('input', function(event) {
            targetSelection = event.target.value;
            saveInputValues();
        });

        // старт
        const startButton = document.createElement('button');
        startButton.textContent = 'Старт скрипт';
        startButton.onclick = startScript;
        startButton.style.display = 'block';
        startButton.style.width = '100%';
        startButton.style.backgroundColor = 'rgb(17, 17, 17)';
        startButton.style.color = 'rgb(131, 131, 131)';
        startButton.style.borderRadius = '5px';
        startButton.style.border = '1px solid rgb(40, 40, 40)';
        startButton.style.marginBottom = '5px';

        // рестарт
        const restartButton = document.createElement('button');
        restartButton.textContent = 'Рестарт скрипт';
        restartButton.onclick = restartScript;
        restartButton.style.display = 'block';
        restartButton.style.width = '100%';
        restartButton.style.backgroundColor = 'rgb(17, 17, 17)';
        restartButton.style.color = 'rgb(131, 131, 131)';
        restartButton.style.borderRadius = '5px';
        restartButton.style.border = '1px solid rgb(40, 40, 40)';
        restartButton.style.marginBottom = '5px';

        // стоп
        const stopButton = document.createElement('button');
        stopButton.textContent = 'Стоп скрипт';
        stopButton.onclick = stopScript;
        stopButton.style.display = 'block';
        stopButton.style.width = '100%';
        stopButton.style.backgroundColor = 'rgb(17, 17, 17)';
        stopButton.style.color = 'rgb(131, 131, 131)';
        stopButton.style.borderRadius = '5px';
        stopButton.style.border = '1px solid rgb(40, 40, 40)';

        // кнопка перемещения
        const moveButton = document.createElement('button');
        moveButton.textContent = '☰';
        moveButton.style.position = 'absolute';
        moveButton.style.top = '-5px';
        moveButton.style.left = '5px';
        moveButton.style.padding = '5px';
        moveButton.style.color = 'rgb(131, 131, 131)';
        moveButton.style.backgroundColor = 'transparent';
        moveButton.style.border = 'none';
        moveButton.style.borderRadius = '5px';
        moveButton.style.cursor = 'move';

        // Добавление элементов в меню
        menu.appendChild(idInputContainer);
        menu.appendChild(hitsInputContainer);
        menu.appendChild(targetContainer);
        menu.appendChild(startButton);
        menu.appendChild(restartButton);
        menu.appendChild(stopButton);
        menu.appendChild(moveButton);

        document.body.appendChild(menu);

        // перемещение
        function startMoveMenu(event) {
            let shiftX = event.clientX - menu.getBoundingClientRect().left;
            let shiftY = event.clientY - menu.getBoundingClientRect().top;

            function moveAt(pageX, pageY) {
                menu.style.left = pageX - shiftX + 'px';
                menu.style.top = pageY - shiftY + 'px';
                saveMenuPosition(); // сохранение позиции меню
            }

            function onMouseMove(event) {
                moveAt(event.pageX, event.pageY);
            }

            document.addEventListener('mousemove', onMouseMove);

            menu.onmouseup = function() {
                document.removeEventListener('mousemove', onMouseMove);
                menu.onmouseup = null;
            };
        }

        moveButton.onmousedown = function(event) {
            event.preventDefault();
            startMoveMenu(event);
        };

        menu.ondragstart = function() {
            return false;
        };

        loadMenuPosition(); // загрузка позиции меню
        loadInputValues(); // загрузка значений

    }

    create_menu();
})();