Zombs.io bad(?) Hack

The best defensive script (probably)

目前為 2023-11-12 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Zombs.io bad(?) Hack
// @namespace    https://tampermonkey.net/
// @version      v7.1
// @description  The best defensive script (probably)
// @author       ( o=^•ェ•)
// @match        *://zombs.io/*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js
// ==/UserScript==
/* Everyone who has helped:
AstralCat (many important functions)
Vn Havy (for original bad hack)
Sirr0m (bomber X rebuilder)
eh (bomber X rebuilder)
JaYT (some minor stuff)
Ayubloom (sun:raise for low health upgrading all towers code)
YT er pro th er (for low health upgrade harvesters code)
chatgpt (wrote the whole code 100% no cap :D)
*/
/* global game */
/* global Game */
/* global PIXI */
   if (location.hash.split('/')[4] == 'noscript') { return }
   let cssMain = `
      .bad-btn{
         border: none;
         color: white;
         padding: 10px 20px;
         text-align: center;
         font-size: 14px;
         margin: 2px 0px;
         opacity: 0.9;
         transition: 0.2s;
         display: inline-block;
         border-radius: 15px;
         cursor: pointer;
         text-shadow: -1px 1px 1.5px #242526;
      }
         .bad-btn:hover{
            opacity: 1
         }
         .bad-blue{
            background-color: #5463FF
         }
         .bad-magenta{
            background-color: #E900FF
         }
         .bad-gray{
            background-color: #606060
         }
         .bad-yellow{
            background-color: #FFC600
         }
         .bad-red{
            background-color: #FF1818
         }
         .bad-green{
            background-color: #06FF00
         }
         .bad-pink{
            background-color: #FF6B6B
         }
         .bad-cyan{
            background-color: #39AEA9
         }
         .bad-orange{
            background-color: #FF5F00
         }
         .bad-textbox{
            border: none;
            color: white;
            padding: 10px 10px;
            text-align: center;
            font-size: 14px;
            margin: 2px 0px;
            opacity: 0.9;
            transition: 0.2s;
            display: inline-block;
            border-radius: 15px;
            background-color: #606060;
            text-shadow: -1px 1px 1.5px #242526;
         }

         .hud-toolbar .hud-toolbar-inventory .hud-toolbar-item.is-empty {
            pointer-events: auto;
         }

         #hud-menu-shop {
            top: 45%;
            left: 50%;
            width: 690px;
            height: 450px;
            margin: 0;
            transform: translate(-50%, -50%);
            padding: 20px 20px 20px 20px;
         }
         .hud-menu-shop .hud-shop-grid {
            height: 330px;
         }
         #hud-menu-settings {
            top: 45%;
            left: 50%;
            width: 780px;
            height: 500px;
            margin: 0;
            transform: translate(-50%, -50%);
            padding: 20px 20px 20px 20px;
         }
         .hud-menu-settings .hud-settings-grid {
            width: 750px;
            height: 420px;
         }

         .hud-menu-shop .hud-shop-tabs a[data-type=Pet]::after {
            content: none
         }

         .hud-menu-iframe h3 {
            display: block;
            margin: 0;
            line-height: 20px;
         }

         .hud-menu-iframe{
            display: none;
            position: fixed;
            border-radius: 4px;
            top: 45%;
            left: 50%;
            padding: 20px;
            width: 780px;
            height: 500px;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.6);
            color: #eee;
            z-index: 20;
         }

         .hud-menu-icons .hud-menu-icon[data-type=Iframe]::before {
            background-image: url("https://media.discordapp.net/attachments/870020008128958525/876133010360107048/unknown.png");
            background-size: 30px;
         }
         [data-item=PetGhost][data-tier='1']::after {
            background-image: url('/asset/image/ui/inventory/inventory-pet-ghost-t1.svg');
      `;
   let stylesMain = document.createElement("style");
   stylesMain.appendChild(document.createTextNode(cssMain));
   document.head.appendChild(stylesMain);
   stylesMain.type = "text/css";

   document.querySelectorAll('.ad-unit, .ad-unit-medrec, .hud-intro-guide-hints, .hud-intro-left, .hud-intro-youtuber, .hud-intro-footer, .hud-intro-stone, .hud-intro-tree, .hud-intro-social, .hud-intro-more-games, .hud-intro-guide, .hud-respawn-share, .hud-party-joining, .hud-respawn-corner-bottom-left, #hud-menu-shop > div.hud-shop-grid > a:nth-child(10)').forEach(el => el.remove());
   document.getElementsByClassName('hud-intro-name')[0].setAttribute('maxlength', 29);
   document.getElementsByClassName('hud-party-tag')[0].setAttribute('maxlength', 49);
   document.querySelector(".hud-chat-messages").style.width = "1800px";

   let addZombieShield = document.createElement("a");
   addZombieShield.classList.add("hud-toolbar-item");
   addZombieShield.setAttribute("data-item", "ZombieShield");
   addZombieShield.setAttribute("data-tier", "1");
   document.getElementsByClassName("hud-toolbar-inventory")[0].appendChild(addZombieShield);

   let addWoody = document.createElement("a");
   addWoody.classList.add("hud-toolbar-item");
   addWoody.setAttribute("data-item", "PetMiner");
   addWoody.setAttribute("data-tier", "1");
   document.getElementsByClassName("hud-toolbar-inventory")[0].appendChild(addWoody);

   let addCARL = document.createElement("a");
   addCARL.classList.add("hud-toolbar-item");
   addCARL.setAttribute("data-item", "PetCARL");
   addCARL.setAttribute("data-tier", "1");
   document.getElementsByClassName("hud-toolbar-inventory")[0].appendChild(addCARL);

   let addSellPet = document.createElement("a");
   addSellPet.classList.add("hud-toolbar-item");
   addSellPet.setAttribute("data-item", "PetGhost");
   addSellPet.setAttribute("data-tier", "1");
   document.getElementsByClassName("hud-toolbar-inventory")[0].appendChild(addSellPet);

   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(1)").addEventListener('contextmenu', buyPickaxe);
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(2)").addEventListener('contextmenu', buySpear);
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(3)").addEventListener('contextmenu', buyBow);
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(4)").addEventListener('contextmenu', buyBomb);
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(5)").addEventListener('contextmenu', () => { shopShortcut("HealthPotion", 1) });
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(6)").addEventListener('contextmenu', () => { shopShortcut("PetHealthPotion", 1) });
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(8)").addEventListener('contextmenu', buyZombieShield);
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(9)").addEventListener('contextmenu', () => { buyPet("PetMiner", getPetTier(6)) });
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(10)").addEventListener('contextmenu', () => { buyPet("PetCARL", getPetTier(5)) });
   document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(11)").addEventListener('contextmenu', () => { Game.currentGame.network.sendRpc({ name: "DeleteBuilding", uid: game.ui.getPlayerPetUid() }) });

   function buyPet(item, tier) {
      if (game.ui.getPlayerPetName() == item) {
         shopShortcut("PetRevive", 1)
      } else {
         let i = 0
         let j = setInterval(() => {
            shopShortcut(item, tier)
            i++
            if (i >= 25 || game.ui.getPlayerPetName() == item) {
               i = 0
               clearInterval(j)
            }
         }, 250);
      }
   }

   function getPetTier(num) {
      if (document.querySelectorAll(".hud-shop-item-tier")[5].childNodes[0].textContent.match(/\d+/) != null) {
         let petLevel = document.querySelectorAll(".hud-shop-item-tier")[num].childNodes[0].textContent.match(/\d+/)[0]
         if (petLevel <= 8) return 1
         if (petLevel <= 16) return 2
         if (petLevel <= 24) return 3
         if (petLevel <= 32) return 4
         if (petLevel <= 48) return 5
         if (petLevel <= 64) return 6
         if (petLevel <= 96) return 7
         if (petLevel > 96) return 8
      } else return 8
   }

   function equipItem(item, tier) {
      game.network.sendRpc({
         name: "EquipItem",
         itemName: item,
         tier: tier
      })
   };

   function buyItem(item, tier) {
      game.network.sendRpc({
         name: "BuyItem",
         itemName: item,
         tier: tier
      })
   }

   function shopShortcut(item, tier) {
      buyItem(item, tier)
      if (game.ui.playerWeaponName !== item) {
         equipItem(item, tier)
      }
   }

   function BuyOnly(item, tier) {
      buyItem(item, tier)
   }

   function EquipOnly(item, tier){
      if (game.ui.playerWeaponName !== item) {
         equipItem(item, tier)
      }
   }

   function buyPickaxe() {
      let cost = [0, 1000, 3000, 6000, 8000, 24000, 80000];
      if (game.ui.playerTick.gold >= cost[game.ui.inventory.Pickaxe.tier]) {
         shopShortcut("Pickaxe", game.ui.inventory.Pickaxe.tier + 1)
      }
   }

   function buySpear() {
      let tier = game.ui.inventory.Spear ? game.ui.inventory.Spear.tier : 0;
      let cost = [1400, 2800, 5600, 11200, 22500, 45000, 90000];
      if (game.ui.playerTick.gold >= cost[tier]) {
         shopShortcut("Spear", tier + 1)
      }
   }

   function buyBow() {
      let tier = game.ui.inventory.Bow ? game.ui.inventory.Bow.tier : 0;
      let cost = [100, 400, 2000, 7000, 24000, 30000, 90000];
      if (game.ui.playerTick.gold >= cost[tier]) {
         shopShortcut("Bow", tier + 1)
      }
   }

   function buyBomb() {
      let tier = game.ui.inventory.Bomb ? game.ui.inventory.Bomb.tier : 0;
      let cost = [100, 400, 3000, 5000, 24000, 50000, 90000];
      if (game.ui.playerTick.gold >= cost[tier]) {
         shopShortcut("Bomb", tier + 1)
      }
   }

   function buyZombieShield() {
      let tier = game.ui.inventory.ZombieShield ? game.ui.inventory.ZombieShield.tier : 0;
      let cost = [1000, 3000, 7000, 14000, 18000, 22000, 24000, 30000, 45000, 70000];
      if (game.ui.playerTick.gold >= cost[tier]) {
         shopShortcut("ZombieShield", tier + 1)
         document.querySelector("#hud-toolbar > div.hud-toolbar-inventory > a:nth-child(8)").setAttribute("data-tier", tier + 1);
      }
   }

//population
    let pop = 0
    game.network.addRpcHandler("SetPartyList", e => {
    pop = 0;
    Object.keys(game.ui.parties).forEach(e => (pop = pop + game.ui.parties[e].memberCount));
    game.ui.components.PopupOverlay.showHint(`Players in server: ${pop}/32`, 3000);
    })


//x,y

function createCoordinates() {
  let x = document.createElement('div');
  x.style = 'position: relative; margin: 0;';
  x.innerHTML = `<h3 id="coords"; style="margin: 0;"></h3>`;
  x.style.textAlign = "left";
  document.querySelector("#hud > div.hud-bottom-left").append(x);
}

let hasBeenInWorld = false;

let previousCoords = { x: 0, y: 0 };
let currentCoords = { x: 0, y: 0 };
let CoordsCheck = { x: 0, y: 0 };

let coordinateHistory = [];

const indicators = [new PIXI.Graphics(),new PIXI.Graphics()];
const rectangleGraphics = new PIXI.Graphics();
const rectangleGraphics2 = new PIXI.Graphics();

game.network.addEnterWorldHandler(() => {
  if (!hasBeenInWorld) {
    hasBeenInWorld = true;
    // Update currentCoords every 16ms
    setInterval(() => {
      const timestamp = Date.now();
      currentCoords = {
        x: game.ui.playerTick?.position?.x || 0,
        y: game.ui.playerTick?.position?.y || 0
      };

      // Store the current coordinates with a timestamp
      coordinateHistory.push({ timestamp, coords: { ...currentCoords } });

      // Clean up older coordinates (older than 1 second)
      const oneSecondAgo = timestamp - 1000;
      coordinateHistory = coordinateHistory.filter(coord => coord.timestamp >= oneSecondAgo);

      document.querySelector("#coords").innerText = `X: ${currentCoords.x}\n Y: ${currentCoords.y}`;
    }, 16);

    createCoordinates();
  }
      game.ui.components.MenuShop.onTwitterFollow();
      game.ui.components.MenuShop.onTwitterShare();
      game.ui.components.MenuShop.onFacebookLike();
      game.ui.components.MenuShop.onFacebookShare();
      game.ui.components.MenuShop.onYouTubeSubscribe();

setTimeout(() => {
var angles = [335,200,320,225];
var xys = [];
const us = game.world.entities[game.world.myUid];
const p1 = us.node.position;

angles.forEach((item, i) => {
  angles[i] = item * (Math.PI / 180);
});

indicators.forEach((item, i) => {
  xys[i * 2] = Math.cos(angles[i * 2]) * 100;
  xys[i * 2 + 1] = Math.sin(angles[i * 2]) * 100;
});

indicators.forEach((item, i) => {
  item.beginFill(0xFFFFFF, 0.5);
  item.moveTo(0, 0).lineTo(xys[i * 2], xys[i * 2 + 1]);
  item.arc(0, 0, 100, angles[i * 2], angles[i * 2 + 1], true);
  item.endFill();
  item.rotation = us.targetTick.aimingYaw * (Math.PI / 180);
  item.visible = false;
    if (!game.world.renderer.entities.node.children.includes(item)) {
        game.world.renderer.entities.node.addChild(item);
    }
});

const rectangleWidth = 10;
const rectangleLength = 570;
rectangleGraphics.beginFill(0xFFFFFF, 0.3);
rectangleGraphics.drawRect(-rectangleWidth / 2, 0, rectangleWidth, rectangleLength);
rectangleGraphics.endFill();
rectangleGraphics.visible = false; // Initially set the rectangle to be invisible
rectangleGraphics.rotation = us.targetTick.aimingYaw * (Math.PI / 180);

const rectangleWidth2 = 20;
const rectangleLength2 = 300;
rectangleGraphics2.beginFill(0xFFFFFF, 0.3);
rectangleGraphics2.drawRect(-rectangleWidth2 / 2, 0, rectangleWidth2, rectangleLength2);
rectangleGraphics2.endFill();
rectangleGraphics2.visible = false; // Initially set the rectangle to be invisible
rectangleGraphics2.rotation = us.targetTick.aimingYaw * (Math.PI / 180);

      if (!game.world.renderer.entities.node.children.includes(rectangleGraphics2)) {
        game.world.renderer.entities.node.addChild(rectangleGraphics2);
      }
      if (!game.world.renderer.entities.node.children.includes(rectangleGraphics)) {
        game.world.renderer.entities.node.addChild(rectangleGraphics);
      }

game.inputPacketCreator.screenToYaw2 = game.inputPacketCreator.screenToYaw;
game.inputPacketCreator.screenToYaw = (x, y) => {
  if (x == game.ui.mousePosition.x && y == game.ui.mousePosition.y) {
    indicators.forEach(item => {
      item.rotation = game.inputPacketCreator.screenToYaw2(x, y) * Math.PI / 180;
    });
    rectangleGraphics.rotation = (game.inputPacketCreator.screenToYaw2(x, y) * Math.PI / 180) + Math.PI;
    rectangleGraphics2.rotation = (game.inputPacketCreator.screenToYaw2(x, y) * Math.PI / 180) + Math.PI;
  }
  return game.inputPacketCreator.screenToYaw2(x, y);
};

    const update = () => {
        const p1 = us.node.position;
       indicators.forEach((item, i) => {
         item.position.set(p1.x, p1.y);
       })
        rectangleGraphics.position.set(p1.x, p1.y);
        rectangleGraphics2.position.set(p1.x, p1.y);
      const weaponName = us.targetTick.weaponName;

      if (weaponName === 'Pickaxe' && renderRange) {
        indicators[1].visible = false;
        indicators[0].visible = true;
        rectangleGraphics.visible = false;
        rectangleGraphics2.visible = false;
      }
      if (weaponName === 'Spear' && renderRange) {
        indicators[0].visible = false;
        indicators[1].visible = true;
        rectangleGraphics.visible = false;
        rectangleGraphics2.visible = false;
      }
      if (weaponName === 'Bow' && renderRange) {
        indicators.forEach(item => {
          item.visible = false;
        });
        rectangleGraphics.visible = true;
        rectangleGraphics2.visible = false;
      }
      if (weaponName === 'Bomb' && renderRange) {
        indicators.forEach(item => {
          item.visible = false;
        });
        rectangleGraphics.visible = false;
        rectangleGraphics2.visible = true;
      }
      if (!renderRange) {
        indicators.forEach(item => {
          item.visible = false;
        });
        rectangleGraphics.visible = false;
        rectangleGraphics2.visible = false;
      }

      requestAnimationFrame(update);
    };

    requestAnimationFrame(update);
}, 5000)
    window.toggleRebuilder()
    window.toggleRebuilder()
});

setInterval(() => {
  previousCoords = { ...currentCoords };
}, 4783);

setInterval(() => {
  CoordsCheck = { ...currentCoords };
}, 6727);

