Greasy Fork

New Something c00L

Too lazy to do something

目前为 2023-09-14 提交的版本。查看 最新版本

// ==UserScript==
// @name         New Something c00L
// @namespace    erepFarm
// @version      1.2.666
// @description  Too lazy to do something
// @author       You
// @match        https://www.erepublik.com/en
// @grant        none
// @run-at		document-end
// ==/UserScript==

(function() {

    // Main function to perform the main task
async function mainFunction() {
    let energymin = 400;
    let aircraft = true;
    let groundWeaponUse = true;
    let abWeaponUse = false;
    let weapQu = -1;
    let groundWeaponQ = 7;
    let abWeaponQ = 5;
    let energy = erepublik.citizen.energy;
    const ablow = 20000;
    const abhigh = 28000;
    const gblow = 160000000;
    const gbhigh = 260000000;
    const abmid = (ablow + abhigh)/2;
    const gbmid = (gblow + gbhigh)/2;
    let low; let mid; let high;


    if (aircraft == true){
        low = ablow;
        mid = abmid;
        high = abhigh;
        createDivElement('aircraft', 'sidebar', 'Aicraft: ');
        createDivElement('slow', 'sidebar', 'Low Damage: ');
        displayValueInHtml('slow', low);
        createDivElement('smid', 'sidebar', 'Mid Damage: ');
        displayValueInHtml('smid', mid);
        createDivElement('shigh', 'sidebar', 'High Damage: ');
        displayValueInHtml('shigh', high);
        createDivElement('useweapon', 'sidebar', 'Activate Weapon: ');
        displayValueInHtml('useweapon', abWeaponUse);
        if(abWeaponUse == true){
            weapQu = abWeaponQ;
        }
        console.log("weapon Quality:",weapQu);
    }
    else {
        low = gblow;
        mid = gbmid;
        high = gbhigh;
        createDivElement('ground', 'sidebar', 'Ground: ');
        createDivElement('slow', 'sidebar', 'Low Damage: ');
        displayValueInHtml('slow', low);
        createDivElement('smid', 'sidebar', 'Mid Damage: ');
        displayValueInHtml('smid', mid);
        createDivElement('shigh', 'sidebar', 'High Damage: ');
        displayValueInHtml('shigh', high);
        createDivElement('useweapon', 'sidebar', 'Activate Weapon: ');
        displayValueInHtml('useweapon', groundWeaponUse);
        if(groundWeaponUse == true){
            weapQu = groundWeaponQ;
        }
        console.log("weapon Quality:",weapQu);

    }

    createDivElement('emptyBattle', 'sidebar', 'Battle List: ');
    createDivElement('list', 'sidebar', '');

    const zone = await fetchData("https://www.erepublik.com/en/military/campaignsJson/citizen");
    await delay(2000);
    const list = await fetchData("https://www.erepublik.com/en/military/campaignsJson/list");



    if(zone && list && energy > energymin){
        try {
            console.log("Aircraft? ", aircraft);
            let _token = csrfToken;
            let countryLocationId = erepublik.citizen.countryLocationId;
            let division;

            if(aircraft == true){division = 11;}
            else {division = erepublik.citizen.division;}


            //separate battle target to array
            for (const battleId in list.battles) {
                if (list.battles.hasOwnProperty(battleId)) {
                    const battle = list.battles[battleId];
                    const zoneId = zone.battles[battleId];
                    const battleType = battle.war_type;
                    const round = battle.zone_id;
                    const rnow = round;
                    let battleZoneId;
                    let end;

                    if(zoneId && aircraft == true){
                        battleZoneId = zoneId.aircraftZoneId;
                    }
                    else {
                        battleZoneId = battleZoneId = zoneId.groundZoneId;
                    }

                    if(battleType == "direct"){
                        const inv = battle.inv.id;
                        const def = battle.def.id;


                        if (inv == countryLocationId || def == countryLocationId){
                            const invpo = battle.inv.points;
                            const devpo = battle.def.points;
                            const point = invpo - devpo;
                            const campaign = Math.abs(point);
                            let oppositeCID;

                            const region = battle.region.name;

                            const batstaturl = `https://www.erepublik.com/en/military/battle-stats/${battleId}/${division}/${battleZoneId}`;
                            const getbatstat = await fetchData(batstaturl);
                            end = getbatstat.zone_finished;
                            let deffend = false;
                            if (countryLocationId == def){
                                deffend = true;
                                oppositeCID = inv;
                            }
                            if (countryLocationId == inv){
                                deffend = false;
                                oppositeCID = def;
                            }
                            console.log(region," deffend?",deffend);
                            await delay(1000);

                            if(end == false){
                                const payloadBStat = payloadStat(battleId, round, rnow, division, battleZoneId, _token);
                                const stat = await battleStat(payloadBStat);
                                const empty = checkFighterDataEmpty(stat, countryLocationId);


                                if (empty == true){
                                    //check damage per hit
                                    const inventoryLoad = inventoryPayload(battleId, countryLocationId, battleZoneId, _token);
                                    const inventory = await inventoryCheck(inventoryLoad);
                                    let pool = inventory.poolEnergy;
                                    const listweapon = inventory.weapons;
                                    const vehicles = inventory.vehicles;
                                    let totDamage = 0;

                                    // Find the object with quality 10 in the weapons response array
                                    const objectWithQuality = listweapon.find(item => item.quality === weapQu);

                                    // Get the value of the 'amount' property if the object is found
                                    let weaponAmount;
                                    let dph;
                                    if (objectWithQuality) {
                                        weaponAmount = objectWithQuality.amount;
                                        dph = objectWithQuality.damageperHit;
                                    }

                                    //skin
                                    const skinRecommended = vehicles.find(skin => skin.isRecommended === true);
                                    let skinId;
                                    let skinBonus;

                                    if (skinRecommended) {
                                        skinId = skinRecommended.id;
                                        skinBonus = skinRecommended.countryData.damageBonus;                                      
                                    }

                                    let percentage = 0;
                                    if (skinBonus !== null) {
                                        percentage = skinBonus / 100;
                                    }

                                    let damageBonus = dph + (dph * percentage);
                                    console.log("Damage bonus: ",damageBonus);


                                    //check opposite total damage
                                    const opposite = checkFighterDataEmpty(stat, oppositeCID);
                                    if (opposite == false){
                                        totDamage = calculateTotalValue(stat, oppositeCID)
                                    }

                                    const linkText = `${region} - ${totDamage}`;
                                    const linkUrl = `https://www.erepublik.com/en/military/battlefield/${battleId}/${battleZoneId}`;
                                    displayLinkInHtml('list', linkText, linkUrl);
                                    console.log("Total Damage opposite: ",totDamage);

                                    //check damage
                                    const damageHit = await checkDamage(low, mid, high, deffend, totDamage, damageBonus, campaign);
                                    if (damageHit > 10){
                                        console.log("Expected Energy: ", damageHit);
                                    }
                                    let delayTime = (damageHit/10) * 400;
                                    console.log("Energy left: ", pool);

                                    if (pool > damageHit){
                                        const loadDeploy = deployLoad(battleId, battleZoneId, countryLocationId, weapQu, damageHit, skinId, _token);
                                        const deployHit = deployDamage(loadDeploy);
                                        console.log(deployHit);
                                        await delay(delayTime);
                                    }
                                    
                                    

                                    
                                }

                                await delay(1000);
                            }

                            console.log("--------------");
                        }
                    }
                }
            }
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    }
}

//list of function

    // Function to send GET request and fetch JSON data
    async function fetchData(url) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();
            return data;
        } catch (error) {
            throw new Error(`Failed to fetch data from ${url}: ${error.message}`);
        }
    }

    // Function to introduce a delay
    function delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Function to construct the payload from variables
    function payloadStat(battleId, zoneId, round, division, battleZoneId, _token) {
        const action = "battleStatistics";
        const type = "damage";
        const leftPage = 1;
        const rightPage = 1;

        return {
            battleId,
            zoneId,
            action,
            round,
            division,
            battleZoneId,
            type,
            leftPage,
            rightPage,
            _token
        };
    }

    // Function to send the payload using POST request
    async function battleStat(payload) {
        const url = "https://www.erepublik.com/en/military/battle-console";

        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    // Function to check if country.fighterData is empty and push to new array if empty
    function checkFighterDataEmpty(responseData, countryLocationId) {
        if (responseData && responseData[countryLocationId] && responseData[countryLocationId]["fighterData"]) {
            const fighterData = responseData[countryLocationId]["fighterData"];
            const isFighterDataEmpty = Object.keys(fighterData).length === 0;
            return isFighterDataEmpty;
        } else {
            console.log(`Could not find ${countryLocationId}.fighterData in the response.`);
        }
    }

    // Function to calculate the total value
    function calculateTotalValue(data, countryId) {
        let totalValue = 0;
        const fighterData = data[countryId]?.fighterData || {};

        for (const key in fighterData) {
          if (fighterData.hasOwnProperty(key)) {
            const value = fighterData[key].value;
            if (typeof value === 'string') {
              const parsedValue = parseInt(value.replace(/,/g, ''), 10);
              if (!isNaN(parsedValue)) {
                totalValue += parsedValue;
              }
            }
          }
        }

        return totalValue;
      }

      //payload for inventory
      function inventoryPayload(battleId, sideCountryId, battleZoneId, _token) {
        return {
            battleId,
            sideCountryId,
            battleZoneId,
            _token
        };
    }

      //function to check inventory
      async function inventoryCheck(payload) {
        const url = "https://www.erepublik.com/en/military/fightDeploy-getInventory";

        try {
            const response = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });

            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error("Error:", error);
            return null;
        }
    }

    // Function to create a new div element inside a parent element
    function createDivElement(divId, parentId, textContent) {
    const parentElement = document.querySelector(`.${parentId}`);
    if (parentElement) {
        const newDiv = document.createElement('div');
        newDiv.id = divId;
        newDiv.textContent = textContent;
        parentElement.appendChild(newDiv);
    } else {
        console.error(`Parent element with class '${parentId}' not found.`);
    }
}

    // Function to display any value in HTML
    function displayValueInHtml(elementId, value) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = `${element.textContent} ${value}`;
    } else {
        console.error(`Element with ID '${elementId}' not found.`);
    }
}

    function displayLinkInHtml(containerId, linkText, linkUrl) {
    const containerElement = document.getElementById(containerId);
    if (containerElement) {
        const linkElement = document.createElement('a');
        linkElement.href = linkUrl;
        linkElement.target = '_blank';
        linkElement.textContent = linkText;
        containerElement.appendChild(linkElement);
        containerElement.appendChild(document.createElement('br'));
    } else {
        console.error(`Container element with ID '${containerId}' not found.`);
    }
}


    async function checkDamage(low, mid, high, deffend, totDamage, damageBonus, campaign){
        let targetDamage;
        let energyCount;
        let doubleL = low * 2;
        let doubleM = mid * 2;
        let doubleH = high * 2;
        let Hplus = high + (high * 0.15);
        let Mplus = mid + (mid * 0.1);
        
        if (campaign > 20) {
            if (deffend) {
                if (totDamage == 0) {
                    targetDamage = mid;
                } else if (totDamage < low) {
                    targetDamage = mid;
                } else if (totDamage > low && totDamage < mid) {
                    targetDamage = Mplus;
                } else if (totDamage > doubleH) {
                    targetDamage = Hplus;
                } else {
                    targetDamage = high;
                }
            } else {
                if (totDamage == 0) {
                    targetDamage = low;
                } else if (totDamage < low) {
                    targetDamage = low;
                } else if (totDamage > mid && totDamage < doubleL) {
                    targetDamage = mid;
                } else if (totDamage > Hplus) {
                    targetDamage = high;
                } 
            }
        } else if (campaign < 20) {
            if (deffend){
                targetDamage = high;
            } else {
                targetDamage = low;
            }
        }
        energyCount = Math.ceil((targetDamage/damageBonus) * 10);
        return energyCount;
    }


    //function to deploy
    function deployLoad(battleId, battleZoneId, sideCountryId, weaponQuality, totalEnergy, skinId, _token) {
        return {
            battleId,
            battleZoneId,
            sideCountryId,
            weaponQuality,
            totalEnergy,
            skinId,
            _token
        };
    }
    
    // Function to send a POST request for fight deploy
    async function deployDamage(payload) {
        const url = 'https://www.erepublik.com/en/military/fightDeploy-startDeploy';
    
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: Object.keys(payload)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(payload[key])}`)
                    .join('&')
            });
    
            const responseData = await response.json();
            return responseData;
        } catch (error) {
            console.error('Error:', error);
            return null;
        }
    }





    //end of line
        // Call the main function when the page loads
        window.addEventListener('load', mainFunction);
})();