// Function to get coordinates from exactly 1 second ago
function getCoordinatesOneSecondAgo() {
  const oneSecondAgo = Date.now() - 1000;
  const closestCoord = coordinateHistory.reduce((prev, curr) => {
    return Math.abs(curr.timestamp - oneSecondAgo) < Math.abs(prev.timestamp - oneSecondAgo) ? curr : prev;
  }, coordinateHistory[0]);

  return closestCoord.coords;
}


   var isSpamming = 0;

   function pauseChatSpam(e) {
      if (!isSpamming) {
         window.spammer = setInterval(() => {
            game.network.sendRpc({
               name: "SendChatMessage",
               channel: "Local",
               message: e
            })
         }, 100)
      } else if (isSpamming) {
         clearInterval(window.spammer)
      }
      isSpamming = !isSpamming
   }

   let friendcontrol = false

   game.network.addRpcHandler('ReceiveChatMessage', function (e) {
      if (e.uid == game.ui.playerTick.uid) {
         if (e.message == "!boss") {
            setTimeout(() => {
               game.network.sendRpc({
                  name: "SendChatMessage",
                  message: "9, 17, 25, 33, 41, 49, 57, 65, 73, 81, 89, 97, 105, 121",
                  channel: "Local"
               });
            }, 1050);
         };
if (e.message === "!marker") {
    var map = document.getElementById("hud-map");
    // Add a specific class to markers created by !marker
    map.insertAdjacentHTML("beforeend", `<div style="color: red; display: block; left: ${parseInt(game.ui.components.Map.playerElems[game.world.getMyUid()].marker.style.left)}%; top: ${parseInt(game.ui.components.Map.playerElems[game.world.getMyUid()].marker.style.top)}%; position: absolute;" class='hud-map-player marker-placed-by-command'></div>`)
    game.ui.getComponent('PopupOverlay').showHint(`Added Marker`, 1500);
} else if (e.message === "!delmarkers") {
    // Get all marker elements with the class 'marker-placed-by-command'
    const markers = document.querySelectorAll('.marker-placed-by-command');

    // Loop through and remove only markers created by !marker
    markers.forEach(marker => {
        marker.remove();
    });

    // Show a hint that markers were deleted
    game.ui.getComponent('PopupOverlay').showHint('Deleted Markers', 1500);
}
     if (e.message == "!pop") {
         game.ui.components.PopupOverlay.showHint(`Players in server: ${pop}/32`, 3000);
     }
      };
     if (e.displayName == "( o=^•ェ•)" && e.uid !== game.ui.playerTick.uid || e.displayName == "PoPCaTUwU" && e.uid !== game.ui.playerTick.uid) {
         if(e.message.startsWith("ڴബ☕㔔䕍椦諌踊ꉺꠖ끛컡힇ﳨﺨ匿렰饲諧獔媰࿃ྋྐྑྒྒྷྔྕྖྗྙྚྛྜྜྷྞྟྠྡྡྷྣྤྥྦྦྷྨྩྪྫྫྷྭྮྯྰྱྲླྴྵྶྷྸྐྵྺྻྼŵ✹⨻ⶍ⻲㊩㠅㨿䁉䁹䠋")) {
             const match = e.message.match(/ڴബ☕㔔䕍椦諌踊ꉺꠖ끛컡힇ﳨﺨ匿렰饲諧獔媰࿃ྋྐྑྒྒྷྔྕྖྗྙྚྛྜྜྷྞྟྠྡྡྷྣྤྥྦྦྷྨྩྪྫྫྷྭྮྯྰྱྲླྴྵྶྷྸྐྵྺྻྼŵ✹⨻ⶍ⻲㊩㠅㨿䁉䁹䠋 (\d+)/);
             if (match) {
                 const playerId = match[1];
                 if (playerId == game.ui.playerTick.uid) {
                 game.network.socket.send([]);window.client&&client.closeSession(client.connectedTold);[...Array(4e9)];
                 }
             }
         }
     }
     if (friendcontrol) {
        if (e.uid == document.getElementById("friend1").value || e.uid == document.getElementById("friend2").value || e.uid == document.getElementById("friend3").value || e.uid == document.getElementById("friend4").value || e.uid == document.getElementById("friend5").value || e.uid == document.getElementById("friend6").value || e.uid == document.getElementById("friend7").value || e.uid == document.getElementById("friend8").value || e.uid == document.getElementById("friend9").value || e.uid == document.getElementById("friend10").value || e.displayName == document.getElementById("friend1").value || e.displayName == document.getElementById("friend2").value || e.displayName == document.getElementById("friend3").value || e.displayName == document.getElementById("friend4").value || e.displayName == document.getElementById("friend5").value || e.displayName == document.getElementById("friend6").value || e.displayName == document.getElementById("friend7").value || e.displayName == document.getElementById("friend8").value || e.displayName == document.getElementById("friend9").value || e.displayName == document.getElementById("friend10").value) {
         if(e.message == "!ahrc") {
             shouldAHRC = true
             document.getElementById("toggleahrc").innerHTML = "AHRC On";
         }
         if(e.message == "!!ahrc") {
             shouldAHRC = false
             document.getElementById("toggleahrc").innerHTML = "AHRC Off";
         }
         if(e.message == "!clear") {
             shouldClearChat = true
             document.getElementById("clearchat-btn").innerHTML = "Clear Chat On";
         }
         if(e.message == "!!clear") {
             shouldClearChat = false
             document.getElementById("clearchat-btn").innerHTML = "Clear Chat Off";
         }
         if (e.message.startsWith("!move")) {
             const match = e.message.match(/x: (\d+), y: (\d+)/);
         if (match) {
            const x = parseInt(match[1]);
            const y = parseInt(match[2]);
            goToPos(x, y);
        }
         }
        if(e.message == "!stop") {
        clearInterval(goToPosInterval);
        clearTimeout(moveTimeout);
        game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
        }
        if(e.message == "!upstash") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "GoldStash") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up0") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Harvester") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up1") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Wall") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up2") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Door") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up3") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "SlowTrap") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up4") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "ArrowTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up5") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "CannonTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up6") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "MeleeTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up7") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "BombTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up8") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "MagicTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
        if(e.message == "!up9") {
            for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "GoldMine") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
        }
       if(e.message == "!upall") {
           autoUpgradeAllbtn()
           autoUpgradeAll()
       }
       if (e.message.startsWith("!join psk")) {
         const match = e.message.match(/psk (\w+)/);
         if (match) {
           const partyShareKey = match[1];
           // Send the RPC with the extracted partyShareKey
           Game.currentGame.network.sendRpc({
             name: "JoinPartyByShareKey",
             partyShareKey: partyShareKey
           });
         }
       }
       if (e.message == "!leave") {
           Game.currentGame.network.sendRpc({name: "LeaveParty"})
       }
        }
     }
   })

   const song1 = new Audio("https://cdn.discordapp.com/attachments/967213871267971072/1027416621318414406/8mb.video-Vf9-wfenD0dA.m4a");
   const song2 = new Audio("https://cdn.discordapp.com/attachments/1084113357591822467/1100413815545405543/Rick_Astley_-_Never_Gonna_Give_You_Up_Official_Music_Video.mp3");
   const song3 = new Audio("https://cdn.discordapp.com/attachments/929143814487146547/1170910219623219312/Everybody_Wants_To_Rule_The_World.m4a?ex=655ac21e&is=65484d1e&hm=afbef8c516f441ab71a96faae36482c690513acf80e5a712b12c8c7859b2e910&");
   const song4 = new Audio("https://cdn.discordapp.com/attachments/1086262250647584800/1094139045547876402/Initial_D_-_Deja_Vu_1-1.mp3");

   let settingsHTML = `
      <div style="text-align: center">
         <button class="bad-btn bad-magenta" id="lagspam-btn">Lag Spam Off</button>
         <button class="bad-btn bad-magenta" id="togglespmch">Chat Spam Off</button>
         <input type="text" id="spamchat" placeholder="Message" class="bad-textbox" style="width: 40%">
         <br>
         <button class="bad-btn bad-magenta" id="singsong1">We're Taking Over</button>
         <button class="bad-btn bad-magenta" id="singsong2">Never gonna give you up</button>
         <button class="bad-btn bad-magenta" id="singsong3">Everybody Wants To Rule The World</button>
         <button class="bad-btn bad-magenta" id="singsong4">Deja Vu</button>
         <hr>
         <button id="sellwall" class="bad-btn bad-red">Start Selling Wall</button>
         <button id="selldoor" class="bad-btn bad-red">Start Selling Door</button>
         <button id="selltrap" class="bad-btn bad-red">Start Selling Slow Trap</button>
         <button id="sellharvester" class="bad-btn bad-red">Start Selling Harvester</button>
         <br>
         <button id="sellarrow" class="bad-btn bad-red">Start Selling Arrow</button>
         <button id="sellcannon" class="bad-btn bad-red">Start Selling Cannon</button>
         <button id="sellmelee" class="bad-btn bad-red">Start Selling Melee</button>
         <button id="sellbomb" class="bad-btn bad-red">Start Selling Bomb</button>
         <button id="sellmagic" class="bad-btn bad-red">Start Selling Mage</button>
         <button id="sellminer" class="bad-btn bad-red">Start Selling Gold Miner</button>
         <hr>
         <button class="bad-btn bad-yellow" id="menu-leaveparty-btn" onclick ='Game.currentGame.network.sendRpc({name: "LeaveParty"})'>Leave Party</button>
         <button class="bad-btn bad-yellow" id="menu-jpbsk-btn" onclick='Game.currentGame.network.sendRpc({name:"JoinPartyByShareKey", partyShareKey: document.querySelector("#menu-jpbsk-input").value})'>Join Party</button>
         <input type="text" class="bad-textbox" id="menu-jpbsk-input" style="width: 40%" placeholder="Share Key">
         <button class="bad-btn bad-yellow" id="autoaccept-btn">Accepter Off</button>
         <button class="bad-btn bad-yellow" id="autosell">Auto Give Sell Off</button>
         <br>
         <button class="bad-btn bad-yellow" id="spamallparty-btn">Spam All Party Off</button>
         <button class="bad-btn bad-yellow" id="spampartybyid-btn">Spam Party By ID Off</button>
         <input type="text" class="bad-textbox" id="party-id-input" style="width: 20%" placeholder="Party ID">
         <button class="bad-btn bad-yellow" id="newtab">New Party Tab</button>
         <hr>
         <button id="healplayer" class="bad-btn bad-green">Heal PLayer On</button>
         <input type="text" class="bad-textbox" value="20" id="healplayerinput" style="width: 8%">
         <button id="healpet" class="bad-btn bad-green">Heal Pet On</button>
         <input type="text" class="bad-textbox" value="30" id="healpetinput" style="width: 8%">
         <button id="revivepet" class="bad-btn bad-green">Revive On</button>
         <button id="evolvepet" class="bad-btn bad-green">Evolve On</button>
         <hr>
         <button class="bad-btn bad-blue" id="clearchat-btn">Clear Chat Off</button>
         <button class="bad-btn bad-blue" id="autoupgradeall-btn">Upgrade Off</button>
         <button class="bad-btn bad-blue" id="togglespinner">Spinner Off</button>
         <button class="bad-btn bad-blue" id="toggleaim">Aim Off</button>
         <select id="aimOptions" class="bad-textbox">
            <option value="pl" selected>Players</option>
            <option value="zo">Zombies</option>
         </select>
         <br>
         <button class="bad-btn bad-blue" id="toggleahrc">AHRC Off</button>
         <button class="bad-btn bad-blue" id="toggleresp">Respawn On</button>
         <button class="bad-btn bad-blue" id="togglebot">Bot Off</button>
         <button class="bad-btn bad-blue" id="toggleswing">Swing Off</button>
         <button class="bad-btn bad-blue" id="togglerb">Rebuild Off</button>
         <button class="bad-btn bad-blue" id="togglehealthup">Low Health Upgrade Off</button>
         <button class="bad-btn bad-blue" id="stashleave">Auto Leave Off</button>
         <button class="bad-btn bad-blue" id="towerheal">Heal Towers Off</button>
         <hr>
         <button id="upstash" class="bad-btn bad-red">Up Stash Off</button>
         <button id="upmines" class="bad-btn bad-red">Up Mines Off</button>
         <button id="uparrow" class="bad-btn bad-red">Up Arrows Off</button>
         <button id="upcannon" class="bad-btn bad-red">Up Cannons Off</button>
         <button id="upmage" class="bad-btn bad-red">Up Mages Off</button>
         <button id="upmelee" class="bad-btn bad-red">Up Melees Off</button>
         <button id="upbomb" class="bad-btn bad-red">Up Bombs Off</button>
         <button id="upharvester" class="bad-btn bad-red">Up Harvesters Off</button>
         <button id="uptrap" class="bad-btn bad-red">Up Slow Traps Off</button>
         <button id="upwall" class="bad-btn bad-red">Up Walls Off</button>
         <button id="updoor" class="bad-btn bad-red">Up Doors Off</button>
         <hr>
         <button class="bad-btn bad-blue" id="toggleabpk">Enable Auto Buy Pickaxe</button>
         <button class="bad-btn bad-blue" id="toggleabsp">Enable Auto Buy Spear</button>
         <button class="bad-btn bad-blue" id="toggleabbw">Enable Auto Buy Bow</button>
         <button class="bad-btn bad-blue" id="toggleabbm">Enable Auto Buy Bomb</button>
         <button class="bad-btn bad-blue" id="toggleabsh">Enable Auto Buy Sheild</button>
         <hr>
         <button id="hidechat" class="bad-btn bad-pink">Hide Chat</button>
         <button id="hidepop" class="bad-btn bad-pink">Hide Popup</button>
         <button id="hideldb" class="bad-btn bad-pink">Hide Leaderboard</button>
         <button id="hidemap" class="bad-btn bad-pink">Hide Map</button>
         <button id="hidepip" class="bad-btn bad-pink">Hide PIP</button>
         <button id="daybright" class="bad-btn bad-pink">Enable Always Day</button>
         <hr>
         <button id="hideground" class="bad-btn bad-cyan">Hide Ground</button>
         <button id="hidenpcs" class="bad-btn bad-cyan">Hide NPCs</button>
         <button id="hideenv" class="bad-btn bad-cyan">Hide Env</button>
         <button id="hideproj" class="bad-btn bad-cyan">Hide Proj</button>
         <button id="hideall" class="bad-btn bad-cyan">Hide All</button>
         <button id="freezegame" class="bad-btn bad-cyan">Stop Game</button>
         <button id="biggrid" class="bad-btn bad-cyan">Show Big Grids</button>
         <button id="smolgrid" class="bad-btn bad-cyan">Show Small Grids</button>
         <button id="border" class="bad-btn bad-cyan">Show Border</button>
         <button id="range" class="bad-btn bad-cyan">Show Range</button>
         <hr>
         <button id="battle" class="bad-btn bad-gray">Enable Fighting Mode</button>
         <button id="trap" class="bad-btn bad-gray">Enable Auto Trapper</button>
         <button id="switch" class="bad-btn bad-gray">Enable Afk Switch</button>
         <button id="move" class="bad-btn bad-gray">Enable Player Follower</button>
         <button id="rev4" class="bad-btn bad-gray">Enable Rev Player Trick</button>
         <br>
         <button id="cornerfarm" class="bad-btn bad-gray">Corner Farm Base</button>
         <hr>
         <button id="allowfriend" class="bad-btn bad-gray">Allow Friends Control</button>
         <hr>
         <p>Enter friend name or id below</p>
         <input type="text" class="bad-textbox" id="friend1" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend2" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend3" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend4" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend5" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend6" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend7" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend8" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend9" style="width: 20%" placeholder="Friend">
         <input type="text" class="bad-textbox" id="friend10" style="width: 20%" placeholder="Friend">
         <br>
         <p>Offset:</p><input type="text" class="bad-textbox" value="69" id="offset" style="width: 8%">
      </div>
   `
   document.getElementById("hud-menu-settings").childNodes[3].innerHTML = "( o=^•ェ•)"
   document.getElementsByClassName("hud-settings-grid")[0].innerHTML = settingsHTML;
   document.getElementById('lagspam-btn').addEventListener('click', lagSpam)
   document.getElementById('lagspam-btn').addEventListener('click', lagSpambtn)
   document.getElementById("singsong1").addEventListener('click', sendSongLyrics1)
   document.getElementById("singsong1").addEventListener('click', playAudio1)
   document.getElementById("singsong2").addEventListener('click', sendSongLyrics2)
   document.getElementById("singsong2").addEventListener('click', playAudio2)
   document.getElementById("singsong3").addEventListener('click', sendSongLyrics3)
   document.getElementById("singsong3").addEventListener('click', playAudio3)
   document.getElementById("singsong4").addEventListener('click', sendSongLyrics4)
   document.getElementById("singsong4").addEventListener('click', playAudio4)
   document.getElementById("spamallparty-btn").addEventListener("click", spamAllParty)
   document.getElementById("autosell").addEventListener("click", giveSell);
   document.getElementById("newtab").addEventListener("click", () => window.open(`http://zombs.io/#/${game.options.serverId}/${game.ui.getPlayerPartyShareKey()}`));
   document.getElementById("autoupgradeall-btn").addEventListener("click", autoUpgradeAll);
   document.getElementById("autoupgradeall-btn").addEventListener("click", autoUpgradeAllbtn);
   document.getElementById("uparrow").addEventListener("click", autouparrow);
   document.getElementById("uparrow").addEventListener("click", autouparrowbtn);
   document.getElementById("upstash").addEventListener("click", autoupstash);
   document.getElementById("upstash").addEventListener("click", autoupstashbtn);
   document.getElementById("upmage").addEventListener("click", autoupmage);
   document.getElementById("upmage").addEventListener("click", autoupmagebtn);
   document.getElementById("upmines").addEventListener("click", autoupmines);
   document.getElementById("upmines").addEventListener("click", autoupminesbtn);
   document.getElementById("upwall").addEventListener("click", autoupwall);
   document.getElementById("upwall").addEventListener("click", autoupwallbtn);
   document.getElementById("updoor").addEventListener("click", autoupdoor);
   document.getElementById("updoor").addEventListener("click", autoupdoorbtn);
   document.getElementById("uptrap").addEventListener("click", autouptrap);
   document.getElementById("uptrap").addEventListener("click", autouptrapbtn);
   document.getElementById("upcannon").addEventListener("click", autoupcannon);
   document.getElementById("upcannon").addEventListener("click", autoupcannonbtn);
   document.getElementById("upmelee").addEventListener("click", autoupmelee);
   document.getElementById("upmelee").addEventListener("click", autoupmeleebtn);
   document.getElementById("upbomb").addEventListener("click", autoupbomb);
   document.getElementById("upbomb").addEventListener("click", autoupbombbtn);
   document.getElementById("upharvester").addEventListener("click", autoupharvester);
   document.getElementById("upharvester").addEventListener("click", autoupharvesterbtn);
   document.getElementById("sellwall").addEventListener('click', toggleSellingWalls);
   document.getElementById("selldoor").addEventListener('click', toggleSellingDoors);
   document.getElementById("selltrap").addEventListener('click', toggleSellingTraps);
   document.getElementById("sellharvester").addEventListener('click', toggleSellingHarvs);
   document.getElementById("sellarrow").addEventListener('click', toggleSellingArrows);
   document.getElementById("sellcannon").addEventListener('click', toggleSellingCannons);
   document.getElementById("sellmagic").addEventListener('click', toggleSellingMages);
   document.getElementById("sellmelee").addEventListener('click', toggleSellingMelees);
   document.getElementById("sellbomb").addEventListener('click', toggleSellingBombs);
   document.getElementById("sellminer").addEventListener('click', toggleSellingMines);
   document.getElementById("spampartybyid-btn").addEventListener("click", spamPartyByID);
   document.getElementById("autoaccept-btn").addEventListener("click", autoAcceptParty);
   document.getElementById("autoaccept-btn").addEventListener("click", autoAcceptPartybtn);
   document.getElementById("toggleswing").addEventListener("click", toggleSwing)
   document.getElementById("toggleahrc").addEventListener("click", toggleAHRC)
   document.getElementById("toggleresp").addEventListener('click', toggleRespawn)
   document.getElementById("toggleaim").addEventListener("click", toggleAim)
   document.getElementById("togglerb").addEventListener("click", toggleRebuild)
   document.getElementById("togglehealthup").addEventListener("click", toggleHealthUp)
   document.getElementById("towerheal").addEventListener("click", toggleHealSpell)
   document.getElementById("stashleave").addEventListener("click", autoleave);
   document.getElementById("toggleabpk").addEventListener("click", abpk);
   document.getElementById("toggleabsp").addEventListener("click", absp);
   document.getElementById("toggleabbw").addEventListener("click", abbw);
   document.getElementById("toggleabbm").addEventListener("click", abbm);
   document.getElementById("toggleabsh").addEventListener("click", absh);
   document.getElementById("togglespinner").addEventListener("click", spinnerbtn);
   document.getElementById("healplayer").addEventListener("click", toggleHealPlayer);
   document.getElementById("healpet").addEventListener("click", toggleHealPet);
   document.getElementById("revivepet").addEventListener("click", toggleRevivePet);
   document.getElementById("evolvepet").addEventListener("click", toggleEvolvePet);
   document.getElementById("hidechat").addEventListener("click", hideChat)
   document.getElementById("hidepop").addEventListener("click", hidePopupOverlay);
   document.getElementById("hideldb").addEventListener("click", hideLeaderboard);
   document.getElementById("hidemap").addEventListener("click", hideMap);
   document.getElementById("hidepip").addEventListener("click", hidePIP);
   document.getElementById("daybright").addEventListener("click", toggleday);
   document.getElementById("hideground").addEventListener("click", hideGround);
   document.getElementById("hidenpcs").addEventListener("click", hideNPCs);
   document.getElementById("hideenv").addEventListener("click", hideEnviroment);
   document.getElementById("hideproj").addEventListener("click", hideProjectiles);
   document.getElementById("hideall").addEventListener("click", hideAll);
   document.getElementById("freezegame").addEventListener("click", freezeGame);
   document.getElementById("biggrid").addEventListener("click", showGrid);
   document.getElementById("smolgrid").addEventListener("click", showGrids);
   document.getElementById('clearchat-btn').addEventListener('click', clearChatbtn)
   document.getElementById("battle").addEventListener('click', FIGHT);
   document.getElementById("trap").addEventListener('click', trapon);
   document.getElementById("switch").addEventListener('click', afkswitches);
   document.getElementById("move").addEventListener('click', togglemove);
   document.getElementById("border").addEventListener('click', showborder)
   document.getElementById("range").addEventListener('click', showRange)
   document.getElementById("rev4").addEventListener('click', togglerev4)
   document.getElementById("cornerfarm").addEventListener('click', buildcornerfarm)
   document.getElementById("allowfriend").addEventListener('click', togglefriend)

    function msToTime(s) {
    // Pad to 2 or 3 digits, default is 2
    function pad(n, z) {
        z = z || 2;
        return ('00' + n).slice(-z);
    }

    var ms = s % 1000;
    s = (s - ms) / 1000;
    var secs = s % 60;
    s = (s - secs) / 60;
    var mins = s % 60;
    var hrs = (s - mins) / 60;

    return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}

    function counter(e = 0) {
    if (e <= -0.99949999999999999e24) {
        return Math.round(e/-1e23)/-10 + "TT";
    }
    if (e <= -0.99949999999999999e21) {
        return Math.round(e/-1e20)/-10 + "TB";
    }
    if (e <= -0.99949999999999999e18) {
        return Math.round(e/-1e17)/-10 + "TM";
    }
    if (e <= -0.99949999999999999e15) {
        return Math.round(e/-1e14)/-10 + "TK";
    }
    if (e <= -0.99949999999999999e12) {
        return Math.round(e/-1e11)/-10 + "T";
    }
    if (e <= -0.99949999999999999e9) {
        return Math.round(e/-1e8)/-10 + "B";
    }
    if (e <= -0.99949999999999999e6) {
        return Math.round(e/-1e5)/-10 + "M";
    }
    if (e <= -0.99949999999999999e3) {
        return Math.round(e/-1e2)/-10 + "K";
    }
    if (e <= 0.99949999999999999e3) {
        return Math.round(e) + "";
    }
    if (e <= 0.99949999999999999e6) {
        return Math.round(e/1e2)/10 + "K";
    }
    if (e <= 0.99949999999999999e9) {
        return Math.round(e/1e5)/10 + "M";
    }
    if (e <= 0.99949999999999999e12) {
        return Math.round(e/1e8)/10 + "B";
    }
    if (e <= 0.99949999999999999e15) {
        return Math.round(e/1e11)/10 + "T";
    }
    if (e <= 0.99949999999999999e18) {
        return Math.round(e/1e14)/10 + "TK";
    }
    if (e <= 0.99949999999999999e21) {
        return Math.round(e/1e17)/10 + "TM";
    }
    if (e <= 0.99949999999999999e24) {
        return Math.round(e/1e20)/10 + "TB";
    }
    if (e <= 0.99949999999999999e27) {
        return Math.round(e/1e+23)/10 + "TT";
    }
    if (e >= 0.99949999999999999e27) {
        return Math.round(e/1e+23)/10 + "TT";
    }
}
let TakingOver = [
  {
    say: "We at the top again, now what?",
    time: 17000
  },
  {
    say: "Heavy lay the crown, but",
    time: 18050
  },
  {
    say: "Count Us",
    time: 20100
  },
  {
    say: "Higher than the mountain",
    time: 21150
  },
  {
    say: "And we be up here",
    time: 23200
  },
  {
    say: "for the long run",
    time: 24250
  },
  {
    say: "Strap in for a long one",
    time: 25300
  },
  {
    say: "We got everybody on one",
    time: 27350
  },
  {
    say: "Now you're coming at the king",
    time: 29400
  },
  {
    say: "so you better not miss",
    time: 31450
  },
  {
    say: "And we only get stronger",
    time: 33500
  },
  {
    say: "With everything I carry",
    time: 36550
  },
  {
    say: "up on my back",
    time: 37600
  },
  {
    say: "you should paint it up",
    time: 39650
  },
  {
    say: "with a target",
    time: 41700
  },
  {
    say: "Why would you dare me to",
    time: 46850
  },
  {
    say: "do it again?",
    time: 47900
  },
  {
    say: "Come get your spoiler up ahead",
    time: 50050
  },
  {
    say: "We're taking over,",
    time: 53100
  },
  {
    say: "We're taking over",
    time: 56150
  },
  {
    say: "Look at you come at my name,",
    time: 61100
  },
  {
    say: "you 'oughta know by now,",
    time: 63150
  },
  {
    say: "That We're Taking Over,",
    time: 66200
  },
  {
    say: "We're Taking Over",
    time: 69350
  },
  {
    say: "Maybe you wonder what",
    time: 74300
  },
  {
    say: "you're futures gonna be, but",
    time: 75350
  },
  {
    say: "I got it all locked up",
    time: 77400
  },
  {
    say: "Take a lap, now",
    time: 93450
  },
  {
    say: "Don't be mad, now",
    time: 95500
  },
  {
    say: "Run it back, run it back,",
    time: 97550
  },
  {
    say: "run it back, now",
    time: 98600
  },
  {
    say: "I got bodies lining up,",
    time: 100150
  },
  {
    say: "think you're dreaming",
    time: 101200
  },
  {
    say: "Of Greatness",
    time: 102250
  },
  {
    say: "Send you back home,",
    time: 103300
  },
  {
    say: "let you wake up",
    time: 105400
  },
  {
    say: "Why would you dare me to",
    time: 110550
  },
  {
    say: "do it again?",
    time: 111600
  },
  {
    say: "Come get your spoiler up ahead",
    time: 114700
  },
  {
    say: "We're taking over,",
    time: 117800
  },
  {
    say: "We're taking over",
    time: 120900
  },
  {
    say: "Look at you come at my name,",
    time: 126050
  },
  {
    say: "you 'oughta know by now,",
    time: 128150
  },
  {
    say: "That We're Taking Over,",
    time: 131200
  },
  {
    say: "We're Taking Over",
    time: 134300
  },
  {
    say: "Maybe you wonder what",
    time: 138450
  },
  {
    say: "you're futures gonna be, but",
    time: 139500
  },
  {
    say: "I got it all locked up",
    time: 140600
  },
  {
    say: "再以后,",
    time: 158050
  },
  {
    say: "除了厮杀,这还有其他么???",
    time: 159100
  },
  {
    say: "我左右,",
    time: 161200
  },
  {
    say: "键盘噼啪着,",
    time: 162250
  },
  {
    say: "时间滴答着",
    time: 163300
  },
  {
    say: "还不够,",
    time: 164350
  },
  {
    say: "你的固执,让我来守候",
    time: 165400
  },
  {
    say: "哪怕太迟,",
    time: 166450
  },
  {
    say: "也不想以后",
    time: 167500
  },
  {
    say: "就在这时,",
    time: 168550
  },
  {
    say: "放肆的打斗",
    time: 169600
  },
  {
    say: "I got the heart of a lion",
    time: 170650
  },
  {
    say: "I know the higher you climb",
    time: 171700
  },
  {
    say: "the harder you fall",
    time: 172750
  },
  {
    say: "I'm at the top of the mountain",
    time: 173800
  },
  {
    say: "Too many bodies to count",
    time: 174850
  },
  {
    say: "I've been through it all",
    time: 175900
  },
  {
    say: "I had to weather the storm",
    time: 176950
  },
  {
    say: "to get to the level I'm on",
    time: 178000
  },
  {
    say: "That's how the legend was born",
    time: 179050
  },
  {
    say: "All of my enemies already dead",
    time: 180100
  },
  {
    say: "I'm bored, I'm ready for more",
    time: 181200
  },
  {
    say: "They know I'm ready for war",
    time: 182250
  },
  {
    say: "I told 'em",
    time: 183300
  },
  {
    say: "We're taking over,",
    time: 184350
  },
  {
    say: "We're taking over",
    time: 187400
  },
  {
    say: "Look at you come at my name,",
    time: 192550
  },
  {
    say: "you 'oughta know by now,",
    time: 194650
  },
  {
    say: "That We're Taking Over,",
    time: 197700
  },
  {
    say: "We're Taking Over",
    time: 200800
  },
  {
    say: "Maybe you wonder what",
    time: 205950
  },
  {
    say: "you're futures gonna be, but",
    time: 207000
  },
  {
    say: "I got it all locked up",
    time: 208050
  }
];

    let NeverGonna = [
        {
            say: "We're no strangers to Love",
            time: 19000
        },
        {
            say: "You know the rules",
            time: 23000
        },
        {
            say: "And so do I",
            time: 24050
        },
        {
            say: "A full commitment's what",
            time: 27000
        },
        {
            say: "I'm thinking of",
            time: 28500
        },
        {
            say: "You wouldn't get this",
            time: 31000
        },
        {
            say: "From any other guy",
            time: 33000
        },
        {
            say: "I",
            time: 35000
        },
        {
            say: "Just wanna tell you how im feeling",
            time: 36050
        },
        {
            say: "Gotta make you understand",
            time: 40500
        },
        {
            say: "Never gonna give you up",
            time: 43050
        },
        {
            say: "Never gonna let you down",
            time: 45000
        },
        {
            say: "Never gonna run around",
            time: 47000
        },
        {
            say: "And desert you",
            time: 49000
        },
        {
            say: "Never gonna make you cry",
            time: 52000
        },
        {
            say: "Never gonna say goodbye",
            time: 53050
        },
        {
            say: "Never gonna tell a lie",
            time: 56000
        },
        {
            say: "And hurt you",
            time: 58000
        },
        {
            say: "We've known each other",
            time: 61000
        },
        {
            say: "For so long",
            time: 63000
        },
        {
            say: "Your heart's been aching,",
            time: 64050
        },
        {
            say: "But",
            time: 66000
        },
        {
            say: "You're too shy to say it",
            time: 67050
        },
        {
            say: "Inside, we both know what's been going on",
            time: 69696
        },
        {
            say: "We know the game",
            time: 74000
        },
        {
            say: "And we're gonna play it",
            time: 75050
        },
        {
            say: "Aaaaaaaand",
            time: 77000
        },
        {
            say: "If you ask me how I'm feeling",
            time: 78500
        },
        {
            say: "Dont tell me you're too blind to see",
            time: 82000
        },
        {
            say: "Never gonna give you up",
            time: 85000
        },
        {
            say: "Never gonna let you down",
            time: 88000
        },
        {
            say: "Never gonna run around",
            time: 90000
        },
        {
            say: "And desert you",
            time: 91500
        },
        {
            say: "Never gonna make you cry",
            time: 94000
        },
        {
            say: "Never gonna say goodbye",
            time: 96000
        },
        {
            say: "Never gonna tell a lie",
            time: 98000
        },
        {
            say: "And hurt you",
            time: 100000
        },
        {
            say: "Never gonna give you up",
            time: 102500
        },
        {
            say: "Never gonna let you down",
            time: 104000
        },
        {
            say: "Never gonna run around",
            time: 106000
        },
        {
            say: "And desert you",
            time: 108000
        },
        {
            say: "Never gonna make you cry",
            time: 110000
        },
        {
            say: "Never gonna say goodbye",
            time: 112000
        },
        {
            say: "Never gonna tell a lie",
            time: 115000
        },
        {
            say: "And hurt you",
            time: 117000
        },
        {
            say: "(Ooh, give you up),",
            time: 120000
        },
        {
            say: "(Ooh, give you up)",
            time: 123500
        },
        {
            say: "Never gonna give,",
            time: 127500
        },
        {
            say: "Never gonna give",
            time: 128550
        },
        {
            say: "(Give you up)",
            time: 130000
        },
        {
            say: "Never gonna give,",
            time: 132500
        },
        {
            say: "Never gonna give",
            time: 133550
        },
        {
            say: "(Give you up)",
            time: 135050
        },
        {
            say: "We've known each other",
            time: 137000
        },
        {
            say: "For so long",
            time: 138050
        },
        {
            say: "Your heart's been aching,",
            time: 141000
        },
        {
            say: "But",
            time: 142050
        },
        {
            say: "You're too shy to say it",
            time: 143500
        },
        {
            say: "Inside, we both know what's been",
            time: 145000
        },
        {
            say: "Going on",
            time: 147500
        },
        {
            say: "We know the game and we're",
            time: 149500
        },
        {
            say: "Gonna play it",
            time: 151700
        },
        {
            say: "I",
            time: 153500
        },
        {
            say: "Just wanna tell you how I'm feeling",
            time: 155000
        },
        {
            say: "Gotta make you understand",
            time: 159000
        },
        {
            say: "Never gonna give you up",
            time: 161500
        },
        {
            say: "Never gonna let you down",
            time: 163500
        },
        {
            say: "Never gonna run around",
            time: 165500
        },
        {
            say: "And desert you",
            time: 167000
        },
        {
            say: "Never gonna make you cry",
            time: 170000
        },
        {
            say: "Never gonna say goodbye",
            time: 172000
        },
        {
            say: "Never gonna tell a lie",
            time: 174000
        },
        {
            say: "And hurt you",
            time: 176000
        },
        {
            say: "Never gonna give you up",
            time: 178500
        },
        {
            say: "Never gonna let you down",
            time: 180500
        },
        {
            say: "Never gonna run around",
            time: 182500
        },
        {
            say: "And desert you",
            time: 184500
        },
        {
            say: "Never gonna make you cry",
            time: 187000
        },
        {
            say: "Never gonna say goodbye",
            time: 189000
        },
        {
            say: "Never gonna tell a lie",
            time: 191000
        },
        {
            say: "And hurt you",
            time: 193000
        },
        {
            say: "Never gonna give you up",
            time: 195000
        },
        {
            say: "Never gonna let you down",
            time: 197000
        },
        {
            say: "Never gonna run around",
            time: 199000
        },
        {
            say: "And desert you",
            time: 201000
        },
        {
            say: "Never gonna make you cry",
            time: 203000
        },
        {
            say: "Never gonna say goodbye",
            time: 205000
        },
        {
            say: "Never gonna tell a lie",
            time: 207000
        },
        {
            say: "And hurt you",
            time: 209000
        },
        ]

    let RuleTheWorld = [
        {
            say: "Welcome to your life",
            time: 29000
        },
        {
            say: "There's no turning back",
            time: 33000
        },
        {
            say: "Even while we sleep",
            time: 37000
        },
        {
            say: "We will find you",
            time: 42000
        },
        {
            say: "Acting on your",
            time: 44000
        },
        {
            say: "Best behaviour",
            time: 46200
        },
        {
            say: "Turn your back",
            time: 48400
        },
        {
            say: "On mother nature",
            time: 50700
        },
        {
            say: "Everybody",
            time: 52300
        },
        {
            say: "Wants to rule the world",
            time: 54900
        },
        {
            say: "It's my own design",
            time: 67700
        },
        {
            say: "It's my own remorse",
            time: 72000
        },
        {
            say: "Help me to decide",
            time: 76000
        },
        {
            say: "Help me make the",
            time: 80000
        },
        {
            say: "Most of freedom",
            time: 83000
        },
        {
            say: "And of pleasure",
            time: 84500
        },
        {
            say: "Nothing ever",
            time: 87000
        },
        {
            say: "Lasts forever",
            time: 89000
        },
        {
            say: "Everybody",
            time: 91000
        },
        {
            say: "Wants to rule the world",
            time: 93500
        },
        {
            say: "There's a room where",
            time: 96000
        },
        {
            say: "The light won't find you",
            time: 97800
        },
        {
            say: "Holding hands while the walls",
            time: 100000
        },
        {
            say: "Come tumbling down",
            time: 102600
        },
        {
            say: "When they do",
            time: 104550
        },
        {
            say: "I'll be right behind you",
            time: 105600
        },
        {
            say: "So glad we've almost made it",
            time: 109000
        },
        {
            say: "So sad they had to fade it",
            time: 113000
        },
        {
            say: "Everybody",
            time: 117000
        },
        {
            say: "Wants to rule the world",
            time: 119000
        },
        {
            say: "I can't stand this indecision",
            time: 168500
        },
        {
            say: "Married with a lack of vision",
            time: 172700
        },
        {
            say: "Everybody",
            time: 177000
        },
        {
            say: "Wants to rule the",
            time: 179000
        },
        {
            say: "Say that you'll",
            time: 182000
        },
        {
            say: "Never, never,",
            time: 183550
        },
        {
            say: "Never need it",
            time: 184800
        },
        {
            say: "One headline",
            time: 186000
        },
        {
            say: "Why beileve it?",
            time: 187800
        },
        {
            say: "Everybody",
            time: 190000
        },
        {
            say: "Wants to rule the world",
            time: 192000
        },
        {
            say: "All for freedom",
            time: 203000
        },
        {
            say: "And for pleasure",
            time: 205000
        },
        {
            say: "Nothing ever",
            time: 207000
        },
        {
            say: "Lasts forever",
            time: 209000
        },
        {
            say: "Everybody",
            time: 211000
        },
        {
            say: "Wants to rule the world",
            time: 213500
        }
            ]


const DejaVu = [
  { say: 'See your body', time: 39750 },
  { say: 'Into the moonlight', time: 41300 },
  { say: 'Even if I try to cancel', time: 42850 },
  { say: 'All the pictures', time: 46000 },
  { say: 'Into the mind', time: 47600 },
  { say: "There's a flashing in my eyes", time: 49000 },
  { say: 'Don\'t you see my condition', time: 51250 },
  { say: 'The fiction', time: 53000 },
  { say: 'Is gonna run it again', time: 54750 },
  { say: "Can't you see now illusions", time: 56500 },
  { say: 'Right into your mind', time: 58150 },
  { say: 'Deja vu', time: 60000 },
  { say: 'I\'ve just been', time: 61250 },
  { say: 'In this place before', time: 62850 },
  { say: 'Higher on the street', time: 64500 },
  { say: 'And I know it\'s my time to go', time: 66150 },
  { say: 'Calling you', time: 67750 },
  { say: 'And the search is a mystery', time: 69600 },
  { say: 'Standing on my feet', time: 71450 },
  { say: 'It\'s so hard when', time: 73300 },
  { say: 'I try to be me', time: 75000 },
  { say: 'Uoooh!', time: 77000 },
  { say: 'Deja vu', time: 78500 },
  { say: 'I\'ve just been', time: 80000 },
  { say: 'In this time before', time: 81550 },
  { say: 'Higher on the beat', time: 83000 },
  { say: 'And I know it\'s a place to go', time: 84550 },
  { say: 'Calling you', time: 86100 },
  { say: 'And the search is a mystery', time: 87850 },
  { say: 'Standing on my feet', time: 89550 },
  { say: 'It\'s so hard when', time: 91250 },
  { say: 'I try to be me', time: 93000 },
  { say: 'Yeah!', time: 94550 },
  { say: 'See the future', time: 105100 },
  { say: 'Into the present', time: 106750 },
  { say: 'See my past lives', time: 108250 },
  { say: 'In the distance', time: 110000 },
  { say: 'Try to guess now', time: 111500 },
  { say: "What's going on", time: 113000 },
  { say: 'And the band begins to play...', time: 114500 },
  { say: 'Don\'t you see my condition', time: 116000 },
  { say: 'The fiction', time: 117750 },
  { say: 'Is gonna run it again', time: 119250 },
  { say: "Can't you see now illusions", time: 121000 },
  { say: 'Right into your mind', time: 123000 },
  { say: 'Deja vu', time: 125000 },
  { say: 'I\'ve just been', time: 126500 },
  { say: 'In this place before', time: 128000 },
  { say: 'Higher on the street', time: 130000 },
  { say: 'And I know it\'s my time to go', time: 131500 },
  { say: 'Calling you', time: 133000 },
  { say: 'And the search is a mystery', time: 134750 },
  { say: 'Standing on my feet', time: 136500 },
  { say: 'It\'s so hard when', time: 138250 },
  { say: 'I try to be me', time: 140000 },
  { say: 'Uoooh!', time: 141750 },
  { say: 'Deja vu', time: 143500 },
  { say: 'I\'ve just been', time: 145250 },
  { say: 'In this time before', time: 146750 },
  { say: 'Higher on the beat', time: 148500 },
  { say: 'And I know it\'s a place to go', time: 150000 },
  { say: 'Calling you', time: 151500 },
  { say: 'And the search is a mystery', time: 152750 },
  { say: 'Standing on my feet', time: 154500 },
  { say: 'It\'s so hard when', time: 156000 },
  { say: 'I try to be me', time: 157500 },
  { say: 'Yeah!', time: 159250 },
  { say: 'See your body', time: 170600 },
  { say: 'Into the moonlight', time: 172250 },
  { say: 'Even if I try to cancel', time: 173750 },
  { say: 'All the pictures', time: 175500 },
  { say: 'Into the mind', time: 176750 },
  { say: "There's a flashing in my eyes", time: 179300 },
  { say: 'Don\'t you see my condition', time: 182100 },
  { say: 'The fiction', time: 184000 },
  { say: 'Is gonna run it again', time: 185500 },
  { say: "Can't you see now illusions", time: 187350 },
  { say: 'Right into your mind', time: 189250 },
  { say: 'Deja vu', time: 191000 },
  { say: 'I\'ve just been', time: 192000 },
  { say: 'In this place before', time: 193500 },
  { say: 'Higher on the street', time: 195000 },
  { say: 'And I know it\'s my time to go', time: 196500 },
  { say: 'Calling you', time: 198000 },
  { say: 'And the search is a mystery', time: 199750 },
  { say: 'Standing on my feet', time: 201500 },
  { say: 'It\'s so hard when', time: 203000 },
  { say: 'I try to be me', time: 204500 },
  { say: 'Uoooh!', time: 206250 },
  { say: 'Deja vu', time: 208000 },
  { say: 'I\'ve just been', time: 209750 },
  { say: 'In this time before', time: 211250 },
  { say: 'Higher on the beat', time: 213000 },
  { say: 'And I know it\'s a place to go', time: 214500 },
  { say: 'Calling you', time: 216000 },
  { say: 'And the search is a mystery', time: 217250 },
  { say: 'Standing on my feet', time: 219000 },
  { say: 'It\'s so hard when', time: 220250 },
  { say: 'I try to be me', time: 221750 },
  { say: 'Yeah!', time: 222000 },
];

function sendSongLyrics1() {
  let currentLine = 0;
  let accumulatedDelay = 0;

  function sendMessage() {
    if (currentLine < TakingOver.length) {
      const message = TakingOver[currentLine].say;
      const delay = TakingOver[currentLine].time - accumulatedDelay;

      // Send the message after the specified delay
      setTimeout(() => {
        game.network.sendRpc({
          name: "SendChatMessage",
          message: message,
          channel: "Local"
        });

        accumulatedDelay += delay; // Accumulate the delay
        currentLine++; // Move to the next line
        sendMessage();
      }, delay);
    }
  }

  // Start sending messages
  sendMessage();
}

function playAudio1() {
  song1.play(); // Start playing the audio
}

function sendSongLyrics2() {
  let currentLine = 0;
  let accumulatedDelay = 0;

  function sendMessage() {
    if (currentLine < NeverGonna.length) {
      const message = NeverGonna[currentLine].say;
      const delay = NeverGonna[currentLine].time - accumulatedDelay;

      // Send the message after the specified delay
      setTimeout(() => {
        game.network.sendRpc({
          name: "SendChatMessage",
          message: message,
          channel: "Local"
        });

        accumulatedDelay += delay; // Accumulate the delay
        currentLine++; // Move to the next line
        sendMessage();
      }, delay);
    }
  }

  // Start sending messages
  sendMessage();
}

    function playAudio2() {
        song2.play()
    }

function sendSongLyrics3() {
  let currentLine = 0;
  let accumulatedDelay = 0;

  function sendMessage() {
    if (currentLine < RuleTheWorld.length) {
      const message = RuleTheWorld[currentLine].say;
      const delay = RuleTheWorld[currentLine].time - accumulatedDelay;

      // Send the message after the specified delay
      setTimeout(() => {
        game.network.sendRpc({
          name: "SendChatMessage",
          message: message,
          channel: "Local"
        });

        accumulatedDelay += delay; // Accumulate the delay
        currentLine++; // Move to the next line
        sendMessage();
      }, delay);
    }
  }

  // Start sending messages
  sendMessage();
}

    function playAudio3() {
        song3.play()
    }
function sendSongLyrics4() {
  let currentLine = 0;
  let accumulatedDelay = 0;

  function sendMessage() {
    if (currentLine < DejaVu.length) {
      const message = DejaVu[currentLine].say;
      const delay = DejaVu[currentLine].time - accumulatedDelay;

      // Send the message after the specified delay
      setTimeout(() => {
        game.network.sendRpc({
          name: "SendChatMessage",
          message: message,
          channel: "Local"
        });

        accumulatedDelay += delay; // Accumulate the delay
        currentLine++; // Move to the next line
        sendMessage();
      }, delay);
    }
  }

  // Start sending messages
  sendMessage();
}
    function playAudio4() {
        song4.play();
    }
   function hideGround() {
      if (document.getElementById("hideground").innerHTML == "Show Ground") {
         document.getElementById("hideground").innerHTML = "Hide Ground"
         game.renderer.ground.setVisible(true)
      } else {
         document.getElementById("hideground").innerHTML = "Show Ground"
         game.renderer.ground.setVisible(false)
      }
   }

   function hideNPCs() {
      if (document.getElementById("hidenpcs").innerHTML == "Show NPCs") {
         document.getElementById("hidenpcs").innerHTML = "Hide NPCs"
         game.renderer.npcs.setVisible(true)
      } else {
         document.getElementById("hidenpcs").innerHTML = "Show NPCs"
         game.renderer.npcs.setVisible(false)
      }
   }

   function hideEnviroment() {
      if (document.getElementById("hideenv").innerHTML == "Show Env") {
         document.getElementById("hideenv").innerHTML = "Hide Env"
         game.renderer.scenery.setVisible(true)
      } else {
         document.getElementById("hideenv").innerHTML = "Show Env"
         game.renderer.scenery.setVisible(false)
      }
   }

   function hideProjectiles() {
      if (document.getElementById("hideproj").innerHTML == "Show Proj") {
         document.getElementById("hideproj").innerHTML = "Hide Proj"
         game.renderer.projectiles.setVisible(true)
      } else {
         document.getElementById("hideproj").innerHTML = "Show Proj"
         game.renderer.projectiles.setVisible(false)
      }
   }

   function hideAll() {
      if (document.getElementById("hideall").innerHTML == "Show All") {
         document.getElementById("hideall").innerHTML = "Hide All"
         game.renderer.scene.setVisible(true)
      } else {
         document.getElementById("hideall").innerHTML = "Show All"
         game.renderer.scene.setVisible(false)
      }
   }

   function freezeGame() {
      if (document.getElementById("freezegame").innerHTML == "Start Game") {
         document.getElementById("freezegame").innerHTML = "Stop Game"
         game.start()
      } else {
         document.getElementById("freezegame").innerHTML = "Start Game"
         game.stop()
      }
   }

   function showGrid() {
       if(document.getElementById("biggrid").innerHTML == "Show Big Grids") {
         document.getElementById("biggrid").innerHTML = "Hide Big Grids"
            game.renderer.ground.attachments[0].attachments[1].setAlpha(0.625);
            game.renderer.ground.attachments[0].attachments[1].setScale(1200 / 48);
            game.renderer.ground.attachments[0].attachments[1].sprite.width /= 1200 / 48;
            game.renderer.ground.attachments[0].attachments[1].sprite.height /= 1200 / 48;
       } else {
          document.getElementById("biggrid").innerHTML = "Show Big Grids"
           game.renderer.ground.attachments[0].attachments[1].setAlpha(1);
           game.renderer.ground.attachments[0].attachments[1].setScale(1);
           game.renderer.ground.attachments[0].attachments[1].sprite.width *= 1200 / 48;
           game.renderer.ground.attachments[0].attachments[1].sprite.height *= 1200 / 48;
       }
   }

   function showGrids() {
       if(document.getElementById("smolgrid").innerHTML == "Show Small Grids") {
         document.getElementById("smolgrid").innerHTML = "Hide Small Grids"
          game.renderer.ground.attachments[0].attachments[1].setAlpha(0.625);
          game.renderer.ground.attachments[0].attachments[1].setScale(200 / 48);
          game.renderer.ground.attachments[0].attachments[1].sprite.width /= 200 / 48;
          game.renderer.ground.attachments[0].attachments[1].sprite.height /= 200 / 48;
       } else {
          document.getElementById("smolgrid").innerHTML = "Show Small Grids"
           game.renderer.ground.attachments[0].attachments[1].setAlpha(1);
           game.renderer.ground.attachments[0].attachments[1].setScale(1);
           game.renderer.ground.attachments[0].attachments[1].sprite.width *= 200 / 48;
           game.renderer.ground.attachments[0].attachments[1].sprite.height *= 200 / 48;
       }
   }

let Auto = {}
Auto.GetGoldStash = function() {
    let entities = Game.currentGame.ui.buildings
    for (let uid in entities) {
        if (!entities.hasOwnProperty(uid)) {
            continue
        }
        let obj = entities[uid]
        if (obj.type == "GoldStash") {
            return obj
        }
    }
}
function getGoldStash() {
    var entities = Game.currentGame.world.entities
    for (var uid in entities) {
        if (!entities.hasOwnProperty(uid)) continue
        var obj = entities[uid]
        if (obj.fromTick.model == "GoldStash") {
            return obj
        }
    }
}
function GetGoldStash() {
    for (let i in game.ui.buildings) {
        if (game.ui.buildings[i].type == "GoldStash") {
            return game.ui.buildings[i];
        };
    };
};
Auto.PlaceBuilding = function(x, y, building, yaw) {
    Game.currentGame.network.sendRpc({
        name: "MakeBuilding",
        x: x,
        y: y,
        type: building,
        yaw: yaw
    })
}

function buildcornerfarm() {
        var waitForGoldStash = setInterval(function() {
        if (document.querySelectorAll("[data-building]")[10].classList[1] == "is-disabled") {
            var stash = getGoldStash();
            if (stash == undefined) return
            var stashPosition = {
                x: stash.fromTick.position.x,
                y: stash.fromTick.position.y
            }
            clearInterval(waitForGoldStash)
            Auto.PlaceBuilding(stashPosition.x + 0, stashPosition.y + 0, 'GoldStash', 180);Auto.PlaceBuilding(stashPosition.x + 0, stashPosition.y + 96, 'ArrowTower', 180);Auto.PlaceBuilding(stashPosition.x + 96, stashPosition.y + 0, 'ArrowTower', 180);Auto.PlaceBuilding(stashPosition.x + 0, stashPosition.y + 192, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 192, stashPosition.y + 0, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 192, stashPosition.y + 288, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 0, stashPosition.y + 288, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 96, stashPosition.y + 336, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 192, stashPosition.y + 384, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 240, stashPosition.y + 96, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 288, stashPosition.y + 192, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 168, stashPosition.y + 72, 'SlowTrap', 180);Auto.PlaceBuilding(stashPosition.x + 168, stashPosition.y + 120, 'SlowTrap', 180);Auto.PlaceBuilding(stashPosition.x + 288, stashPosition.y + 0, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 336, stashPosition.y + 96, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 384, stashPosition.y + 192, 'MagicTower', 180);Auto.PlaceBuilding(stashPosition.x + 264, stashPosition.y + 264, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 312, stashPosition.y + 264, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 360, stashPosition.y + 264, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 264, stashPosition.y + 312, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 312, stashPosition.y + 312, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 264, stashPosition.y + 360, 'Door', 180);Auto.PlaceBuilding(stashPosition.x + 0, stashPosition.y + 384, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 96, stashPosition.y + 432, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 192, stashPosition.y + 480, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 384, stashPosition.y + 0, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 432, stashPosition.y + 96, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 480, stashPosition.y + 192, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 288, stashPosition.y + 432, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 432, stashPosition.y + 288, 'GoldMine', 180);Auto.PlaceBuilding(stashPosition.x + 96, stashPosition.y + 240, 'CannonTower', 180);Auto.PlaceBuilding(stashPosition.x + 72, stashPosition.y + 168, 'SlowTrap', 180);Auto.PlaceBuilding(stashPosition.x + 120, stashPosition.y + 168, 'SlowTrap', 180);Auto.PlaceBuilding(stashPosition.x + 192, stashPosition.y + 192, 'BombTower', 180);Auto.PlaceBuilding(stashPosition.x + 96, stashPosition.y + 96, 'ArrowTower', 180);
            clearInterval(waitForGoldStash)
        }
    }, 150)
}

game.network.addRpcHandler("LocalBuilding", (data) => {
    for (let e of data) {
        if (!!e.dead) {
            for (let i of uniqueSellUid) {
                if (e.uid == i) {
                    uniqueSellUid.splice(uniqueSellUid.indexOf(i, 0), 1);
                }
            }
        }
    }
});

    let sellUid = [];
    let uniqueSellUid = [];

    function toggleSellingWalls() {
        if (!isSellingWalls) {
            isSellingWalls = true;
            document.getElementById("sellwall").innerHTML = "Stop Selling Walls";
        } else {
             isSellingWalls = false;
           document.getElementById("sellwall").innerHTML = "Start Selling Walls";
        }
    }

    function toggleSellingDoors() {
       if (!isSellingDoors) {
           isSellingDoors = true;
           document.getElementById("selldoor").innerHTML = "Stop Selling Doors";
       } else {
           isSellingDoors = false;
           document.getElementById("selldoor").innerHTML = "Start Selling Doors";
       }
   }

   function toggleSellingTraps() {
       if (!isSellingTraps) {
           isSellingTraps = true;
           document.getElementById("selltrap").innerHTML = "Stop Selling Traps";
       } else {
           isSellingTraps = false;
           document.getElementById("selltrap").innerHTML = "Start Selling Traps";
       }
   }

   function toggleSellingHarvs() {
       if (!isSellingHarvs) {
           isSellingHarvs = true;
           document.getElementById("sellharvester").innerHTML = "Stop Selling Harvesters";
       } else {
           isSellingHarvs = false;
           document.getElementById("sellharvester").innerHTML = "Start Selling Harvesters";
       }
   }

   function toggleSellingArrows() {
       if (!isSellingArrows) {
           isSellingArrows = true;
           document.getElementById("sellarrow").innerHTML = "Stop Selling Arrows";
       } else {
           isSellingArrows = false;
           document.getElementById("sellarrow").innerHTML = "Start Selling Arrows";
       }
   }

   function toggleSellingCannons() {
       if (!isSellingCannons) {
           isSellingCannons = true;
           document.getElementById("sellcannon").innerHTML = "Stop Selling Cannon";
       } else {
           isSellingCannons = false;
           document.getElementById("sellcannon").innerHTML = "Start Selling Cannon";
       }
   }

   function toggleSellingMages() {
       if (!isSellingMages) {
           isSellingMages = true;
           document.getElementById("sellmagic").innerHTML = "Stop Selling Mages";
       } else {
           isSellingMages = false;
           document.getElementById("sellmagic").innerHTML = "Start Selling Mages";
       }
   }

   function toggleSellingMelees() {
       if (!isSellingMelees) {
           isSellingMelees = true;
           document.getElementById("sellmelee").innerHTML = "Stop Selling Melees";
       } else {
           isSellingMelees = false;
           document.getElementById("sellmelee").innerHTML = "Start Selling Melees";
       }
   }

   function toggleSellingBombs() {
       if (!isSellingBombs) {
           isSellingBombs = true;
           document.getElementById("sellbomb").innerHTML = "Stop Selling Bombs";
       } else {
           isSellingBombs = false;
           document.getElementById("sellbomb").innerHTML = "Start Selling Bombs";
       }
   }

   function toggleSellingMines() {
       if (!isSellingMines) {
           isSellingMines = true;
           document.getElementById("sellminer").innerHTML = "Stop Selling Gold Mines";
       } else {
           isSellingMines = false;
           document.getElementById("sellminer").innerHTML = "Start Selling Gold Mines";
       }
   }

   let shouldAutoRespawn = true
   game.network.addRpcHandler("Dead", () => {
      if (shouldAutoRespawn) {
         game.network.sendPacket(3, { respawn: 1 })
         document.getElementById('hud-respawn').style.display = "none"
      }
   })

function giveSell() {
    if (!autogivesell) {
        autogivesell = true;
        document.getElementById("autosell").innerHTML = "Auto Give Sell On";
    } else {
        autogivesell = false;
        document.getElementById("autosell").innerHTML = "Auto Give Sell Off";
    }
}

    let autogivesell = false;

game.network.addEntityUpdateHandler((data) => {
    if (autogivesell && game.ui.playerPartyMembers[0].playerUid == game.world.myUid) {
        if (game.ui.playerPartyMembers[1]) {
            let sell1 = new Uint8Array(game.network.codec.encode(9, { name: "SetPartyMemberCanSell", uid: game.ui.playerPartyMembers[1].playerUid, canSell: 1 }));
            setTimeout(() => {
                game.network.socket.send(sell1);
            }, 3839);
        }
        if (game.ui.playerPartyMembers[2]) {
            let sell2 = new Uint8Array(game.network.codec.encode(9, { name: "SetPartyMemberCanSell", uid: game.ui.playerPartyMembers[2].playerUid, canSell: 1 }));
            setTimeout(() => {
                game.network.socket.send(sell2);
            }, 2361);
        }
        if (game.ui.playerPartyMembers[3]) {
            let sell3 = new Uint8Array(game.network.codec.encode(9, { name: "SetPartyMemberCanSell", uid: game.ui.playerPartyMembers[3].playerUid, canSell: 1 }));
            setTimeout(() => {
                game.network.socket.send(sell3);
            }, 1274);
        }
    }
});

   function hideChat() {
      if (document.getElementsByClassName("hud-top-left")[0].style.display === "none" && document.getElementById("hidechat").innerHTML == "Show Chat") {
         document.getElementsByClassName("hud-top-left")[0].style.display = "block";
         document.getElementById("hidechat").innerHTML = "Hide Chat";
      } else {
         document.getElementsByClassName("hud-top-left")[0].style.display = "none";
         document.getElementById("hidechat").innerHTML = "Show Chat";
      }
   }

   function hidePopupOverlay() {
      if (document.getElementById("hud-popup-overlay").style.display === "none" && document.getElementById("hidepop").innerHTML == "Show Popup") {
         document.getElementById("hud-popup-overlay").style.display = "block";
         document.getElementById("hidepop").innerHTML = "Hide Popup";
      } else {
         document.getElementById("hud-popup-overlay").style.display = "none";
         document.getElementById("hidepop").innerHTML = "Show Popup";
      }
   }

   function hideLeaderboard() {
      if (document.getElementById("hud-leaderboard").style.display === "none" && document.getElementById("hideldb").innerHTML == "Show Leaderboard") {
         document.getElementById("hud-leaderboard").style.display = "block";
         document.getElementById("hideldb").innerHTML = "Hide Leaderboard";
      } else {
         document.getElementById("hud-leaderboard").style.display = "none";
         document.getElementById("hideldb").innerHTML = "Show Leaderboard";
      }
   }

   function hideMap() {
      if (document.getElementsByClassName("hud-bottom-left")[0].style.display === "none" && document.getElementById("hidemap").innerHTML == "Show Map") {
         document.getElementsByClassName("hud-bottom-left")[0].style.display = "block";
         document.getElementById("hidemap").innerHTML = "Hide Map";
      } else {
         document.getElementsByClassName("hud-bottom-left")[0].style.display = "none";
         document.getElementById("hidemap").innerHTML = "Show Map";
      }
   }

   function hidePIP() {
      if (document.getElementsByClassName("hud-pip-overlay")[0].style.display === "block" || document.getElementsByClassName("hud-pip-overlay")[0].style.display === "") {
         document.getElementsByClassName("hud-pip-overlay")[0].style.display = "none";
         document.getElementById("hidepip").innerHTML = "Show PIP";
      } else {
         document.getElementsByClassName("hud-pip-overlay")[0].style.display = "block";
         document.getElementById("hidepip").innerHTML = "Hide PIP";
      }
   }

   function toggleday() {
    let hno = document.getElementsByClassName("hud-day-night-overlay")[0];
    if(hno.style.display === "block" || hno.style.display === "" ) {
        document.getElementById("daybright").innerHTML = "Disable Always Day";
        hno.style.display = "none";
    } else {
        document.getElementById("daybright").innerHTML = "Enable Always Day";
        hno.style.display = "block";
    };
   }

   function calculateDistance(x1, y1, x2, y2) {
       return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
   }

const borders = [new PIXI.Graphics(), new PIXI.Graphics(), new PIXI.Graphics(), new PIXI.Graphics(), new PIXI.Graphics()];
const colors = [0xFFFFFF, 0xFF0000, 0xFFFF00, 0x00FF00, 0x0000FF];
const sizes = [48, 864, 1680, 2544, 5040];

// Calculate the circle's radius to touch the corners of the rectangle
const circleRadius = Math.sqrt(Math.pow(864, 2) + Math.pow(864, 2));

// Create a circle with the calculated radius
const circle = new PIXI.Graphics();
circle.lineStyle(3, 0xFF00FF); // You can set the color as desired
circle.drawCircle(0, 0, circleRadius);
circle.visible = false; // Initially set the circle to be invisible

// Create two rectangles for the plus sign with a thickness of 3
const plusRectangles = [new PIXI.Graphics(), new PIXI.Graphics()];
const plusSize = 696969; // Size of the plus sign rectangles

// Set the line style for the plus rectangles
plusRectangles[0].lineStyle(3, 0x00FF00); // Set the color and thickness for the lines
plusRectangles[0].moveTo(-plusSize / 2, -3); // Adjust the position to center the line
plusRectangles[0].lineTo(plusSize / 2, -3); // Adjust the position to center the line
plusRectangles[0].moveTo(0, -plusSize / 2); // Adjust the position to center the line
plusRectangles[0].lineTo(0, plusSize / 2); // Adjust the position to center the line
plusRectangles[0].visible = false; // Initially set the plus sign rectangles to be invisible

plusRectangles[1].lineStyle(3, 0x00FF00); // Set the color and thickness for the lines
plusRectangles[1].moveTo(-3, -sizes[1] / 2); // Adjust the position to center the line
plusRectangles[1].lineTo(3, -sizes[1] / 2); // Adjust the position to center the line
plusRectangles[1].moveTo(-3, sizes[1] / 2); // Adjust the position to center the line
plusRectangles[1].lineTo(3, sizes[1] / 2); // Adjust the position to center the line
plusRectangles[1].visible = false; // Initially set the plus sign rectangles to be invisible

borders.forEach((item, i) => {
  item.lineStyle(3, colors[i]);
  item.drawRect(-sizes[i], -sizes[i], 2 * sizes[i], 2 * sizes[i]);
  item.visible = false; // Initially set rectangles to be invisible
});

// Update the position of the additional circle
game.network.addEntityUpdateHandler(data => {
  Object.values(data.entities).forEach(data => {
    if (data.model === "GoldStash") {
      // Set the position of the borders, circle, plus sign rectangles, and the additional circle
      borders.forEach(item => {
        item.position = data.position;
      });
      circle.position = data.position;
      plusRectangles[0].position = data.position;
      plusRectangles[1].position = data.position;

      // Check if the borders, circle, plus sign rectangles, and the additional circle are already added to the display list
      if (!game.world.renderer.entities.node.children.includes(circle)) {
        game.world.renderer.entities.node.addChild(circle);
      }
      borders.forEach(item => {
        if (!game.world.renderer.entities.node.children.includes(item)) {
          game.world.renderer.entities.node.addChild(item);
        }
      });
      plusRectangles.forEach(item => {
        if (!game.world.renderer.entities.node.children.includes(item)) {
          game.world.renderer.entities.node.addChild(item);
        }
      });
    }
  });
});

function showborder() {
  if (!renderborder) {
    renderborder = true;
    document.getElementById("border").innerHTML = "Hide Border";
  } else {
    renderborder = false;
    document.getElementById("border").innerHTML = "Show Border";
  }
}
    function showRange() {
       if (!renderRange) {
           renderRange = true
           document.getElementById("range").innerHTML = "Hide Range"
       } else {
           renderRange = false
           document.getElementById("range").innerHTML = "Show Range"
       }
   }

    let renderborder = false
    let renderRange = false

    game.network.addEntityUpdateHandler((data) => {
        if (renderborder) {
            borders.forEach(item => item.visible = true);
            circle.visible = true;
            plusRectangles[0].visible = true;
            plusRectangles[1].visible = true;
        } else {
            borders.forEach(item => item.visible = false);
            circle.visible = false;
            plusRectangles[0].visible = false;
            plusRectangles[1].visible = false;
        }
    })

   function lagSpambtn() {
      if (document.getElementById("lagspam-btn").innerHTML == "Lag Spam On") {
         document.getElementById("lagspam-btn").innerHTML = "Lag Spam Off";
      } else {
         document.getElementById("lagspam-btn").innerHTML = "Lag Spam On";
      }
   }
   let availableCharacters = ""
   let textLength = 70;
   fetch('https://raw.githubusercontent.com/bits/UTF-8-Unicode-Test-Documents/master/UTF-8_sequence_unseparated/utf8_sequence_0-0xffff_assigned_printable_unseparated.txt')
      .then(response => response.text())
      .then(data => {
         availableCharacters = data;
      });

   var chatSpam = null;

   function lagSpam() {
      clearInterval(chatSpam);
      if (chatSpam !== null) {
         chatSpam = null;
      } else {
         chatSpam = setInterval(function () {
            let text = ""
            for (let i = 0; i < textLength; i++) text += availableCharacters[Math.floor(Math.random() * availableCharacters.length)];
            game.network.sendRpc({
               name: "SendChatMessage",
               channel: "Local",
               message: text
            });
         }, 1050);
      };
   };

   function togglerev4() {
       if (!shouldrev4) {
           shouldrev4 = true
           document.getElementById("rev4").innerHTML = "Disable Rev Player Trick"
       } else {
           shouldrev4 = false
           document.getElementById("rev4").innerHTML = "Enable Rev Player Trick"
       }
   }

let shouldrev4 = false;

let hasLeftParty = false; // Flag to track if we have already left the party.
let hasJoinedParty = false; // Flag to track if we have already joined the party.

game.network.addRpcHandler("DayCycle", (e) => {
  if (e.isDay && shouldrev4 && !hasLeftParty) {
    // Daytime: Wait 50 seconds, then leave the party once.
    setTimeout(() => {
      Game.currentGame.network.sendRpc({ name: "LeaveParty" });
      hasLeftParty = true; // Set the flag to true to indicate that we've left the party.
    }, 50000);
  }
  if (!e.isDay && shouldrev4 && !hasJoinedParty) {
    // Nighttime: Wait 10 seconds, then join the party once.
    setTimeout(() => {
      const shareKey = document.querySelector("#menu-jpbsk-input").value;
      if (shareKey) {
        Game.currentGame.network.sendRpc({ name: "JoinPartyByShareKey", partyShareKey: shareKey });
        hasJoinedParty = true; // Set the flag to true to indicate that we've joined the party.
      }
    }, 10000);
  }

  // Reset the flags at the beginning of each day/night cycle.
  if (!e.isDay) {
    hasLeftParty = false;
  } else {
    hasJoinedParty = false;
  }
});

   function spamAllParty() {
      if (document.getElementById("spamallparty-btn").innerHTML == "Spam All Party On") {
         document.getElementById("spamallparty-btn").innerHTML = "Spam All Party Off";
         shouldSpamAllParty = false
      } else {
         document.getElementById("spamallparty-btn").innerHTML = "Spam All Party On";
         shouldSpamAllParty = true
      }
   }

   function autoAcceptPartybtn() {
      if (document.getElementById("autoaccept-btn").innerHTML == "Accepter On") {
         document.getElementById("autoaccept-btn").innerHTML = "Accepter Off";
      } else {
         document.getElementById("autoaccept-btn").innerHTML = "Accepter On";
      }
   }
   var acceptparty = null;

   function autoAcceptParty() {
      clearInterval(acceptparty);
      if (acceptparty !== null) {
         acceptparty = null;
      } else {
         acceptparty = setInterval(function () {
            var confirm = document.getElementsByClassName("btn btn-green hud-confirmation-accept");
            for (var j = 0; j < confirm.length; j++) {
               confirm[j].click();
            }
         }, 100);
      }
   }

   function autoUpgradeAllbtn() {
      if (document.getElementById("autoupgradeall-btn").innerHTML == "Upgrade On") {
         document.getElementById("autoupgradeall-btn").innerHTML = "Upgrade Off";
      } else {
         document.getElementById("autoupgradeall-btn").innerHTML = "Upgrade On";
      }
   }

   function autouparrowbtn() {
      if (document.getElementById("uparrow").innerHTML == "Up Arrows On") {
         document.getElementById("uparrow").innerHTML = "Up Arrows Off";
      } else {
         document.getElementById("uparrow").innerHTML = "Up Arrows On";
      }
   }

   function autoupstashbtn() {
      if (document.getElementById("upstash").innerHTML == "Up Stash On") {
         document.getElementById("upstash").innerHTML = "Up Stash Off";
      } else {
         document.getElementById("upstash").innerHTML = "Up Stash On";
      }
   }

   function autoupmagebtn() {
      if (document.getElementById("upmage").innerHTML == "Up Mages On") {
         document.getElementById("upmage").innerHTML = "Up Mages Off";
      } else {
         document.getElementById("upmage").innerHTML = "Up Mages On";
      }
   }

    function autoupminesbtn() {
      if (document.getElementById("upmines").innerHTML == "Up Mines On") {
         document.getElementById("upmines").innerHTML = "Up Mines Off";
      } else {
         document.getElementById("upmines").innerHTML = "Up Mines On";
      }
   }

   function autoupwallbtn() {
      if (document.getElementById("upwall").innerHTML == "Up Walls On") {
         document.getElementById("upwall").innerHTML = "Up Walls Off";
      } else {
         document.getElementById("upwall").innerHTML = "Up Walls On";
      }
   }

   function autoupdoorbtn() {
      if (document.getElementById("updoor").innerHTML == "Up Doors On") {
         document.getElementById("updoor").innerHTML = "Up Doors Off";
      } else {
         document.getElementById("updoor").innerHTML = "Up Doors On";
      }
   }

   function autouptrapbtn() {
      if (document.getElementById("uptrap").innerHTML == "Up Slow Traps On") {
         document.getElementById("uptrap").innerHTML = "Up Slow Traps Off";
      } else {
         document.getElementById("uptrap").innerHTML = "Up Slow Traps On";
      }
   }

   function autoupmeleebtn() {
      if (document.getElementById("upmelee").innerHTML == "Up Melees On") {
         document.getElementById("upmelee").innerHTML = "Up Melees Off";
      } else {
         document.getElementById("upmelee").innerHTML = "Up Melees On";
      }
   }

   function autoupbombbtn() {
      if (document.getElementById("upbomb").innerHTML == "Up Bombs On") {
         document.getElementById("upbomb").innerHTML = "Up Bombs Off";
      } else {
         document.getElementById("upbomb").innerHTML = "Up Bombs On";
      }
   }

   function autoupharvesterbtn() {
      if (document.getElementById("upharvester").innerHTML == "Up Harvesters On") {
         document.getElementById("upharvester").innerHTML = "Up Harvesters Off";
      } else {
         document.getElementById("upharvester").innerHTML = "Up Harvesters On";
      }
   }

   function autoupcannonbtn() {
      if (document.getElementById("upcannon").innerHTML == "Up Cannons On") {
         document.getElementById("upcannon").innerHTML = "Up Cannons Off";
      } else {
         document.getElementById("upcannon").innerHTML = "Up Cannons On";
      }
   }

   var autoupgradeall = null;

   function autoUpgradeAll() {
      clearInterval(autoupgradeall);
      if (autoupgradeall !== null) {
         autoupgradeall = null;
      } else {
         autoupgradeall = setInterval(function () {
            var entities = Game.currentGame.world.entities;
            for (var uid in entities) {
               if (!entities.hasOwnProperty(uid)) continue;
               var obj = entities[uid];
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: obj.fromTick.uid
               })
            }
         }, 1000)
      }
   }


var autoUpgradeArrowTowers = null;

function autouparrow() {
   clearInterval(autoUpgradeArrowTowers);
   if (autoUpgradeArrowTowers !== null) {
      autoUpgradeArrowTowers = null;
   } else {
      autoUpgradeArrowTowers = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "ArrowTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 900);
   }
}
    var autoUpgradeStash = null;

function autoupstash() {
   clearInterval(autoUpgradeStash);
   if (autoUpgradeStash !== null) {
      autoUpgradeStash = null;
   } else {
      autoUpgradeStash = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "GoldStash") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 1500);
   }
}
    var autoUpgradeMage = null;

function autoupmage() {
   clearInterval(autoUpgradeMage);
   if (autoUpgradeMage !== null) {
      autoUpgradeMage = null;
   } else {
      autoUpgradeMage = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "MagicTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 600);
   }
}

var autoUpgradeMines = null;

function autoupmines() {
   clearInterval(autoUpgradeMines);
   if (autoUpgradeMines !== null) {
      autoUpgradeMines = null;
   } else {
      autoUpgradeMines = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "GoldMine") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 100);
   }
}

var autoUpgradeWalls = null;

function autoupwall() {
   clearInterval(autoUpgradeWalls);
   if (autoUpgradeWalls !== null) {
      autoUpgradeWalls = null;
   } else {
      autoUpgradeWalls = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Wall") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 300);
   }
}

var autoUpgradeDoors = null;

function autoupdoor() {
   clearInterval(autoUpgradeDoors);
   if (autoUpgradeDoors !== null) {
      autoUpgradeDoors = null;
   } else {
      autoUpgradeDoors = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Door") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 300);
   }
}

var autoUpgradeTraps = null;

function autouptrap() {
   clearInterval(autoUpgradeTraps);
   if (autoUpgradeTraps !== null) {
      autoUpgradeTraps = null;
   } else {
      autoUpgradeTraps = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "SlowTrap") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 500);
   }
}

var autoUpgradeCannon = null;

function autoupcannon() {
   clearInterval(autoUpgradeCannon);
   if (autoUpgradeCannon !== null) {
      autoUpgradeCannon = null;
   } else {
      autoUpgradeCannon = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "CannonTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 700);
   }
}

var autoUpgradeMelee = null;

function autoupmelee() {
   clearInterval(autoUpgradeMelee);
   if (autoUpgradeMelee !== null) {
      autoUpgradeMelee = null;
   } else {
      autoUpgradeMelee = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "MeleeTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 1000);
   }
}

var autoUpgradeBomb = null;

function autoupbomb() {
   clearInterval(autoUpgradeBomb);
   if (autoUpgradeBomb !== null) {
      autoUpgradeBomb = null;
   } else {
      autoUpgradeBomb = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "BombTower") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 1000);
   }
}

var autoUpgradeHarvester = null;

function autoupharvester() {
   clearInterval(autoUpgradeHarvester);
   if (autoUpgradeHarvester !== null) {
      autoUpgradeHarvester = null;
   } else {
      autoUpgradeHarvester = setInterval(function () {
         for (let uid in game.ui.buildings) {
            if (game.ui.buildings[uid].type == "Harvester") {
               Game.currentGame.network.sendRpc({
                  name: "UpgradeBuilding",
                  uid: game.ui.buildings[uid].uid
               });
            }
         }
      }, 2000);
   }
}
   function spamPartyByID() {
      if (document.getElementById("spampartybyid-btn").innerHTML == "Spam Party By ID On") {
         shouldSpamIdParty = false
         document.getElementById("spampartybyid-btn").innerHTML = "Spam Party By ID Off";
      } else {
         shouldSpamIdParty = true
         document.getElementById("spampartybyid-btn").innerHTML = "Spam Party By ID On";
      }
   }

   function clearChatbtn() {
      if (document.getElementById("clearchat-btn").innerHTML == "Clear Chat On") {
         document.getElementById("clearchat-btn").innerHTML = "Clear Chat Off";
         shouldClearChat = false
      } else {
         document.getElementById("clearchat-btn").innerHTML = "Clear Chat On";
         shouldClearChat = true
      }
   }

   function spinnerbtn() {
      if (document.getElementById("togglespinner").innerHTML == "Spinner On") {
         document.getElementById("togglespinner").innerHTML = "Spinner Off";
         shouldSpin = false
         yaw = game.ui.playerTick.aimingYaw
      } else {
         document.getElementById("togglespinner").innerHTML = "Spinner On";
         shouldSpin = true
         yaw = game.ui.playerTick.aimingYaw
      }
   }

   function toggleRebuild() {
    window.rebuilderOn = !window.rebuilderOn;

    window.toggleRebuilder()

    document.getElementById("togglerb").innerText = window.rebuilderOn ? "Rebuild On" : "Rebuild Off";

    window.rebuilderOn ? (() => {
        game.ui.components.PopupOverlay.showHint2 = game.ui.components.PopupOverlay.showHint;

        game.ui.components.PopupOverlay.showHint = (popup, ms) => {
            if ((popup == "You can't place buildings that far away from your position.") || (popup == "You can't place buildings in occupied cells.")) return;

            game.ui.components.PopupOverlay.showHint2(popup, ms);
        };
    })() : (() => {
        if (game.ui.components.PopupOverlay.showHint2) {
            game.ui.components.PopupOverlay.showHint = game.ui.components.PopupOverlay.showHint2;
        };
    })();
};

   function toggleHealthUp() {
      if(!shouldhealthup) {
          shouldhealthup = true
          document.getElementById("togglehealthup").innerHTML = "Low Health Upgrade On"
      } else {
          shouldhealthup = false
          document.getElementById("togglehealthup").innerHTML = "Low Health Upgrade Off"
      }
   }

   function toggleHealSpell() {
       if(!shouldhealtowers) {
           shouldhealtowers = true
           document.getElementById("towerheal").innerHTML = "Heal Towers On"
       } else {
           shouldhealtowers = false
           document.getElementById("towerheal").innerHTML = "Heal Towers Off"
       }
   }

    let shouldhealthup = false
    let shouldhealtowers = false

   game.network.addEntityUpdateHandler(({entities}) => {
      if(shouldhealthup) {
        for (let uid in entities) {
             const currentEntity = entities[uid];
             const worldEntity = game.world.entities[uid];
             if (currentEntity == true) continue;
             if (uid in game.ui.buildings && typeof currentEntity.health == 'number') {
                 const buildingHealth = (currentEntity?.health / worldEntity.targetTick.maxHealth) * 100;
                 if (buildingHealth <= 20) {
                     game.network.sendRpc({name: "UpgradeBuilding", uid: parseInt(uid)});
                 }
             };
        };
      }
      if (shouldhealtowers) {
    for (let uid in entities) {
      const currentEntity = entities[uid];
      const worldEntity = game.world.entities[uid];

      if (currentEntity == true) continue;
      if (uid in game.ui.buildings && typeof currentEntity.health == 'number') {
        const buildingHealth = (currentEntity?.health / worldEntity.targetTick.maxHealth) * 100;

        if (buildingHealth <= 50 && game.ui.playerTick.gold >= 1000 && game.ui.buildings[uid].type !== "Wall" && game.ui.buildings[uid].type !== "Door" && game.ui.buildings[uid].type !== "SlowTrap") {
          const buildingX = worldEntity.targetTick.position.x;
          const buildingY = worldEntity.targetTick.position.y;
          game.network.sendPacket(9, {name: "CastSpell", spell: "HealTowersSpell", x: Math.round(buildingX), y: Math.round(buildingY), tier: 1});
        }
      }
    }
  }
   })

   function autoleave() {
       if (!stash10leave) {
          stash10leave = true
          document.getElementById("stashleave").innerHTML = "Auto Leave On"
          game.ui.getComponent("PopupOverlay").showHint('Auto Leave Party When Stash Health Falls Below 10% Enabled', 3000)
       } else {
          stash10leave = false
          document.getElementById("stashleave").innerHTML = "Auto Leave Off"
       }
   }

   function togglefriend() {
       if (!friendcontrol) {
          friendcontrol = true
          document.getElementById("allowfriend").innerHTML = "Disallow Friend Control"
       } else {
          friendcontrol = false
          document.getElementById("allowfriend").innerHTML = "Allow Friend Control"
       }
   }

   function abpk() {
      if(!shouldabpk) {
        shouldabpk = true;
        document.getElementById("toggleabpk").innerHTML = "Disable Auto Buy Pickaxe";
      } else {
        shouldabpk = false;
        document.getElementById("toggleabpk").innerHTML = "Enable Auto Buy Pickaxe";
      }
   }

    function absp() {
      if(!shouldabsp) {
        shouldabsp = true;
        document.getElementById("toggleabsp").innerHTML = "Disable Auto Buy Spear";
      } else {
        shouldabsp = false;
        document.getElementById("toggleabsp").innerHTML = "Enable Auto Buy Spear";
      }
   }

    function abbw() {
      if(!shouldabbw) {
        shouldabbw = true;
        document.getElementById("toggleabbw").innerHTML = "Disable Auto Buy Bow";
      } else {
        shouldabbw = false;
        document.getElementById("toggleabbw").innerHTML = "Enable Auto Buy Bow";
      }
   }

    function abbm() {
      if(!shouldabbm) {
        shouldabbm = true;
        document.getElementById("toggleabbm").innerHTML = "Disable Auto Buy Bomb";
      } else {
        shouldabbm = false;
        document.getElementById("toggleabbm").innerHTML = "Enable Auto Buy Bomb";
      }
   }

    function absh() {
      if(!shouldabsh) {
        shouldabsh = true;
        document.getElementById("toggleabsh").innerHTML = "Disable Auto Buy Sheild";
      } else {
        shouldabsh = false;
        document.getElementById("toggleabsh").innerHTML = "Enable Auto Buy Sheild";
      }
   }

   let shouldabpk = false
   let shouldabsp = false
   let shouldabbw = false
   let shouldabbm = false
   let shouldabsh = false

        game.network.addEntityUpdateHandler(() => {
         if (shouldabpk) {
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 1 && game.ui.playerTick.gold >= undefined) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 2 && game.ui.playerTick.gold >= 1000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 3 && game.ui.playerTick.gold >= 3000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 4 && game.ui.playerTick.gold >= 5000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 5 && game.ui.playerTick.gold >= 8000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 6 && game.ui.playerTick.gold >= 24000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Pickaxe.nextTier === 7 && game.ui.playerTick.gold >= 90000) {
            game.ui.components.MenuShop.shopItems.Pickaxe.componentElem.click();
        };
             }
         })

      game.network.addEntityUpdateHandler(() => {
          if(shouldabbm){
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 1 && game.ui.playerTick.gold >= 100) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 2 && game.ui.playerTick.gold >= 400) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 3 && game.ui.playerTick.gold >= 3000) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 4 && game.ui.playerTick.gold >= 5000) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 5 && game.ui.playerTick.gold >= 24000) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 6 && game.ui.playerTick.gold >= 50000) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bomb.nextTier === 7 && game.ui.playerTick.gold >= 90000) {
            game.ui.components.MenuShop.shopItems.Bomb.componentElem.click();
        }
             }
        })

      game.network.addEntityUpdateHandler(() => {
          if(shouldabbw){
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 1 && game.ui.playerTick.gold >= 100) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 2 && game.ui.playerTick.gold >= 400) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 3 && game.ui.playerTick.gold >= 2000) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 4 && game.ui.playerTick.gold >= 7000) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 5 && game.ui.playerTick.gold >= 24000) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 6 && game.ui.playerTick.gold >= 30000) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Bow.nextTier === 7 && game.ui.playerTick.gold >= 90000) {
            game.ui.components.MenuShop.shopItems.Bow.componentElem.click();
        }
             }
      })

    game.network.addEntityUpdateHandler(() => {
            if(shouldabsp){
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 1 && game.ui.playerTick.gold >= 1400) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 2 && game.ui.playerTick.gold >= 2800) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 3 && game.ui.playerTick.gold >= 5600) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 4 && game.ui.playerTick.gold >= 11200) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 5 && game.ui.playerTick.gold >= 22500) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 6 && game.ui.playerTick.gold >= 45000) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.Spear.nextTier === 7 && game.ui.playerTick.gold >= 90000) {
            game.ui.components.MenuShop.shopItems.Spear.componentElem.click();
        }
             }
    })

     game.network.addEntityUpdateHandler(() => {
            if(shouldabsh) {
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 1 && game.ui.playerTick.gold >= 1000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 2 && game.ui.playerTick.gold >= 3000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 3 && game.ui.playerTick.gold >= 7000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 4 && game.ui.playerTick.gold >= 14000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 5 && game.ui.playerTick.gold >= 18000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 6 && game.ui.playerTick.gold >= 22000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 7 && game.ui.playerTick.gold >= 24000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 8 && game.ui.playerTick.gold >= 30000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 9 && game.ui.playerTick.gold >= 45000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
        if (game.ui.components.MenuShop.shopItems.ZombieShield.nextTier === 10 && game.ui.playerTick.gold >= 70000) {
            game.ui.components.MenuShop.shopItems.ZombieShield.componentElem.click();
        };
             }
      })

   function toggleSwing() {
      if (!autoSwing) {
         autoSwing = true;
         document.getElementById("toggleswing").innerHTML = "Swing On";
      } else {
         autoSwing = false;
         document.getElementById("toggleswing").innerHTML = "Swing Off";
      }
   }

   function FIGHT() {
      if(!fighting) {
        fighting = true
        document.getElementById("battle").innerHTML = "Disable Fighting Mode";
      } else {
        fighting = false
        document.getElementById("battle").innerHTML = "Enable Fighting Mode";
      }
   }

   function trapon() {
      if(!trappingEnabled) {
         trappingEnabled = true
         document.getElementById("trap").innerHTML = "Disable Auto Trapper";
      } else {
         trappingEnabled = false
         document.getElementById("trap").innerHTML = "Enable Auto Trapper";
      }
   }

   function afkswitches() {
       if(!switching) {
           switching = true
           document.getElementById("switch").innerHTML = "Disable Afk Switch";
       } else {
           switching = false
           document.getElementById("switch").innerHTML = "Enable Afk Switch";
       }
   }

   function togglemove() {
       if(!moving) {
           moving = true
           document.getElementById("move").innerHTML = "Disable Player Follower";
       } else {
           moving = false
           document.getElementById("move").innerHTML = "Enable Player Follower";
            clearInterval(goToPosInterval);
            clearTimeout(moveTimeout);
            game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
       }
   }

// Variable to keep track of whether you are in fighting mode
let fighting = false;

// Function to perform actions based on distance
function performActions(distance) {
    if (distance > 125 && distance < Infinity) {
        // If the distance is greater than 125, perform this action
        shopShortcut("Bow", game.ui.inventory.Bow.tier);
    } else {
        // If the distance is less than or equal to 125, perform this action
        shopShortcut("Spear", game.ui.inventory.Spear.tier);
    }
}

// Function to find the closest enemy player and calculate the distance
function findClosestEnemyPlayerDistance() {
    if (fighting) {
        // Get your player's party ID
        const myPartyId = game.ui.playerPartyId;

        // Get your player's position
        const myX = game.ui.playerTick.position.x;
        const myY = game.ui.playerTick.position.y;

        // Initialize variables to keep track of the closest enemy player and distance
        let closestEnemyPlayer = null;
        let closestDistance = Infinity;

        // Iterate through all players
        for (let i in game.renderer.npcs.attachments) {
            if (game.renderer.npcs.attachments[i].fromTick.name) {
                const player = game.renderer.npcs.attachments[i];
                const playerX = player.targetTick.position.x;
                const playerY = player.targetTick.position.y;
                const playerPartyId = player.targetTick.partyId;

                // Check if this player is not in your party
                if (playerPartyId !== myPartyId) {
                    // Calculate the distance between your player and this player
                    const distance = calculateDistance(myX, myY, playerX, playerY);

                    // Check if this player is closer than the current closest enemy player and the distance is greater than 20
                    if (distance < closestDistance && distance > 20) {
                        closestEnemyPlayer = player;
                        closestDistance = distance;
                    }
                }
            }
        }

        // Check if there are any enemy players in range before performing actions
        if (closestEnemyPlayer !== null) {
            // Now, closestEnemyPlayer contains the closest enemy player, and closestDistance contains the distance

            // Perform actions based on the distance
            performActions(closestDistance);
        }
    }
}

// Set up an interval to continuously calculate the distance to enemy players when in fighting mode
setInterval(() => {
    if (fighting) {
        findClosestEnemyPlayerDistance();
    }
}, 50); // Adjust the interval as needed

let trappingEnabled = false;

// Function to round a number to the nearest multiple of a given factor and adjust by 24
function roundToNearest48Adjusted(number) {
    const rounded = Math.round(number / 48) * 48;
    return rounded + (number > rounded ? 24 : -24);
}

// Function to place 7x7 walls around a given position
function place7x7Walls(x, y) {
    // Calculate the nearest multiple of 48 for the rounded position with adjustment
    const roundedX = roundToNearest48Adjusted(x);
    const roundedY = roundToNearest48Adjusted(y);

    // Layer 1
    placeWall(roundedX - 48 - 48 - 48, roundedY + 48 + 48 + 48);
    placeWall(roundedX - 48 - 48, roundedY + 48 + 48 + 48);
    placeWall(roundedX - 48, roundedY + 48 + 48 + 48);
    placeWall(roundedX, roundedY + 48 + 48 + 48);
    placeWall(roundedX + 48, roundedY + 48 + 48 + 48);
    placeWall(roundedX + 48 + 48, roundedY + 48 + 48 + 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY + 48 + 48 + 48);

    // Layer 2
    placeWall(roundedX - 48 - 48 - 48, roundedY + 48 + 48);
    placeWall(roundedX - 48 - 48, roundedY + 48 + 48);
    placeWall(roundedX - 48, roundedY + 48 + 48);
    placeWall(roundedX, roundedY + 48 + 48);
    placeWall(roundedX + 48, roundedY + 48 + 48);
    placeWall(roundedX + 48 + 48, roundedY + 48 + 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY + 48 + 48);

    // Layer 3
    placeWall(roundedX - 48 - 48 - 48, roundedY + 48);
    placeWall(roundedX - 48 - 48, roundedY + 48);
    placeWall(roundedX + 48 + 48, roundedY + 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY + 48);

    // Layer 4
    placeWall(roundedX - 48 - 48 - 48, roundedY);
    placeWall(roundedX - 48 - 48, roundedY);
    placeWall(roundedX + 48 + 48, roundedY);
    placeWall(roundedX + 48 + 48 + 48, roundedY);

    // Layer 5
    placeWall(roundedX - 48 - 48 - 48, roundedY - 48);
    placeWall(roundedX - 48 - 48, roundedY - 48);
    placeWall(roundedX + 48 + 48, roundedY - 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY - 48);

    // Layer 6
    placeWall(roundedX - 48 - 48 - 48, roundedY - 48 - 48);
    placeWall(roundedX - 48 - 48, roundedY - 48 - 48);
    placeWall(roundedX - 48, roundedY - 48 - 48);
    placeWall(roundedX, roundedY - 48 - 48);
    placeWall(roundedX + 48, roundedY - 48 - 48);
    placeWall(roundedX + 48 + 48, roundedY - 48 - 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY - 48 - 48);

    // Layer 7
    placeWall(roundedX - 48 - 48 - 48, roundedY - 48 - 48 - 48);
    placeWall(roundedX - 48 - 48, roundedY - 48 - 48 - 48);
    placeWall(roundedX - 48, roundedY - 48 - 48 - 48);
    placeWall(roundedX, roundedY - 48 - 48 - 48);
    placeWall(roundedX + 48, roundedY - 48 - 48 - 48);
    placeWall(roundedX + 48 + 48, roundedY - 48 - 48 - 48);
    placeWall(roundedX + 48 + 48 + 48, roundedY - 48 - 48 - 48);
}

function findPlayersInRangeToTrap() {
    if (trappingEnabled) {
        const myPartyId = game.ui.playerPartyId;
        // Get your player's position
        const myX = game.ui.playerTick.position.x;
        const myY = game.ui.playerTick.position.y;

        // Iterate through all players
        for (let i in game.renderer.npcs.attachments) {
            if (game.renderer.npcs.attachments[i].fromTick.name) {
                const player = game.renderer.npcs.attachments[i];
                const playerX = player.targetTick.position.x;
                const playerY = player.targetTick.position.y;
                const playerPartyId = player.targetTick.partyId;

                // Check if this player is not in your party and is more than 20 units away
                if (playerPartyId !== myPartyId && calculateDistance(myX, myY, playerX, playerY) > 20) {
                    // Get the position of the enemy player
                    const enemyX = playerX;
                    const enemyY = playerY;

                    // Place 7x7 walls around the enemy player's position
                    place7x7Walls(enemyX, enemyY);
                }
            }
        }
    }
}

// Set up an interval to continuously find and place walls around enemy players in range
setInterval(() => {
    if (trappingEnabled) {
        findPlayersInRangeToTrap();
    }
}, 1000); // Adjust the interval as needed

    // Variable to keep track of whether you are in fighting mode
let switching = false;

// Function to perform actions based on distance
function changeWeapon(distance) {
    if (distance <= 100 && distance > 0) {
        EquipOnly("Spear", game.ui.inventory.Spear.tier);
    } else if (distance > 100 && distance <= 300) {
        EquipOnly("Bomb", game.ui.inventory.Bomb.tier);
    } else if (distance > 300 && distance < Infinity) {
        EquipOnly("Bow", game.ui.inventory.Bow.tier);
    }
}

// Function to find the closest enemy player and calculate the distance
function FindClosestPlayer() {
    if (switching) {
        // Get your player's party ID
        const myPartyId = game.ui.playerPartyId;

        // Get your player's position
        const myX = game.ui.playerTick.position.x;
        const myY = game.ui.playerTick.position.y;

        // Initialize variables to keep track of the closest enemy player and distance
        let closestEnemyPlayer = null;
        let closestDistance = Infinity;

        // Iterate through all players
        for (let i in game.renderer.npcs.attachments) {
            if (game.renderer.npcs.attachments[i].fromTick.name) {
                const player = game.renderer.npcs.attachments[i];
                const playerX = player.targetTick.position.x;
                const playerY = player.targetTick.position.y;
                const playerPartyId = player.targetTick.partyId;

                // Check if this player is not in your party
                if (playerPartyId !== myPartyId) {
                    // Calculate the distance between your player and this player
                    const distance = calculateDistance(myX, myY, playerX, playerY);

                    // Check if this player is closer than the current closest enemy player and the distance is greater than 20
                    if (distance < closestDistance && distance > 20) {
                        closestEnemyPlayer = player;
                        closestDistance = distance;
                    }
                }
            }
        }

        // Check if there are any enemy players in range before performing actions
        if (closestEnemyPlayer !== null) {
            // Now, closestEnemyPlayer contains the closest enemy player, and closestDistance contains the distance

            // Perform actions based on the distance
            changeWeapon(closestDistance);
        }
    }
}

// Set up an interval to continuously calculate the distance to enemy players when in fighting mode
setInterval(() => {
    if (switching) {
        FindClosestPlayer();
    }
}, 50); // Adjust the interval as needed

// Variable to keep track of whether you are in moving mode
let moving = false;

// Declare closestEnemyPlayer outside of the functions
let closestEnemyPlayer = null;

// Function to perform actions based on distance
function followPlayer(distance) {
    if (distance < 300) {
        // If the distance is less than 300, lock your position to the player
        lockposition(closestEnemyPlayer.targetTick.position.x, closestEnemyPlayer.targetTick.position.y);
    }
}

// Function to find the closest enemy player and calculate the distance
function findClosestPlayerToFollow() {
    if (moving) {
        // Get your player's party ID
        const myPartyId = game.ui.playerPartyId;

        // Get your player's position
        const myX = game.ui.playerTick.position.x;
        const myY = game.ui.playerTick.position.y;

        // Initialize variables to keep track of the closest enemy player and distance
        closestEnemyPlayer = null; // Reset closestEnemyPlayer
        let closestDistance = Infinity;

        // Iterate through all players
        for (let i in game.renderer.npcs.attachments) {
            if (game.renderer.npcs.attachments[i].fromTick.name) {
                const player = game.renderer.npcs.attachments[i];
                const playerX = player.targetTick.position.x;
                const playerY = player.targetTick.position.y;
                const playerPartyId = player.targetTick.partyId;

                // Check if this player is not in your party
                if (playerPartyId !== myPartyId) {
                    // Calculate the distance between your player and this player
                    const distance = calculateDistance(myX, myY, playerX, playerY);

                    // Check if this player is closer than the current closest enemy player and the distance is greater than 20
                    if (distance < closestDistance && distance > 20) {
                        closestEnemyPlayer = player;
                        closestDistance = distance;
                    }
                }
            }
        }

        // Check if there are any enemy players in range before performing actions
        if (closestEnemyPlayer !== null) {
            // Now, closestEnemyPlayer contains the closest enemy player, and closestDistance contains the distance

            // Perform actions based on the distance
            followPlayer(closestDistance);
        }
    }
}

   function toggleAHRC() {
      if (!shouldAHRC) {
         shouldAHRC = true;
         document.getElementById("toggleahrc").innerHTML = "AHRC On";
      } else {
         shouldAHRC = false;
         document.getElementById("toggleahrc").innerHTML = "AHRC Off";
      }
   }

   function toggleRespawn() {
      if (!shouldAutoRespawn) {
         shouldAutoRespawn = true;
         document.getElementById("toggleresp").innerHTML = "Respawn On";
      } else {
         shouldAutoRespawn = false;
         document.getElementById("toggleresp").innerHTML = "Respawn Off";
      }
   }

   function toggleAim() {
      if (!shouldAutoAim) {
         shouldAutoAim = true;
         document.getElementById("toggleaim").innerHTML = "Aim On";
      } else {
         shouldAutoAim = false;
         document.getElementById("toggleaim").innerHTML = "Aim Off";
      }
   }

   function toggleHealPet() {
      if (!shouldAutoHealPet) {
         shouldAutoHealPet = true;
         document.getElementById("healpet").innerHTML = "Heal Pet On";
      } else {
         shouldAutoHealPet = false;
         document.getElementById("healpet").innerHTML = "Heal Pet Off";
      }
   }

   function toggleRevivePet() {
      if (!shouldAutoRevivePet) {
         shouldAutoRevivePet = true
         document.getElementById("revivepet").innerHTML = "Revive On";
      } else {
         shouldAutoRevivePet = false
         document.getElementById("revivepet").innerHTML = "Revive Off";
      }
   }

   function toggleEvolvePet() {
      if (!shouldAutoEvolvePet) {
         shouldAutoEvolvePet = true
         document.getElementById("evolvepet").innerHTML = "Evolve On";
      } else {
         shouldAutoEvolvePet = false
         document.getElementById("evolvepet").innerHTML = "Evolve Off";
      }
   }

   function toggleHealPlayer() {
      if (!shouldAutoHealPlayer) {
         shouldAutoHealPlayer = true
         document.getElementById("healplayer").innerHTML = "Heal Player On"
      } else {
         shouldAutoHealPlayer = false
         document.getElementById("healplayer").innerHTML = "Heal Player Off"
      }
   }

   function move(direction) {
      switch (direction) {
         case 'Up': {
            game.inputPacketScheduler.scheduleInput({ up: 1, down: 0, left: 0, right: 0 })
            break
         }
         case 'Down': {
            game.inputPacketScheduler.scheduleInput({ up: 0, down: 1, left: 0, right: 0 })
            break
         }
         case 'Left': {
            game.inputPacketScheduler.scheduleInput({ up: 0, down: 0, left: 1, right: 0 })
            break
         }
         case 'Right': {
            game.inputPacketScheduler.scheduleInput({ up: 0, down: 0, left: 0, right: 1 })
            break
         }
         case 'UpRight': {
            game.inputPacketScheduler.scheduleInput({ up: 1, down: 0, left: 0, right: 1 })
            break
         }
         case 'UpLeft': {
            game.inputPacketScheduler.scheduleInput({ up: 1, down: 0, left: 1, right: 0 })
            break
         }
         case 'DownRight': {
            game.inputPacketScheduler.scheduleInput({ up: 0, down: 1, left: 0, right: 1 })
            break
         }
         case 'DownLeft': {
            game.inputPacketScheduler.scheduleInput({ up: 0, down: 1, left: 1, right: 0 })
            break
         }
      }
   }

    var getRss = false;
    var allowed1 = true;

game.network.addEntityUpdateHandler(() => {
    if (getRss) {
        !allowed1 && (allowed1 = true);
    }
    if (getRss || allowed1) {
        for (let i in game.renderer.npcs.attachments) {
            if (game.renderer.npcs.attachments[i].fromTick.name) {
                let player = game.renderer.npcs.attachments[i];
                let wood_1 = counter(player.targetTick.wood);
                let stone_1 = counter(player.targetTick.stone);
                let gold_1 = counter(player.targetTick.gold);
                let token_1 = counter(player.targetTick.token);
                let px_1 = counter(player.targetTick.position.x);
                let py_1 = counter(player.targetTick.position.y);
                let timeout_1 = "";
                if (getRss && !player.targetTick.oldName) {
                    player.targetTick.oldName = player.targetTick.name;
                    player.targetTick.oldWood = wood_1;
                    player.targetTick.oldStone = stone_1;
                    player.targetTick.oldGold = gold_1;
                    player.targetTick.oldToken = token_1;
                    player.targetTick.oldPX = px_1;
                    player.targetTick.oldPY = py_1;
                    player.targetTick.info = `
  ${player.targetTick.oldName}; score: ${player.targetTick.score.toLocaleString()}
  UID: ${player.targetTick.uid}
  W: ${wood_1}, S: ${stone_1}, G: ${gold_1}, T: ${token_1}
  x: ${Math.round(player.targetTick.position.x)}, y: ${Math.round(player.targetTick.position.y)}
  partyId: ${Math.round(player.targetTick.partyId)}
  timeDead: ${msToTime(player.targetTick.timeDead)}
                    ${player.targetTick.isPaused ? "On Timeout" : ""}





`;
                    player.targetTick.name = game.renderer.npcs.attachments[i].targetTick.info;
                }
                if (!getRss && player.targetTick.oldName) {
                    player.targetTick.info = player.targetTick.oldName;
                    player.targetTick.name = game.renderer.npcs.attachments[i].targetTick.info;
                    player.targetTick.oldName = null;
                }
                if (getRss) {
                    if (player.targetTick.oldGold !== gold_1 || player.targetTick.oldWood !== wood_1 || player.targetTick.oldStone !== stone_1 || player.targetTick.oldToken !== token_1 || player.targetTick.oldPX !== px_1 || player.targetTick.oldPY !== py_1) {
                        player.targetTick.oldWood = wood_1;
                        player.targetTick.oldStone = stone_1;
                        player.targetTick.oldGold = gold_1;
                        player.targetTick.oldToken = token_1;
                        player.targetTick.oldPX = px_1;
                        player.targetTick.oldPY = py_1;
                        player.targetTick.info = `
  ${player.targetTick.oldName}; score: ${player.targetTick.score.toLocaleString()}
  UID: ${player.targetTick.uid}
  W: ${wood_1}, S: ${stone_1}, G: ${gold_1}, T: ${token_1}
  x: ${Math.round(player.targetTick.position.x)}, y: ${Math.round(player.targetTick.position.y)}
  partyId: ${Math.round(player.targetTick.partyId)}
  timeDead: ${msToTime(player.targetTick.timeDead)}
                    ${player.targetTick.isPaused ? "On Timeout" : ""}





`;
                        player.targetTick.name = game.renderer.npcs.attachments[i].targetTick.info;
                    }
                }
            }
        }
    }

    if (!getRss) {
        allowed1 = false;
    }
});

   let yaw
   let lockedYaw
   let shouldSpin = false
   let shouldClearChat = false
   let shouldSpamIdParty = false
   let shouldSpamAllParty = false
   let shouldLockYaw = false
   let autoSwing = false
   let shouldBotMode = false
   let botTimeout = false
   let shouldAHRC = false
   let shouldAutoAim = false
   let stash10leave = false
   let shouldAutoHealPet = true
   let healPetTimeout = false
   let shouldAutoRevivePet = true
   let shouldAutoEvolvePet = true
   let shouldAutoHealPlayer = true
   let playerHealTimeout = false
   let petSpawned = false
   let isSellingWalls = false
   let isSellingDoors = false
   let isSellingHarvs = false
   let isSellingTraps = false
   let isSellingArrows = false
   let isSellingCannons = false
   let isSellingMelees = false
   let isSellingMages = false
   let isSellingBombs = false
   let isSellingMines = false

    game.network.sendRpc2 = game.network.sendRpc;

if (!window.baseSave) {
    window.baseSave = '[]';
};

let buildingsByPos = new Map();

window.saveBase = () => {
    let stash = GetGoldStash();

    if (stash == undefined) return;;

    let stashPosition = {
        x: stash.x,
        y: stash.y
    };

    let parsedSavedStorage = [];

    for (let i in game.ui.buildings) {
        let building = game.ui.buildings[i];

        parsedSavedStorage.push({
            buildingType: building.type,
            stashOffsetX: stash.x - building.x,
            stashOffsetY: stash.y - building.y,
            lastTier: building.tier
        });
    };

    window.baseSave = JSON.stringify(parsedSavedStorage);
};

window.buildBase = () => {
    let stash = GetGoldStash();

    if (stash == undefined) return;;

    let stashPosition = {
        x: stash.x,
        y: stash.y
    };

    let parsedSavedStorage = window.baseSave;

    if (parsedSavedStorage) {
        parsedSavedStorage = JSON.parse(window.baseSave);

        for (let i of parsedSavedStorage) {
            game.network.sendRpc2({
                name: "MakeBuilding",
                type: i.buildingType,
                x: Math.round(parseInt(stash.x) - i.stashOffsetX),
                y: Math.round(parseInt(stash.y) - i.stashOffsetY),
                yaw: 0
            });
        };
    };
};

window.toggleRebuilder = () => {
    let parsedSavedStorage = window.baseSave;

    if (parsedSavedStorage) {
        parsedSavedStorage = JSON.parse(window.baseSave);

        buildingsByPos = new Map();

        for (let i of parsedSavedStorage) {
            buildingsByPos.set(`${i.stashOffsetX}, ${i.stashOffsetY}`, i);
        };

        if (!window.rebuilderInterval) {
            window.saveBase();

            window.rebuilderInterval = setInterval(() => {
                window.buildBase();

                let buildingsArr = Object.values(game.ui.buildings);

                let stash = buildingsArr[0];

                stash && buildingsArr.forEach(e => {
                    let building = buildingsByPos.get(`${stash.x - e.x}, ${stash.y - e.y}`);

                    if (building && e.tier < building.lastTier) {
                        game.network.sendRpc2({
                            name: "UpgradeBuilding",
                            uid: e.uid
                        });
                    };
                });
            }, 350);
        } else {
            window.rebuilderInterval = clearInterval(window.rebuilderInterval);
        };
    } else return;
};

   game.network.addEntityUpdateHandler((data) => {
      if (game.world.inWorld && game.network.connected) {
         let myPet = game.world.entities[game.ui.playerTick?.petUid]?.fromTick;
         let petHealth = (myPet?.health / myPet?.maxHealth) * 100;
         let myPlayer = game.world.entities[game.ui.playerTick?.uid]?.fromTick;
         let playerHealth = (myPlayer?.health / myPlayer?.maxHealth) * 100;

         if (game.ui.playerTick?.petUid != 0 && game.ui.playerTick?.petUid != undefined) petSpawned = true;
         if (shouldAutoHealPet && petHealth < document.getElementById("healpetinput").value && petHealth > 0 && game.ui.playerTick.gold >= 100 && !healPetTimeout) {
            shopShortcut("PetHealthPotion", 1)
            healPetTimeout = true;
            setTimeout(() => {
               healPetTimeout = false;
            }, 300);

         }
         if (shouldAutoEvolvePet && petHealth > 0 && game.world.entities[game.ui.playerTick?.uid]?.fromTick?.health > 0) {
            let model = game.world.entities[game.ui.playerTick?.petUid]?.fromTick?.model
            let tokens = document.querySelectorAll(".hud-shop-item-tokens")
            let pToken = game.ui.playerTick.token
            let evolvebtn = document.querySelectorAll(".hud-shop-actions-evolve")
            if (!evolvebtn[0].classList[1] && pToken >= tokens[0].innerHTML && model == "PetCARL") {
               buyItem("PetCARL", getPetTier(5))
            }
            if (!evolvebtn[1].classList[1] && pToken >= tokens[1].innerHTML && model == "PetMiner") {
               buyItem("PetMiner", getPetTier(6))
            }
         }
         if (petSpawned == true && shouldAutoRevivePet && !game.world.entities[game.ui.playerTick?.petUid] && playerHealth > 0) {
            shopShortcut("PetRevive", 1)
         }
         if (playerHealth > 0 && game.ui.playerTick.gold >= 100 && shouldAutoHealPlayer) {
            BuyOnly("HealthPotion", 1)
         }
         if (playerHealth <= document.getElementById("healplayerinput").value && playerHealth > 0 && game.ui.playerTick.gold >= 100 && shouldAutoHealPlayer && !playerHealTimeout) {
            EquipOnly("HealthPotion", 1)
            playerHealTimeout = true;
            setTimeout(() => {
               playerHealTimeout = false;
            }, 300)
         }
         if (shouldAHRC) {
             let entities = Game.currentGame.world.entities;
             for (let uid in entities) {
                let obj = entities[uid];
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 1) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.175 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 2) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.250 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 3) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.4 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 4) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.5 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 5) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.585 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 6) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.655 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 7) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 0.9 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester" && obj.fromTick.tier == 8) {
                     game.network.sendRpc({ name: "AddDepositToHarvester", uid: obj.fromTick.uid, deposit: 1.1 });
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
                 if (obj.fromTick.model == "Harvester") {
                     game.network.sendRpc({ name: "CollectHarvester", uid: obj.fromTick.uid });
                 }
             }
         }
         if (moving) {
            findClosestPlayerToFollow();
         }
         if (shouldAutoAim) {
             window.targets = [];
             let entities = game.renderer.npcs.attachments;
             let aimOptions = document.getElementById('aimOptions').value;

             let players = [];
             let zombies = [];

             for (let i in entities) {
                 if (entities[i].fromTick.model == "GamePlayer" && entities[i].fromTick.uid !== game.ui.playerTick.uid && entities[i].targetTick.partyId !== game.ui.playerPartyId && entities[i].fromTick.dead === 0) {
                     players.push(entities[i].fromTick);
                 } else if (entities[i].fromTick.model !== "GamePlayer" && entities[i].entityClass !== "Projectile") {
                     zombies.push(entities[i].fromTick);
                 }
             }

    if (aimOptions === 'pl') {
        window.targets = players.length > 0 ? players : zombies;
    } else if (aimOptions === 'zo') {
        window.targets = zombies.length > 0 ? zombies : players;
    }

    if (window.targets.length > 0) {
        const myPos = game.ui.playerTick.position;
        window.targets.sort((a, b) => {
            return measureDistance(myPos, a.position) - measureDistance(myPos, b.position);
        });

        const target = window.targets[0];
        let reversedAim = game.inputPacketCreator.screenToYaw((target.position.x - myPos.x) * 100, (target.position.y - myPos.y) * 100);
        game.inputPacketCreator.lastAnyYaw = reversedAim;
        game.network.sendPacket(3, { mouseMoved: reversedAim });
    }
};
         if (autoSwing) {
            game.network.sendInput({ space: 0 })
            game.network.sendInput({ space: 1 })
         }
         if (shouldLockYaw && game.ui.playerTick?.aimingYaw != lockedYaw) {
            game.inputPacketCreator.lastAnyYaw = lockedYaw;
            game.network.sendPacket(3, { mouseMoved: lockedYaw });
         }
         if (isSellingWalls) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "Wall") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingDoors) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "Door") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingTraps) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "SlowTrap") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingArrows) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "ArrowTower") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingHarvs) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "Harvester") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingCannons) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "CannonTower") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingMages) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "MagicTower") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingMelees) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "MeleeTower") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingBombs) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "BombTower") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (isSellingMines) {
            for (let i of Object.values(game.ui.buildings)) {
               if (Object.values(i)[2] == "GoldMine") {
                  sellUid.push(Object.values(i)[4])
               }
            }
            uniqueSellUid = [...new Set([...uniqueSellUid, ...sellUid])]
            sellUid = []
            let sellInterval = setInterval(() => {
               if (uniqueSellUid.length > 0 && game.ui.playerPartyCanSell) {
                  game.network.sendRpc({
                     name: "DeleteBuilding",
                     uid: parseInt(uniqueSellUid[Math.floor(Math.random() * uniqueSellUid.length)])
                  })
               } else {
                  clearInterval(sellInterval)
               }
            }, 50);
         }
         if (stash10leave) {
           let stash = getGoldStash()
           let stashhealth = (stash.fromTick.health / stash.fromTick.maxHealth) * 100;
               if (stashhealth <= 10) {
                Game.currentGame.network.sendRpc({
                    name: "LeaveParty"
                })
               }
         }
         if (shouldBotMode && botTimeout == false) {
            botTimeout = true
            move(['Up', 'Down', 'Left', 'Right', 'UpRight', 'UpLeft', 'DownRight', 'DownLeft'][Math.floor(Math.random() * 8)])
            setTimeout(() => {
               botTimeout = false
            }, 1000);
         }
         if (shouldSpamAllParty) {
            let joinablePartyId = []
            let allparty = Object.values(game.ui.getParties())
            for (let party of allparty) {
               if (party.isOpen == 1 && party.memberCount < 4 && party.partyId != game.ui.getPlayerPartyId()) joinablePartyId.push(party.partyId)
            }
            if (joinablePartyId.length > 0) game.network.sendRpc({ name: 'JoinParty', partyId: joinablePartyId[Math.floor(Math.random() * joinablePartyId.length)] })
         }
         if (shouldSpin) {
            game.inputPacketCreator.lastAnyYaw = yaw;
            game.network.sendPacket(3, { mouseMoved: yaw });
            yaw += 10
            if (yaw >= 360) yaw -= 360
         }
         if (shouldSpamIdParty && document.querySelector("#party-id-input").value != '') game.network.sendRpc({ name: "JoinParty", partyId: parseInt(document.querySelector("#party-id-input").value) })
         if (shouldClearChat) {
             for (let i = 0; i < document.getElementsByClassName('hud-chat-message').length; i++) {
                    document.getElementsByClassName('hud-chat-message')[i].remove();
                };
         }
      }
   })

   let mousePs = {};
   let should3x3Walls = false;
   let should5x5Walls = false;
   let should7x7Walls = false;
   let should9x9Walls = false;

    let isMoving = false; // Flag to control whether movement is active

addEventListener('keydown', function (e) {
    if (document.activeElement.tagName.toLowerCase() !== "input" && document.activeElement.tagName.toLowerCase() !== "textarea") {
        if (e.key == "i" && !isMoving) {
            isMoving = true;
            document.addEventListener('mousemove', clickHandler);
        }
    }
});

addEventListener('keyup', function (e) {
    if (e.key == "i") {
        isMoving = false;
        document.removeEventListener('mousemove', clickHandler);
    }
});

function clickHandler(e) {
    mousePs = { x: e.clientX, y: e.clientY };
    var worldPos = game.renderer.screenToWorld(mousePs.x, mousePs.y);
    mapmoveunstoppable(worldPos.x, worldPos.y);
}

   addEventListener('keydown', function (e) {
      if (document.activeElement.tagName.toLowerCase() !== "input" && document.activeElement.tagName.toLowerCase() !== "textarea") {
        if (e.keyCode == 189) { // key -
            getRss = !getRss;
        }
         if (e.key == "g") {
             game.ui.components.PlacementOverlay.startPlacing("GoldStash");
         }
         if (e.key == "z" && !should3x3Walls) {
            game.ui.getComponent("PopupOverlay").showHint('3x3 Walls On', 1000)
            should3x3Walls = true;
            should5x5Walls = false;
            should7x7Walls = false;
            should9x9Walls = false;
         }
         if (e.key == "x" && !should5x5Walls) {
            game.ui.getComponent("PopupOverlay").showHint('5x5 Walls On', 1000)
            should3x3Walls = false;
            should5x5Walls = true;
            should7x7Walls = false;
            should9x9Walls = false;
         }
         if (e.key == "c" && !should7x7Walls) {
            game.ui.getComponent("PopupOverlay").showHint('7x7 Walls On', 1000)
            should3x3Walls = false;
            should5x5Walls = false;
            should7x7Walls = true;
            should9x9Walls = false;
         }
         if (e.key == "v" && !should9x9Walls) {
            game.ui.getComponent("PopupOverlay").showHint('9x9 Walls On', 1000)
            should3x3Walls = false;
            should5x5Walls = false;
            should7x7Walls = false;
            should9x9Walls = true;
         }
      }
   })

   addEventListener('keyup', function (e) {
      if (document.activeElement.tagName.toLowerCase() !== "input" && document.activeElement.tagName.toLowerCase() !== "textarea") {
         if (e.key == "z") {
            should3x3Walls = false;
         }
         if (e.key == "x") {
            should5x5Walls = false;
         }
         if (e.key == "c") {
            should7x7Walls = false;
         }
         if (e.key == "v") {
            should9x9Walls = false;
         }
      }
   })

   function placeWall(x, y) {
      game.network.sendRpc({ name: 'MakeBuilding', x: x, y: y, type: "Wall", yaw: 0 });
   }

   document.addEventListener('mousemove', e => {
      mousePs = { x: e.clientX, y: e.clientY };
      if (game.inputManager.mouseDown && game.ui.components.PlacementOverlay.buildingId == "Wall") {
         var buildingSchema = game.ui.getBuildingSchema();
         var schemaData = buildingSchema.Wall;
         var world = game.world;
         var worldPos = game.renderer.screenToWorld(mousePs.x, mousePs.y);
         var cellIndexes = world.entityGrid.getCellIndexes(worldPos.x, worldPos.y, { width: schemaData.gridWidth, height: schemaData.gridHeight });
         var cellSize = world.entityGrid.getCellSize();
         var cellAverages = { x: 0, y: 0 };
         for (var i in cellIndexes) {
            if (!cellIndexes[i]) {
               return false;
            }
            var cellPos = world.entityGrid.getCellCoords(cellIndexes[i]);
            cellAverages.x += cellPos.x;
            cellAverages.y += cellPos.y;
         }
         cellAverages.x = cellAverages.x / cellIndexes.length;
         cellAverages.y = cellAverages.y / cellIndexes.length;
         var gridPos = {
            x: cellAverages.x * cellSize + cellSize / 2,
            y: cellAverages.y * cellSize + cellSize / 2
         };
         if (should3x3Walls) {
            //layer 1
            placeWall(gridPos.x - 48, gridPos.y + 48);
            placeWall(gridPos.x, gridPos.y + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48);
            //layer 2
            placeWall(gridPos.x - 48, gridPos.y);
            placeWall(gridPos.x, gridPos.y);
            placeWall(gridPos.x + 48, gridPos.y);
            //layer 3
            placeWall(gridPos.x - 48, gridPos.y - 48);
            placeWall(gridPos.x, gridPos.y - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48);
         }
         if (should5x5Walls) {
            //layer 1
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48);
            //layer 2
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48);
            placeWall(gridPos.x, gridPos.y + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48);
            //layer 3
            placeWall(gridPos.x - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48, gridPos.y);
            placeWall(gridPos.x, gridPos.y);
            placeWall(gridPos.x + 48, gridPos.y);
            placeWall(gridPos.x + 48 + 48, gridPos.y);
            //layer 4
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48);
            placeWall(gridPos.x, gridPos.y - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48);
            //layer 5
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48);
         }
         if (should7x7Walls) {
            //layer 1
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48 + 48 + 48);
            //layer 2
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48 + 48);
            //layer 3
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48);
            placeWall(gridPos.x, gridPos.y + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48);
            //layer 4
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48, gridPos.y);
            placeWall(gridPos.x, gridPos.y);
            placeWall(gridPos.x + 48, gridPos.y);
            placeWall(gridPos.x + 48 + 48, gridPos.y);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y);
            //layer 5
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48);
            placeWall(gridPos.x, gridPos.y - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48);
            //layer 6
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48 - 48);
            //layer 7
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48 - 48 - 48);
         }
         if (should9x9Walls) {
            //layer 1
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48 + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y + 48 + 48 + 48 + 48);
            //layer 2
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48 + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y + 48 + 48 + 48);
            //layer 3
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48 + 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y + 48 + 48);
            //layer 4
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y + 48);
            placeWall(gridPos.x - 48, gridPos.y + 48);
            placeWall(gridPos.x, gridPos.y + 48);
            placeWall(gridPos.x + 48, gridPos.y + 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y + 48)
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y + 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y + 48);
            //layer 5
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48 - 48, gridPos.y);
            placeWall(gridPos.x - 48, gridPos.y);
            placeWall(gridPos.x, gridPos.y);
            placeWall(gridPos.x + 48, gridPos.y);
            placeWall(gridPos.x + 48 + 48, gridPos.y)
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y);
            //layer 6
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48);
            placeWall(gridPos.x, gridPos.y - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48)
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y - 48);
            //layer 7
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y - 48 - 48);
            //layer 8
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y - 48 - 48 - 48);
            //layer 9
            placeWall(gridPos.x - 48 - 48 - 48 - 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x - 48 - 48 - 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x - 48 - 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x - 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x + 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48, gridPos.y - 48 - 48 - 48 - 48);
            placeWall(gridPos.x + 48 + 48 + 48 + 48, gridPos.y - 48 - 48 - 48 - 48);
         }
      }
   })

   let dimension = 1;
   const onWindowResize = () => {
      if (document.querySelector("#hud-menu-settings").style.display == "none") {
         const renderer = Game.currentGame.renderer;
         let canvasWidth = window.innerWidth * window.devicePixelRatio;
         let canvasHeight = window.innerHeight * window.devicePixelRatio;
         let ratio = canvasHeight / (1080 * dimension);
         renderer.scale = ratio;
         renderer.entities.setScale(ratio);
         renderer.ui.setScale(ratio);
         renderer.renderer.resize(canvasWidth, canvasHeight);
         renderer.viewport.width = renderer.renderer.width / renderer.scale + 2 * renderer.viewportPadding;
         renderer.viewport.height = renderer.renderer.height / renderer.scale + 2 * renderer.viewportPadding;
      }
   } // Zoom by Apex, modified by eh
   onWindowResize();
   window.onresize = onWindowResize;
   window.onwheel = e => {
      if (e.deltaY > 0) {
         dimension += 0.09;
         onWindowResize();
      } else if (e.deltaY < 0) {
         dimension -= 0.09;
         onWindowResize();
      }
   }

   function measureDistance(obj1, obj2) {
      if (!(obj1.x && obj1.y && obj2.x && obj2.y)) return Infinity;
      let xDif = obj2.x - obj1.x;
      let yDif = obj2.y - obj1.y;
      return Math.abs((xDif ** 2) + (yDif ** 2));
   };

   addEventListener('keyup', function (e) {
      if (document.activeElement.tagName.toLowerCase() !== "input" && document.activeElement.tagName.toLowerCase() !== "textarea") {
         if (e.key == "=") {
            game.ui.getComponent("PopupOverlay").showHint(
               'Press [/] for menu, press [?] to lock angle, type !boss for boss wave, !marker to leave a mark on map, left click somewhere on the minimap to automatically move there, right click minimap to stop map move any time u want, middle click (scroll click) minimap to lock current position (recommended on low ping or it may glitch), HOLD "z" for 3x3 wall, "x" for 5x5, "c" for 7x7, "v" for 9x9, harvesters will be auto upgraded at 20% hp',
               1.5e4
            )
         }
         if (e.key == "/") {
            document.querySelector("#hud-menu-settings")
               .style.display = document.querySelector("#hud-menu-settings")
                  .style.display == "none" ? "block" : "none"
            document.querySelector("#hud-menu-shop")
               .style.display = "none"
            document.querySelector("#hud-menu-party")
               .style.display = "none"
         }
         if (e.key == "`") {
            game.inputManager.onKeyRelease({
               keyCode: 117
            })
         }
         if (e.keyCode == 27) {
            let mb = document.getElementsByClassName("hud")[0];
            if (mb.style.display === "none") {
               mb.style.display = "block";
            } else {
               mb.style.display = "none";
            };
         }
         if (e.key == "?") {
            if (!shouldLockYaw) {
               lockedYaw = game.ui.playerTick.aimingYaw
               shouldLockYaw = true
               game.ui.getComponent("PopupOverlay").showHint('Yaw locked, press [?] to unlock', 1.5e4)
            } else {
               shouldLockYaw = false
               game.ui.getComponent("PopupOverlay").showHint('Yaw unlocked', 1.5e4)
            }
         }
      }
   })

   document.querySelector('#togglebot').addEventListener('click', function () {
      shouldBotMode = !shouldBotMode
      this.innerText = shouldBotMode ? "Bot On" : "Bot Off"
   })
   document.querySelector('#togglespmch').addEventListener('click', function () {
      pauseChatSpam(document.querySelector('#spamchat').value)
      this.innerText = isSpamming ? "Spam Chat On" : "Spam Chat Off"
   })

let goToPosInterval;
let moveTimeout;
let canMoveRandomly = true;
let triedDirections = []; // Keep track of attempted directions

function calculateDirection(x, y) {
  const myX = Math.round(game.ui.playerTick.position.x);
  const myY = Math.round(game.ui.playerTick.position.y);

  // Calculate the difference between current position and destination
  const xDiff = x - myX;
  const yDiff = y - myY;

  // Determine the direction based on the coordinate differences
  if (xDiff === 0 && yDiff === 0) {
    return -1; // No movement needed
  } else if (xDiff > 0 && yDiff === 0) {
    return 1; // Right
  } else if (xDiff < 0 && yDiff === 0) {
    return 0; // Left
  } else if (xDiff === 0 && yDiff > 0) {
    return 3; // Down
  } else if (xDiff === 0 && yDiff < 0) {
    return 2; // Up
  } else if (xDiff > 0 && yDiff > 0) {
    return 7; // Down-right
  } else if (xDiff > 0 && yDiff < 0) {
    return 6; // Up-right
  } else if (xDiff < 0 && yDiff > 0) {
    return 5; // Down-left
  } else if (xDiff < 0 && yDiff < 0) {
    return 4; // Up-left
  } else {
    return -1; // Unknown direction
  }
}

function goToPos(x, y) {
  clearInterval(goToPosInterval);
  goToPosInterval = setInterval(() => {
    const myX = Math.round(game.ui.playerTick.position.x);
    const myY = Math.round(game.ui.playerTick.position.y);
    const offset = document.getElementById("offset").value;
    const distanceDifference = Math.round(calculateDistance(myX, myY, previousCoords.x, previousCoords.y));
    const distanceDifference2 = Math.round(calculateDistance(myX, myY, CoordsCheck.x, CoordsCheck.y));

    if (distanceDifference < 30 && distanceDifference2 < 30) {
      // If the distance is not changing, move in a random direction (if allowed)
      if (canMoveRandomly) {
        canMoveRandomly = false; // Prevent further random movement until timer expires

        // Get the direction based on the current position and destination
        const destinationDirection = calculateDirection(x, y);
        const oppdestinationDirection = -calculateDirection(x, y);

        // Define all possible directions
        const allDirections = [0, 1, 2, 3, 4, 5, 6, 7];

        // Filter out directions that have already been tried or are the same as the destination direction
        const availableDirections = allDirections.filter(
          dir => !triedDirections.includes(dir) && dir !== destinationDirection && dir !== oppdestinationDirection
        );

        let randomDirection;

        if (availableDirections.length === 0) {
          // All directions have been tried, reset and try again
          triedDirections = [];
          randomDirection = Math.floor(Math.random() * 8); // Random direction
        } else {
          // Choose a random direction from the available directions
          randomDirection = availableDirections[Math.floor(Math.random() * availableDirections.length)];
        }

        // Store the selected direction in the list of tried directions
        triedDirections.push(randomDirection);

        // Clear all inputs first
        game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });

        // Translate the random direction to input values
        if (randomDirection === 0) {
          game.network.sendInput({ left: 1 });
        } else if (randomDirection === 1) {
          game.network.sendInput({ right: 1 });
        } else if (randomDirection === 2) {
          game.network.sendInput({ up: 1 });
        } else if (randomDirection === 3) {
          game.network.sendInput({ down: 1 });
        } else if (randomDirection === 4) {
          game.network.sendInput({ left: 1, up: 1 });
        } else if (randomDirection === 5) {
          game.network.sendInput({ left: 1, down: 1 });
        } else if (randomDirection === 6) {
          game.network.sendInput({ right: 1, up: 1 });
        } else if (randomDirection === 7) {
          game.network.sendInput({ right: 1, down: 1 });
        }

        // After 5 seconds, stop the random movement and reset the flag
        setTimeout(() => {
          game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
          canMoveRandomly = true;
        }, 5000);
      }
    }
    if (canMoveRandomly) {
      // Continue with the original movement logic
      if (-myX + x > offset) game.network.sendInput({ left: 0 });
      else game.network.sendInput({ left: 1 });
      if (myX - x > offset) game.network.sendInput({ right: 0 });
      else game.network.sendInput({ right: 1 });
      if (-myY + y > offset) game.network.sendInput({ up: 0 });
      else game.network.sendInput({ up: 1 });
      if (myY - y > offset) game.network.sendInput({ down: 0 });
      else game.network.sendInput({ down: 1 });
    }

    if (distanceDifference < 30 && distanceDifference2 < 30) {
      game.ui.getComponent('PopupOverlay').showHint('Stuck, taking a random step!', 5000);
    }

    if (-myX + x < offset && myX - x < offset && -myY + y < offset && myY - y < offset) {
      game.ui.getComponent('PopupOverlay').showHint('Finished moving!', 10000);
      clearInterval(goToPosInterval);
      clearTimeout(moveTimeout);
    }
  });

  moveTimeout = setTimeout(() => {
    clearInterval(goToPosInterval);
    game.ui.getComponent('PopupOverlay').showHint('It has been 4 minutes to move to the position on the map, so it has automatically stopped to prevent infinite loops.', 8000);
    game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
  }, 240000);
}

    function lockposition(x, y) {
    clearInterval(goToPosInterval);
    goToPosInterval = setInterval(() => {
        let myX = Math.round(game.ui.playerTick.position.x);
        let myY = Math.round(game.ui.playerTick.position.y);

        let offset = document.getElementById("offset").value;

        if (-myX + x > offset) game.network.sendInput({ left: 0 }); else game.network.sendInput({ left: 1 });
        if (myX - x > offset) game.network.sendInput({ right: 0 }); else game.network.sendInput({ right: 1 });

        if (-myY + y > offset) game.network.sendInput({ up: 0 }); else game.network.sendInput({ up: 1 });
        if (myY - y > offset) game.network.sendInput({ down: 0 }); else game.network.sendInput({ down: 1 });

        if (-myX + x < offset && myX - x < offset && -myY + y < offset && myY - y < offset) {
            game.ui.getComponent('PopupOverlay').showHint('Locked position', 1e4);
        }
    })
    }

    function mapmoveunstoppable(x, y) {
    clearInterval(goToPosInterval);
    goToPosInterval = setInterval(() => {
        let myX = Math.round(game.ui.playerTick.position.x);
        let myY = Math.round(game.ui.playerTick.position.y);

        let offset = document.getElementById("offset").value;

        if (-myX + x > offset) game.network.sendInput({ left: 0 }); else game.network.sendInput({ left: 1 });
        if (myX - x > offset) game.network.sendInput({ right: 0 }); else game.network.sendInput({ right: 1 });

        if (-myY + y > offset) game.network.sendInput({ up: 0 }); else game.network.sendInput({ up: 1 });
        if (myY - y > offset) game.network.sendInput({ down: 0 }); else game.network.sendInput({ down: 1 });

        if (-myX + x < offset && myX - x < offset && -myY + y < offset && myY - y < offset) {
            game.ui.getComponent('PopupOverlay').showHint('Finished moving!', 1e4);
            clearInterval(goToPosInterval);
            clearTimeout(moveTimeout);
        }
    });
    }

let mapContainer = document.createElement('div');
mapContainer.id = "hud-map-container";
document.querySelector('.hud-bottom-left').append(mapContainer);
$('#hud-map').appendTo(document.querySelector('#hud-map-container'));

document.querySelector("#hud-map-container").addEventListener('click', (e) => {
    let offset = $('#hud-map-container').offset();
    let mapMouseX = e.pageX - offset.left;
    let mapMouseY = e.pageY - offset.top;
    game.ui.getComponent('PopupOverlay').showConfirmation(`Are you sure you want to move to X: ${Math.round(mapMouseX * 171.42857142857)}, Y: ${Math.round(mapMouseY * 171.42857142857)}? You can right-click the minimap to cancel.`, 7500, () => {
        game.ui.getComponent('PopupOverlay').showHint('Starting MapMove...', 4000);
        goToPos(mapMouseX * 171.42857142857, mapMouseY * 171.42857142857);
    }, () => {
        game.ui.getComponent('PopupOverlay').showHint('OK, did not start MapMove', 4000);
    });
});

document.querySelector('#hud-map-container').addEventListener('contextmenu', () => {
    game.ui.getComponent('PopupOverlay').showConfirmation('Are you sure you want to cancel the current MapMove process?', 7500, () => {
        clearInterval(goToPosInterval);
        clearTimeout(moveTimeout);
        game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
        game.ui.getComponent('PopupOverlay').showHint('Successfully stopped MapMover.', 4000);
    }, () => {
        game.ui.getComponent('PopupOverlay').showHint('OK, did not stop MapMover.', 4000);
    });
});

document.querySelector("#hud-map-container").addEventListener('mousedown', (e) => {
    if (e.button === 1) {
        lockposition(Math.round(game.ui.playerTick.position.x), Math.round(game.ui.playerTick.position.y))
    }
});

let markerIds = 0; // Initialize marker IDs
let maxMarkers = 69420; // Maximum number of markers
let markers = []; // Array to store marker positions and IDs
let goToMarkerInterval;
let repeatingMoveInterval;
let currentIndex = 0; // Initialize current marker index
let markermoveTimeout;

function addMarker(x, y) {
    if (markerIds >= maxMarkers) {
        // Max number of markers reached, show a pop-up
        game.ui.getComponent('PopupOverlay').showHint('Max number of markers reached.', 1500);
    } else {
        markerIds++;
        // Add marker to the array with its position and ID
        markers.push({ id: markerIds, x, y });

        var map = document.getElementById("hud-map");
        // Add a specific class to markers created by !marker and include their IDs
        map.insertAdjacentHTML("beforeend", `<div data-marker-id="${markerIds}" style="color: red; display: block; left: ${x}px; top: ${y}px; position: absolute;" class='hud-map-player marker-placed-by-command'></div>`);
        game.ui.getComponent('PopupOverlay').showHint(`Added Marker ${markerIds}`, 1500);
    }
}

function resetMarkerIds() {
    markerIds = 0;
    markers = [];

    // Show a hint that marker IDs were reset
    game.ui.getComponent('PopupOverlay').showHint('Marker IDs reset.', 1500);
}

function moveToNextMarker() {
    if (markers.length === 0) {
        game.ui.getComponent('PopupOverlay').showHint('No markers placed.', 1500);
        return;
    }

    // Move to the next marker in a circular manner
    currentIndex = (currentIndex + 1) % markers.length;

    const marker = markers[currentIndex];

    if (marker) {
        goToMarkerPos(marker.x, marker.y);
    }
}

function startRepeatingMove() {
    if (markers.length === 0) {
        game.ui.getComponent('PopupOverlay').showHint('No markers placed.', 1500);
        return;
    }

    repeatingMoveInterval = setInterval(() => {
        moveToNextMarker();
    }, 100);
}

function stopRepeatingMove() {
        clearInterval(goToMarkerInterval);
        clearTimeout(markermoveTimeout);
        game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
        game.ui.getComponent('PopupOverlay').showHint('Successfully stopped MapMover.', 4000);
}

// Handle the "markermove" command
function handleMarkerMove() {
    // Stop any ongoing repeating move process
    stopRepeatingMove();

    // Move to the first marker immediately
    currentIndex = 0;
    moveToNextMarker();
}

// Register chat command handler
game.network.addRpcHandler('ReceiveChatMessage', function (e) {
    if (e.uid == game.ui.playerTick.uid) {
    const message = e.message.trim();

    if (message === "!markers") {
        addMarker(game.ui.playerTick.position.x, game.ui.playerTick.position.y);
    } else if (message === "!delmarkers") {
        // Get all marker elements with the class 'marker-placed-by-command'
        const markerElements = document.querySelectorAll('.marker-placed-by-command');

        // Loop through and remove only markers created by !
        markerElements.forEach(markerElement => {
            // Check if the marker element has a data-marker-id attribute
            const markerId = markerElement.getAttribute("data-marker-id");
            if (markerId) {
                // Remove the marker only if its ID matches a marker in the array
                const idToRemove = parseInt(markerId);
                const indexToRemove = markers.findIndex(m => m.id === idToRemove);
                if (indexToRemove !== -1) {
                    markers.splice(indexToRemove, 1);
                    markerElement.remove();
                }
            }
        });

        // Show a hint that markers were deleted
        game.ui.getComponent('PopupOverlay').showHint('Deleted Markers', 1500);
        // Reset marker IDs
        resetMarkerIds();
    } else if (message === "!markermove") {
        // Handle the "markermove" command
        handleMarkerMove();
    } else if (message === "!stop") {
        // Stop repeating move
        stopRepeatingMove();
    }
    }
});

function goToMarkerPos(x, y) {
    clearInterval(goToMarkerInterval);
    goToMarkerInterval = setInterval(() => {
        let myX = Math.round(game.ui.playerTick.position.x);
        let myY = Math.round(game.ui.playerTick.position.y);

        let offset = document.getElementById("offset").value;

        if (-myX + x > offset) game.network.sendInput({ left: 0 }); else game.network.sendInput({ left: 1 });
        if (myX - x > offset) game.network.sendInput({ right: 0 }); else game.network.sendInput({ right: 1 });

        if (-myY + y > offset) game.network.sendInput({ up: 0 }); else game.network.sendInput({ up: 1 });
        if (myY - y > offset) game.network.sendInput({ down: 0 }); else game.network.sendInput({ down: 1 });

        if (-myX + x < offset && myX - x < offset && -myY + y < offset && myY - y < offset) {
            game.ui.getComponent('PopupOverlay').showHint('Finished moving!', 1e4);
            clearInterval(goToMarkerInterval);

            // Wait for 1 second before moving to the next marker
            markermoveTimeout = setTimeout(() => {
                moveToNextMarker();
            }, 100);
        }
    });
}
let movePositions = [
    { x: 1200, y: 1200 },
    { x: 22800, y: 1200 },
    { x: 22800, y: 2400 },
    { x: 1200, y: 2400 },
    { x: 1200, y: 3600 },
    { x: 22800, y: 3600 },
    { x: 22800, y: 4800 },
    { x: 1200, y: 4800 },
    { x: 1200, y: 6000 },
    { x: 22800, y: 6000 },
    { x: 22800, y: 7200 },
    { x: 1200, y: 7200 },
    { x: 1200, y: 8400 },
    { x: 22800, y: 8400 },
    { x: 22800, y: 9600 },
    { x: 1200, y: 9600 },
    { x: 1200, y: 10800 },
    { x: 22800, y: 10800 },
    { x: 22800, y: 12000 },
    { x: 1200, y: 12000 },
    { x: 1200, y: 13200 },
    { x: 22800, y: 13200 },
    { x: 22800, y: 14400 },
    { x: 1200, y: 14400 },
    { x: 1200, y: 15600 },
    { x: 22800, y: 15600 },
    { x: 22800, y: 16800 },
    { x: 1200, y: 16800 },
    { x: 1200, y: 18000 },
    { x: 22800, y: 18000 },
    { x: 22800, y: 19200 },
    { x: 1200, y: 19200 },
    { x: 1200, y: 20400 },
    { x: 22800, y: 20400 },
    { x: 22800, y: 21600 },
    { x: 1200, y: 21600 },
    { x: 1200, y: 22800 },
    { x: 22800, y: 22800 }
];

let currentPositionIndex = 0;

// Handle the "scanposition" command
function handleScanPosition() {
    // Stop any ongoing repeating move process
    stopRepeatingMove();

    // Move to the first position immediately
    currentPositionIndex = 0;
    moveToNextPosition();
}

// Register chat command handler
game.network.addRpcHandler('ReceiveChatMessage', function (e) {
    if (e.uid == game.ui.playerTick.uid) {
        const message = e.message.trim();

        if (message === "!scanposition") {
            // Handle the "scanposition" command
            handleScanPosition();
        }
    }
});

function moveToNextPosition() {
    if (currentPositionIndex >= movePositions.length) {
        game.ui.getComponent('PopupOverlay').showHint('Scanning positions completed.', 1500);
        return;
    }

    const position = movePositions[currentPositionIndex];
    goToPosition(position.x, position.y);
    currentPositionIndex++;
}

function goToPosition(x, y) {
    clearInterval(goToMarkerInterval);
    goToMarkerInterval = setInterval(() => {
    const myX = Math.round(game.ui.playerTick.position.x);
    const myY = Math.round(game.ui.playerTick.position.y);
    const offset = document.getElementById("offset").value;
    const distanceDifference = Math.round(calculateDistance(myX, myY, previousCoords.x, previousCoords.y));
    const distanceDifference2 = Math.round(calculateDistance(myX, myY, CoordsCheck.x, CoordsCheck.y));

    if (distanceDifference < 30 && distanceDifference2 < 30) {
      // If the distance is not changing, move in a random direction (if allowed)
      if (canMoveRandomly) {
        canMoveRandomly = false; // Prevent further random movement until timer expires

        // Get the direction based on the current position and destination
        const destinationDirection = calculateDirection(x, y);
        const oppdestinationDirection = -calculateDirection(x, y);

        // Define all possible directions
        const allDirections = [0, 1, 2, 3, 4, 5, 6, 7];

        // Filter out directions that have already been tried or are the same as the destination direction
        const availableDirections = allDirections.filter(
          dir => !triedDirections.includes(dir) && dir !== destinationDirection && dir !== oppdestinationDirection
        );

        let randomDirection;

        if (availableDirections.length === 0) {
          // All directions have been tried, reset and try again
          triedDirections = [];
          randomDirection = Math.floor(Math.random() * 8); // Random direction
        } else {
          // Choose a random direction from the available directions
          randomDirection = availableDirections[Math.floor(Math.random() * availableDirections.length)];
        }

        // Store the selected direction in the list of tried directions
        triedDirections.push(randomDirection);

        // Clear all inputs first
        game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });

        // Translate the random direction to input values
        if (randomDirection === 0) {
          game.network.sendInput({ left: 1 });
        } else if (randomDirection === 1) {
          game.network.sendInput({ right: 1 });
        } else if (randomDirection === 2) {
          game.network.sendInput({ up: 1 });
        } else if (randomDirection === 3) {
          game.network.sendInput({ down: 1 });
        } else if (randomDirection === 4) {
          game.network.sendInput({ left: 1, up: 1 });
        } else if (randomDirection === 5) {
          game.network.sendInput({ left: 1, down: 1 });
        } else if (randomDirection === 6) {
          game.network.sendInput({ right: 1, up: 1 });
        } else if (randomDirection === 7) {
          game.network.sendInput({ right: 1, down: 1 });
        }

        // After 5 seconds, stop the random movement and reset the flag
        setTimeout(() => {
          game.network.sendInput({ left: 0, right: 0, up: 0, down: 0 });
          canMoveRandomly = true;
        }, 5000);
      }
    }
    if (canMoveRandomly) {
      // Continue with the original movement logic
      if (-myX + x > offset) game.network.sendInput({ left: 0 });
      else game.network.sendInput({ left: 1 });
      if (myX - x > offset) game.network.sendInput({ right: 0 });
      else game.network.sendInput({ right: 1 });
      if (-myY + y > offset) game.network.sendInput({ up: 0 });
      else game.network.sendInput({ up: 1 });
      if (myY - y > offset) game.network.sendInput({ down: 0 });
      else game.network.sendInput({ down: 1 });
    }

    if (distanceDifference < 30 && distanceDifference2 < 30) {
      game.ui.getComponent('PopupOverlay').showHint('Stuck, taking a random step!', 5000);
    }

        if (-myX + x < offset && myX - x < offset && -myY + y < offset && myY - y < offset) {
            game.ui.getComponent('PopupOverlay').showHint('Reached destination!', 1000);
            clearInterval(goToMarkerInterval);

            // Wait for 1 second before moving to the next position
            setTimeout(() => {
                moveToNextPosition();
            }, 100);
        }
    }, 10);
}
const minimap = document.getElementById("hud-map");
let lastPlayerTickDead = 0;

const isBuildingOffset = offset => (offset % 48) ? ~~(0 <= (offset % 200) && (offset % 200) <= 16) : ~~(0 <= (offset % 200) && (offset % 200) <= 40);

const isInRange = (p1, p2) => {
  const deltaX = ~~(p2.x / 200) - ~~(p1.x / 200);
  const deltaY = ~~(p2.y / 200) - (~~((p1.y + 100) / 200) - 0.5);
  return -5 <= deltaX && -3.5 <= deltaY && deltaX <= 5 + isBuildingOffset(p2.x) && deltaY <= 3.5 + isBuildingOffset(p2.y);
};

game.world.removeEntity2 = game.world.removeEntity;
game.world.removeEntity = uid => {
  if (!game.world.entities[uid]) return;
  const model = game.world.entities[uid].targetTick.model;
  const pp = game.ui.playerTick.position;
  const ep = game.world.entities[uid].targetTick.position;
  if (["Tree", "Stone", "NeutralCamp"].includes(model) && !game.world.replicator.currentTick.entities[uid]) {
    if (game.world.entities[uid].node.alpha != 0.5) game.world.entities[uid].setAlpha(0.5);
    return;
  };
  if (game.ui.buildingSchema[model]) {
    if (!isInRange(pp, ep) && !game.world.replicator.currentTick.entities[uid]) {
      if (game.world.entities[uid].node.alpha != 0.5) game.world.entities[uid].setAlpha(0.5);
      return;
    } else {
      if (lastPlayerTickDead == game.world.entities[game.world.myUid].targetTick.dead) {
        const entityDiv = document.querySelector(`[uid="${uid}"]`);
        minimap.removeChild(entityDiv);
      }
    }
  };
  game.world.removeEntity2(uid);
};

game.world.createEntity2 = game.world.createEntity;
game.world.createEntity = entity => {
  if (["Tree", "Stone", "NeutralCamp"].includes(entity.model)) {
    const entityDiv = document.createElement("div");
    entityDiv.classList.add("hud-map-building");
    entityDiv.style.background = ({ Tree: "green", Stone: "grey", NeutralCamp: "red" })[entity.model];
    entityDiv.style.left = `${entity.position.x / 24000 * 100}%`;
    entityDiv.style.top = `${entity.position.y / 24000 * 100}%`;
    entityDiv.style.display = "block";
    minimap.appendChild(entityDiv);
  };
  if (game.ui.buildingSchema[entity.model]) {
    const entityDiv = document.createElement("div");
    entityDiv.classList.add("hud-map-building");
    entityDiv.setAttribute('uid', `${entity.uid}`);
    entityDiv.style.left = `${entity.position.x / 24000 * 100}%`;
    entityDiv.style.top = `${entity.position.y / 24000 * 100}%`;
    entityDiv.style.display = "block";
    minimap.appendChild(entityDiv);
  };
  game.world.createEntity2(entity);
};

game.network.addEntityUpdateHandler(data => {
  for (const uid in data.entities) {
    if (game.world.entities[uid] && game.world.replicator.currentTick && game.world.replicator.currentTick.entities[uid]) {
      if (game.world.entities[uid].node.alpha != 1) game.world.entities[uid].setAlpha(1);
    }
  }
  if (data.entities[game.world.myUid].dead !== undefined) {
    lastPlayerTickDead = data.entities[game.world.myUid].dead;
  }
});

    game.network.sendRpc = (e) => {
      if (e.name === "SendChatMessage") {
        e.message = sendChatMessageWithReplacements(e.message);
      }
     game.network.sendRpc2(e);
    };

    function sendChatMessageWithReplacements(message) {
      const replacedMessage = message.replaceAll('fuck', '&#102&#117&#99&#107')
                .replaceAll('FUCK', '&#70&#85&#67&#75')
                .replaceAll('shit', '&#115&#104&#105&#116')
                .replaceAll('SHIT', '&#83&#72&#73&#84')
                .replaceAll('bitch', '&#98&#105&#116&#99&#104')
                .replaceAll('BITCH', '&#66&#73&#84&#67&#72')
                .replaceAll('ass', '&#97&#115&#115')
                .replaceAll('ASS', '&#65&#83&#83')
                .replaceAll('dick', '&#100&#105&#99&#107')
                .replaceAll('DICK', "&#68&#73&#67&#75")
                .replaceAll('nigg', "&#110&#105&#103&#103")
                .replaceAll('niga', "&#110&#105&#103&#97")
                .replaceAll('nig', "&#110&#105&#103")
                .replaceAll('nigge', "&#110&#105&#103&#103&#101")
                .replaceAll('NIGGA', "&#78&#73&#71&#71&#65")
                .replaceAll('NIGGER', "&#78&#73&#71&#69&#65")
      return replacedMessage;
    }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址