yolkbot 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bot.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /* eslint-disable */
2
2
 
3
- import{createAccount as z,loginAnonymously as H,loginWithCredentials as W,loginWithRefreshToken as j,queryServices as g}from"./api.js";import s from"./comm/CommIn.js";import f from"./comm/CommOut.js";import{CloseCode as K}from"./comm/Codes.js";import{CommCode as c}from"./constants/codes.js";import U from"./bot/GamePlayer.js";import q from"./matchmaker.js";import Y from"./socket.js";import{ChiknWinnerDailyLimit as Z,CollectTypes as T,CoopStates as y,findItemById as d,FramesBetweenSyncs as w,GameActions as E,GameModes as u,GameOptionFlags as G,GunList as X,ItemTypes as V,Movements as F,PlayTypes as J,ProxiesEnabled as Q,ShellStreaks as m,StateBufferSize as b}from"./constants/index.js";import R from"./dispatches/LookAtPosDispatch.js";import M from"./dispatches/MovementDispatch.js";import{NodeList as tt}from"./pathing/mapnode.js";import{fetchMap as et,initKotcZones as st}from"./util.js";import{Challenges as at}from"./constants/challenges.js";import{Maps as S}from"./constants/maps.js";const B=Object.fromEntries(Object.entries(y).map(([P,t])=>[t,P])),A=Object.fromEntries(Object.entries(u).map(([P,t])=>[t,P])),O={CHALLENGES:1,STATS:2,PATHFINDING:3,PING:5,COSMETIC_DATA:6,PLAYER_HEALTH:7,PACKET_HOOK:8,LOG_PACKETS:10,NO_LOGIN:11,DEBUG_BUFFER:12,DEBUG_BEST_TARGET:14},x=(P,t)=>(P%t+t)%t;class it{static Intents=O;Intents=O;#e=[];#t={};#i=[];#n;#o;constructor(t={}){if(t.proxy&&!Q)throw new Error("proxies do not work and hence are not supported in the browser");this.intents=t.intents||[],this.instance=t.instance||"shellshock.io",this.protocol=t.protocol||"wss",this.proxy=t.proxy||"",this.state={name:"yolkbot",weaponIdx:0,reloading:!1,swappingGun:!1,usingMelee:!1,stateIdx:0,serverStateIdx:0,shotsFired:0,buffer:[],left:!1,quit:!1},this.players={},this.me=new U({}),this.game={raw:{},code:"",socket:null,gameModeId:0,gameMode:A[0],mapIdx:0,map:{filename:"",hash:"",name:"",modes:{FFA:!1,Teams:!1,Spatula:!1,King:!1},availability:"both",numPlayers:"18",raw:{},nodes:{},zones:[]},playerLimit:0,isGameOwner:!1,isPrivate:!0,options:{gravity:1,damage:1,healthRegen:1,locked:!1,noTeamChange:!1,noTeamShuffle:!1,weaponsDisabled:Array(7).fill(!1),mustUseSecondary:!1},collectables:[[],[]],teamScore:[0,0,0],spatula:{coords:{x:0,y:0,z:0},controlledBy:0,controlledByTeam:0},stage:y.capturing,zoneNumber:0,activeZone:[],capturing:0,captureProgress:0,numCapturing:0,stageName:"",capturePercent:0},this.#o=this.game,this.account={id:0,firebaseId:"",sessionId:"",session:"",email:"",password:"",cw:{atLimit:!1,limit:0,secondsUntilPlay:0,canPlayAgain:Date.now()},loadout:{hatId:null,meleeId:0,stampId:null,classIdx:0,colorIdx:0,grenadeId:0,primaryId:[3100,3600,3400,3800,4e3,4200,4500],secondaryId:new Array(7).fill(3e3),stampPositionX:0,stampPositionY:0},ownedItemIds:[],vip:!1,accountAge:0,emailVerified:!1,eggBalance:0,rawLoginData:{}},this.#n=this.account,this.matchmaker=null,this.ping=0,this.lastPingTime=-1,this.lastDeathTime=-1,this.lastChatTime=-1,this.lastUpdateTick=0,this.controlKeys=0,this.pathing={nodeList:null,followingPath:!1,activePath:null,activeNode:null,activeNodeIdx:0}}dispatch(t){t.check(this)?t.execute(this):this.#e.push(t)}async createAccount(t,e){this.account.email=t,this.account.password=e;const a=await z(t,e,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(a)}async login(t,e){this.account.email=t,this.account.password=e;const a=await W(t,e,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(a)}async loginWithRefreshToken(t){const e=await j(t,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(e)}async loginAnonymously(){delete this.account.email,delete this.account.password;const t=await H(this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(t)}async#s(t){return typeof t!="object"?(this.emit("authFail",t),!1):t.banRemaining?(this.emit("banned",t.banRemaining),!1):t.playerOutput?(t=t.playerOutput,this.account.rawLoginData=t,this.account.accountAge=t.accountAge,this.account.eggBalance=t.currentBalance,this.account.emailVerified=t.emailVerified,this.account.firebaseId=t.firebaseId,this.account.id=t.id,this.account.loadout=t.loadout,this.account.ownedItemIds=t.ownedItemIds,this.account.session=t.session,this.account.sessionId=t.sessionId,this.account.vip=t.upgradeProductId&&!t.upgradeIsExpired,this.intents.includes(this.Intents.STATS)&&(this.account.stats={lifetime:t.statsLifetime,monthly:t.statsCurrent}),this.intents.includes(this.Intents.CHALLENGES)&&this.#a(t.challenges),this.emit("authSuccess",this.account),this.account):(this.emit("authFail",t),!1)}#a(t){this.account.challenges=[];for(const e of t){const a=at.find(i=>i.id==e.challengeId);a&&(delete e.playerId,this.account.challenges.push({raw:{challengeInfo:a,challengeData:e},id:e.challengeId,name:a.loc.title,desc:a.loc.desc,rewardEggs:a.reward,isRerolled:!!e.reset,isClaimed:!!e.claimed,isCompleted:!!e.completed,progressNum:e.progress,goalNum:a.goal}))}}async initMatchmaker(){return!this.account.sessionId&&!this.intents.includes(this.Intents.NO_LOGIN)&&!await this.loginAnonymously()?!1:(this.matchmaker||(this.matchmaker=new q({sessionId:this.account.sessionId,proxy:this.proxy,instance:this.instance,protocol:this.protocol,noLogin:this.intents.includes(this.Intents.NO_LOGIN)}),this.matchmaker.on("authFail",t=>this.emit("authFail",t)),await this.matchmaker.getRegions()),!0)}async#c(t){return await this.initMatchmaker()?await new Promise(e=>{const a=i=>{if(i.command=="gameFound"&&(this.matchmaker.off("msg",a),this.game.raw=i,this.game.code=i.id,e()),i.error&&i.error=="gameNotFound")throw new Error(`Game ${t} not found (likely expired).`)};this.matchmaker.on("msg",a),this.matchmaker.send({command:"joinGame",id:t,observe:!1,sessionId:this.account.sessionId})}):!1}async createPrivateGame(t={}){if(!await this.initMatchmaker())return!1;if(!t.region)throw new Error('pass a region: createPrivateGame({ region: "useast", ... })');if(!this.matchmaker.regionList.find(i=>i.id==t.region))throw new Error('invalid region, see <bot>.matchmaker.regionList for a region list (pass an "id")');if(!t.mode)throw new Error('pass a mode: createPrivateGame({ mode: "ffa", ... })');if(u[t.mode]==null)throw new Error("invalid mode, see GameModes for a list");if(!t.map)throw new Error('pass a map: createPrivateGame({ map: "downfall", ... })');const e=S.find(i=>i.name.toLowerCase()==t.map.toLowerCase()),a=S.indexOf(e);if(a==-1)throw new Error("invalid map, see the Maps constant for a list");return await new Promise(i=>{const n=o=>{o.command=="gameFound"&&(this.matchmaker.off("msg",n),this.game.raw=o,this.game.code=this.game.raw.id,i())};this.matchmaker.on("msg",n),this.matchmaker.send({command:"findGame",region:t.region,playType:J.createPrivate,gameType:u[t.mode],sessionId:this.account.sessionId,noobLobby:!1,map:a})}),this.game.raw}async join(t,e){if(this.state.name=t||"yolkbot",typeof e=="string"?(e.includes("#")&&(e=e.split("#")[1]),await this.#c(e)):typeof e=="object"&&(this.account.id==0&&await this.loginAnonymously(),this.game.raw=e,this.game.code=this.game.raw.id),!this.game.raw.id)throw new Error("invalid game data passed to <bot>.join");const a=async()=>{try{const i=this.instance.startsWith("localhost:")?this.instance:`${this.game.raw.subdomain}.${this.instance}`;this.game.socket=new Y(`${this.protocol}://${i}/game/${this.game.raw.id}`,this.proxy),this.game.socket.onerror=async n=>(console.error(n),await new Promise(o=>setTimeout(o,100)),await a())}catch{await new Promise(i=>setTimeout(i,100)),await a()}};await a(),this.game.socket.binaryType="arraybuffer",this.game.socket.onopen=()=>this.game.socket.onerror=null,this.game.socket.onmessage=i=>this.processPacket(i.data),this.game.socket.onclose=i=>{this.state.left?this.state.left=!1:(this.emit("close",i.code),this.leave(-1))}}#r(){if(Object.entries(this.me.position).map(e=>Math.floor(e[1])).join(",")==this.pathing.activePath[this.pathing.activePath.length-1].positionStr)this.pathing.followingPath=!1,this.pathing.activePath=null,this.pathing.activeNode=null,this.pathing.activeNodeIdx=0,this.dispatch(new M(0));else{let e;this.pathing.activeNodeIdx<this.pathing.activePath.length-1?(e=this.pathing.activePath[this.pathing.activeNodeIdx+1].flatCenter(),this.dispatch(new R(e))):(e=this.pathing.activePath[this.pathing.activeNodeIdx].flatCenter(),this.dispatch(new R(e)));for(const a of this.pathing.activePath)if(a.flatRadialDistance(this.me.position)<.1&&a.position.y==Math.floor(this.me.position.y)&&this.pathing.activePath.indexOf(a)>=this.pathing.activeNodeIdx){this.pathing.activeNodeIdx=this.pathing.activePath.indexOf(a)+1,this.pathing.activeNode=this.pathing.activePath[this.pathing.activeNodeIdx];break}this.controlKeys&F.FORWARD||this.dispatch(new M(F.FORWARD))}}update(){if(!this.state.quit){if(this.pathing.followingPath&&this.intents.includes(this.Intents.PATHFINDING)&&this.#r(),this.#e.length>0)for(let t=0;t<this.#e.length;t++){const e=this.#e[t];e.check(this)&&(e.execute(this),this.#e.splice(t,1))}if(this.me.playing){const t=this.state.stateIdx;if(this.intents.includes(this.Intents.DEBUG_BUFFER)&&(console.log("setting buffer for idx",t),console.log("checking...shotsFired",this.state.shotsFired)),this.state.buffer[t]={controlKeys:this.controlKeys,yaw:this.me.view.yaw,pitch:this.me.view.pitch,shotsFired:this.state.shotsFired},this.state.shotsFired=0,this.lastUpdateTick>=2){this.emit("tick");const e=f.getBuffer();e.packInt8(c.syncMe),e.packInt8(this.state.stateIdx),e.packInt8(this.state.serverStateIdx);const a=x(this.state.stateIdx-w+1,b);for(let i=0;i<w;i++){const n=x(a+i,b);this.intents.includes(this.Intents.DEBUG_BUFFER)&&console.log("going with",this.state.stateIdx,a,n,this.state.buffer[n]),e.packInt8(this.state.buffer[n]?.controlKeys||0),e.packInt8(this.state.buffer[n]?.shotsFired||0),e.packRadU(this.state.buffer[n]?.yaw||this.me.view.yaw),e.packRad(this.state.buffer[n]?.pitch||this.me.view.pitch),e.packInt8(100)}e.send(this.game.socket),this.state.buffer=[],this.lastUpdateTick=0}else this.lastUpdateTick++;this.state.stateIdx=x(this.state.stateIdx+1,b)}if(this.intents.includes(this.Intents.PLAYER_HEALTH))for(const t of Object.values(this.players)){if(t.playing&&t.hp>0){const e=.1*(this.game.isPrivate?this.game.options.healthRegen:1);t.streakRewards.includes(m.OverHeal)?t.hp=Math.max(100,t.hp-e):t.hp=Math.min(100,t.hp+e)}t.spawnShield>0&&(t.spawnShield-=6)}}}on(t,e){Object.keys(this.#t).includes(t)?this.#t[t].push(e):this.#t[t]=[e]}onAny(t){this.#i.push(t)}off(t,e){this.#t[t]=this.#t[t].filter(a=>a!==e)}emit(t,...e){if(!this.state.quit){if(this.#t[t])for(const a of this.#t[t])a(...e);for(const a of this.#i)a(t,...e)}}#h(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackString().valueOf(),i=this.players[t];this.emit("chat",i,a,e)}#l(){const t=s.unPackInt8U(),e=this.intents.includes(this.Intents.COSMETIC_DATA),a={id:t,uniqueId:s.unPackString(),name:s.unPackString(),safename:s.unPackString(),charClass:s.unPackInt8U(),team:s.unPackInt8U(),primaryWeaponItem:e?d(s.unPackInt16U()):s.unPackInt16U(),secondaryWeaponItem:e?d(s.unPackInt16U()):s.unPackInt16U(),shellColor:s.unPackInt8U(),hatItem:e?d(s.unPackInt16U()):s.unPackInt16U(),stampItem:e?d(s.unPackInt16U()):s.unPackInt16U(),stampPosX:s.unPackInt8(),stampPosY:s.unPackInt8(),grenadeItem:e?d(s.unPackInt16U()):s.unPackInt16U(),meleeItem:e?d(s.unPackInt16U()):s.unPackInt16U(),x:s.unPackFloat(),y:s.unPackFloat(),z:s.unPackFloat(),$dx:s.unPackFloat(),$dy:s.unPackFloat(),$dz:s.unPackFloat(),yaw:s.unPackRadU(),pitch:s.unPackRad(),score:s.unPackInt32U(),kills:s.unPackInt16U(),deaths:s.unPackInt16U(),streak:s.unPackInt16U(),totalKills:s.unPackInt32U(),totalDeaths:s.unPackInt32U(),bestGameStreak:s.unPackInt16U(),bestOverallStreak:s.unPackInt16U(),shield:s.unPackInt8U(),hp:s.unPackInt8U(),playing:s.unPackInt8U(),weaponIdx:s.unPackInt8U(),$controlKeys:s.unPackInt8U(),upgradeProductId:s.unPackInt8U(),activeShellStreaks:s.unPackInt8U(),social:s.unPackLongString(),hideBadge:s.unPackInt8U()};s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U(),this.players[a.id]||(this.players[a.id]=new U(a)),this.me.id==a.id&&(this.me=this.players[a.id]),this.emit("playerJoin",this.players[a.id])}#m(){const t=s.unPackInt8U(),e=s.unPackInt16U(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackInt8U(),h=s.unPackInt8U(),p=s.unPackInt8U(),I=s.unPackInt8U(),k=s.unPackInt8U(),r=this.players[t];r&&(r.playing=!0,r.randomSeed=e,r.weapons[0]&&r.weapons[0].ammo&&(r.weapons[0].ammo.rounds=o),r.weapons[0]&&r.weapons[0].ammo&&(r.weapons[0].ammo.store=h),r.weapons[1]&&r.weapons[1].ammo&&(r.weapons[1].ammo.rounds=p),r.weapons[1]&&r.weapons[1].ammo&&(r.weapons[1].ammo.store=I),r.grenades=k,r.position={x:a,y:i,z:n},r.spawnShield=120,this.emit("playerRespawn",r))}#d(){const t=s.unPackInt8U(),e=s.unPackFloat(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackInt8U(),o=this.players[t];if(!o||o.id==this.me.id){for(let h=0;h<w;h++)s.unPackInt8U(),s.unPackRadU(),s.unPackRad(),s.unPackInt8U();return}o.position.x!==e&&(o.position.x=e),o.position.z!==i&&(o.position.z=i),(!o.jumping||Math.abs(o.position.y-a)>.5&&o.position.y!==a)&&(o.position.y=a),o.climbing!==n&&(o.climbing=n);for(let h=0;h<w;h++)s.unPackInt8U(),s.unPackRadU(),s.unPackRad(),s.unPackInt8U()}#u(){const t=s.unPackInt8U(),e=this.players[t];e&&(e.playing=!1,this.emit("playerPause",e))}#p(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];a&&(a.activeGun=e,this.emit("playerSwapWeapon",a,e))}#g(){const t=s.unPackInt8U(),e=s.unPackInt8U();s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U();const a=this.players[t],i=this.players[e];a&&(a.playing=!1,a.streak=0,a.lastDeathTime=Date.now(),a.hp=100,a.spawnShield=0),i&&i.streak++,this.emit("playerDeath",a,i)}#k(){const t=s.unPackInt8U();for(let i=0;i<6;i++)s.unPackFloat();const e=this.players[t],a=e.weapons[e.activeGun];a&&a.ammo&&(a.ammo.rounds--,this.emit("playerFire",e,a))}#I(){const t=s.unPackInt16U(),e=s.unPackInt8U(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat();this.game.collectables[e].push({id:t,x:a,y:i,z:n}),this.emit("spawnItem",e,t,{x:a,y:i,z:n})}#f(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackInt8U(),i=s.unPackInt16U(),n=this.players[t];if(this.game.collectables[e]=this.game.collectables[e].filter(o=>o.id!=i),e==T.AMMO){const o=n.weapons[a];o&&o.ammo&&(o.ammo.store=Math.min(o.ammo.storeMax,o.ammo.store+o.ammo.pickup),this.emit("collectAmmo",n,o))}e==T.GRENADE&&(n.grenades++,n.grenades>3&&(n.grenades=3),this.emit("collectGrenade",n))}#P(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;const i=a.hp;a.hp=e,this.emit("playerDamaged",a,i,a.hp)}#y(){const t=s.unPackInt8U();s.unPackFloat(),s.unPackFloat();const e=this.me.hp;this.me.hp=t,this.emit("selfDamaged",e,this.me.hp)}#w(){const t=s.unPackInt8U(),e=this.players[t];s.unPackInt8U();const a=s.unPackInt8U(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackFloat();if(s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U(),!e)return;this.state.serverStateIdx=a;const h=e.position.x,p=e.position.y,I=e.position.z;e.position.x=i,e.position.y=n,e.position.z=o,(h!=i||p!=n||I!=o)&&this.emit("selfMoved",e,{x:h,y:p,z:I},{x:i,y:n,z:o})}#U(){const t=f.getBuffer();t.packInt8(c.eventModifier),t.send(this.game.socket)}#b(){const t=s.unPackInt8U(),e={...this.players[t]};delete this.players[t.toString()],this.emit("playerLeave",e)}#S(){if(this.game.gameModeId==u.spatula){this.game.teamScore[1]=s.unPackInt16U(),this.game.teamScore[2]=s.unPackInt16U();const t={x:s.unPackFloat(),y:s.unPackFloat(),z:s.unPackFloat()},e=s.unPackInt8U(),a=s.unPackInt8U();this.game.spatula={coords:t,controlledBy:e,controlledByTeam:a},this.emit("gameStateChange",this.game)}else this.game.gameModeId==u.kotc?(this.game.stage=s.unPackInt8U(),this.game.zoneNumber=s.unPackInt8U(),this.game.capturing=s.unPackInt8U(),this.game.captureProgress=s.unPackInt16U(),this.game.numCapturing=s.unPackInt8U(),this.game.teamScore[1]=s.unPackInt8U(),this.game.teamScore[2]=s.unPackInt8U(),this.game.stageName=B[this.game.stage],this.game.capturePercent=this.game.captureProgress/1e3,this.game.activeZone=this.game.map.zones?this.game.map.zones[this.game.zoneNumber-1]:null,this.emit("gameStateChange",this.game)):this.game.gameModeId==u.team&&(this.game.teamScore[1]=s.unPackInt16U(),this.game.teamScore[2]=s.unPackInt16U());this.game.gameModeId!==u.spatula&&delete this.game.spatula,this.game.gameModeId!==u.kotc&&(delete this.game.stage,delete this.game.zoneNumber,delete this.game.capturing,delete this.game.captureProgress,delete this.game.numCapturing,delete this.game.stageName,delete this.game.numCapturing,delete this.game.activeZone),this.game.gameModeId==u.ffa&&delete this.game.teamScore}#x(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];switch(e){case m.HardBoiled:t===this.me.id&&(this.me.shieldHp=100),a.streakRewards.push(m.HardBoiled);break;case m.EggBreaker:a.streakRewards.push(m.EggBreaker);break;case m.Restock:{a.grenades=3,a.weapons[0]&&a.weapons[0].ammo&&(a.weapons[0].ammo.rounds=a.weapons[0].ammo.capacity,a.weapons[0].ammo.store=a.weapons[0].ammo.storeMax),a.weapons[1]&&a.weapons[1].ammo&&(a.weapons[1].ammo.rounds=a.weapons[1].ammo.capacity,a.weapons[1].ammo.store=a.weapons[1].ammo.storeMax);break}case m.OverHeal:a.hp=Math.min(200,a.hp+100),a.streakRewards.push(m.OverHeal);break;case m.DoubleEggs:a.streakRewards.push(m.DoubleEggs);break;case m.MiniEgg:a.streakRewards.push(m.MiniEgg);break}this.emit("playerBeginStreak",a,e)}#v(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];[m.EggBreaker,m.OverHeal,m.DoubleEggs,m.MiniEgg].includes(e)&&a.streakRewards.includes(e)&&(a.streakRewards=a.streakRewards.filter(n=>n!=e)),this.emit("playerEndStreak",e,a)}#C(){const t=s.unPackInt8U(),e=s.unPackInt8U();s.unPackFloat(),s.unPackFloat(),this.me.shieldHp=t,this.me.hp=e,this.me.shieldHp<=0?(this.me.streakRewards=this.me.streakRewards.filter(a=>a!=m.HardBoiled),this.emit("selfShieldLost")):this.emit("selfShieldHit",this.me.shieldHp)}#T(){const t={...this.game.options};let e=s.unPackInt8U(),a=s.unPackInt8U(),i=s.unPackInt8U();(e<1||e>4)&&(e=4),(a<0||a>8)&&(a=4),i>16&&(i=4),this.game.options.gravity=e/4,this.game.options.damage=a/4,this.game.options.healthRegen=i/4;const n=s.unPackInt8U();return Object.keys(G).forEach(o=>{const h=n&G[o]?1:0;this.game.options[o]=h}),this.game.options.weaponsDisabled=Array.from({length:7},()=>s.unPackInt8U()===1),this.game.options.mustUseSecondary=this.game.options.weaponsDisabled.every(o=>o),this.emit("gameOptionsChange",t,this.game.options),!1}#E(){const t=s.unPackInt8U();t==E.pause&&(this.emit("gameForcePause"),setTimeout(()=>this.me.playing=!1,3e3)),t==E.reset&&(Object.values(this.players).forEach(e=>e.streak=0),this.game.gameModeId!==u.ffa&&(this.game.teamScore=[0,0,0]),this.game.gameModeId===u.spatula&&(this.game.spatula.controlledBy=0,this.game.spatula.controlledByTeam=0,this.game.spatula.coords={x:0,y:0,z:0}),this.game.gameModeId===u.kotc&&(this.game.stage=y.capturing,this.game.zoneNumber=0,this.game.activeZone=null,this.game.capturing=0,this.game.captureProgress=0,this.game.numCapturing=0,this.game.stageName=B[y.capturing],this.game.capturePercent=0),this.emit("gameReset"))}#G(){if(!this.intents.includes(this.Intents.PING))return;const t=this.ping;this.ping=Date.now()-this.lastPingTime,this.emit("pingUpdate",t,this.ping),setTimeout(()=>{const e=f.getBuffer();e.packInt8(c.ping),e.send(this.game.socket),this.lastPingTime=Date.now()},this.pingInterval)}#F(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;const i=a.team;a.team=e,a.streak=0,this.emit("playerSwitchTeam",a,i,e)}#R(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackInt16U(),i=s.unPackInt16U(),n=s.unPackInt8U(),o=s.unPackInt16U(),h=s.unPackInt16U(),p=s.unPackInt16U(),I=s.unPackInt16U();s.unPackInt8(),s.unPackInt8();const k=this.intents.includes(this.Intents.COSMETIC_DATA),r=k?d(a):a,L=k?d(i):i,N=k?d(o):o,D=k?d(h):h,$=k?d(p):p,_=k?d(I):I,l=this.players[t];if(l){const v={...l.character},C=l.selectedGun;l.character.eggColor=n,l.character.primaryGun=r,l.character.secondaryGun=L,l.character.stamp=D,l.character.hat=N,l.character.grenade=$,l.character.melee=_,l.selectedGun=e,l.weapons[0]=new X[e],C!==l.selectedGun&&this.emit("playerChangeGun",l,C,l.selectedGun),v!==l.character&&this.emit("playerChangeCharacter",l,v,l.character)}}#M(){const t=s.unPackInt32U(),e=this.account.eggBalance;this.account.eggBalance=t,this.emit("balanceUpdate",t-e,t)}#B(){this.me.playing=!1,this.emit("selfRespawnFail")}#A(){const t=s.unPackInt8U(),e=this.players[t];e&&this.emit("playerMelee",e)}#O(){const t=s.unPackInt8U(),e=this.players[t];if(!e)return;const a=e.weapons[e.activeGun];if(a.ammo){const i=Math.min(Math.min(a.ammo.capacity,a.ammo.reload)-a.ammo.rounds,a.ammo.store);a.ammo.rounds+=i,a.ammo.store-=i}this.emit("playerReload",e,a)}#L(){const t=f.getBuffer();t.packInt8(c.gameOptions),t.packInt8(this.game.options.gravity*4),t.packInt8(this.game.options.damage*4),t.packInt8(this.game.options.healthRegen*4);const e=(this.game.options.locked?1:0)|(this.game.options.noTeamChange?2:0)|(this.game.options.noTeamShuffle?4:0);t.packInt8(e),this.game.options.weaponsDisabled.forEach(a=>{t.packInt8(a?1:0)}),t.send(this.game.socket)}#N(){const t=s.unPackInt8U();let e=s.unPackInt16U();const a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackInt8U(),h=s.unPackFloat();this.intents.includes(this.Intents.COSMETIC_DATA)&&(e=d(e)),t==V.Grenade?this.emit("grenadeExploded",e,{x:a,y:i,z:n},o,h):this.emit("rocketHit",{x:a,y:i,z:n},o,h)}#D(){const t=s.unPackInt8U(),e=s.unPackFloat(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackFloat(),h=s.unPackFloat(),p=this.players[t];p&&(p.grenades--,this.emit("playerThrowGrenade",p,{x:e,y:a,z:i},{x:n,y:o,z:h}))}#$(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;if(!this.intents.includes(this.Intents.CHALLENGES))return this.emit("challengeComplete",a,e);const i=this.account.challenges.find(n=>n.id==e);this.emit("challengeComplete",a,i),a.id==this.me.id&&this.refreshChallenges()}#_(){const t=f.getBuffer();t.packInt8(c.joinGame),t.packString(this.state.name),t.packString(this.game.raw.uuid),t.packInt8(0),t.packInt8(this.state.weaponIdx||this.account?.loadout?.classIdx||0),t.packInt32(this.account.session),t.packString(this.account.firebaseId),t.packString(this.account.sessionId),t.send(this.game.socket)}async#z(){if(this.me.id=s.unPackInt8U(),this.me.team=s.unPackInt8U(),this.game.gameModeId=s.unPackInt8U(),this.game.gameMode=A[this.game.gameModeId],this.game.mapIdx=s.unPackInt8U(),this.game.map=S[this.game.mapIdx],this.intents.includes(this.Intents.PATHFINDING)&&(this.game.map.raw=await et(this.game.map.filename,this.game.map.hash),this.pathing.nodeList=new tt(this.game.map.raw),this.game.gameModeId===u.kotc)){const e=this.game.map.raw.data["DYNAMIC.capture-zone.none"];e?this.game.map.zones=st(e):delete this.game.map.zones}this.game.playerLimit=s.unPackInt8U(),this.game.isGameOwner=s.unPackInt8U()==1,this.game.isPrivate=s.unPackInt8U()==1,s.unPackInt8U(),this.state.joinedGame=!0,this.lastDeathTime=Date.now();const t=f.getBuffer();if(t.packInt8(c.clientReady),t.send(this.game.socket),this.game.socket.onmessage=e=>this.processPacket(e.data),this.updateIntervalId=setInterval(()=>this.update(),100/3),this.intents.includes(this.Intents.PING)){this.lastPingTime=Date.now();const e=f.getBuffer();e.packInt8(c.ping),e.send(this.game.socket)}this.emit("gameReady")}processPacket(t){s.init(t),this.intents.includes(this.Intents.PACKET_HOOK)&&this.emit("packet",t);let e=0,a=0,i=!1;for(;s.isMoreDataAvailable()&&!i;){const n=s.unPackInt8U();switch(n){case c.syncThem:this.#d();break;case c.fire:this.#k();break;case c.hitThem:this.#P();break;case c.syncMe:this.#w();break;case c.hitMe:this.#y();break;case c.swapWeapon:this.#p();break;case c.collectItem:this.#f();break;case c.respawn:this.#m();break;case c.die:this.#g();break;case c.pause:this.#u();break;case c.chat:this.#h();break;case c.addPlayer:this.#l();break;case c.removePlayer:this.#b();break;case c.eventModifier:this.#U();break;case c.metaGameState:this.#S();break;case c.beginShellStreak:this.#x();break;case c.endShellStreak:this.#v();break;case c.hitMeHardBoiled:this.#C();break;case c.gameOptions:this.#T();break;case c.ping:this.#G();break;case c.switchTeam:this.#F();break;case c.changeCharacter:this.#R();break;case c.reload:this.#O();break;case c.explode:this.#N();break;case c.throwGrenade:this.#D();break;case c.spawnItem:this.#I();break;case c.melee:this.#A();break;case c.updateBalance:this.#M();break;case c.challengeCompleted:this.#$();break;case c.socketReady:this.#_();break;case c.gameJoined:this.#z();break;case c.gameAction:this.#E();break;case c.requestGameOptions:this.#L();break;case c.respawnDenied:this.#B();break;case c.expireUpgrade:case c.clientReady:break;case c.musicInfo:s.unPackLongString();break;default:console.error(`handlePacket: I got but did not handle a: ${Object.keys(c).find(o=>c[o]===n)} ${n}`),e&&console.error(`handlePacket: It may be a result of the ${e} command (${a}).`),i=!0;break}e=Object.keys(c).find(o=>c[o]===n),a=n,this.intents.includes(this.Intents.LOG_PACKETS)&&console.log(`[LOG_PACKETS] Packet ${e}: ${a}`)}}async checkChiknWinner(){const t=await g({cmd:"chicknWinnerReady",id:this.account.id,sessionId:this.account.sessionId});return typeof t=="string"?t:(this.account.cw.limit=t.limit,this.account.cw.atLimit=t.limit>=4,this.account.cw.secondsUntilPlay=(this.account.cw.atLimit?t.period:t.span)||0,this.account.cw.canPlayAgain=Date.now()+this.account.cw.secondsUntilPlay*1e3,this.account.cw)}async playChiknWinner(t=!0){if(this.account.cw.atLimit||this.account.cw.limit>Z)return"hit_daily_limit";if(this.account.cw.canPlayAgain>Date.now()&&t)return"on_cooldown";const e=await g({cmd:"incentivizedVideoReward",firebaseId:this.account.firebaseId,id:this.account.id,sessionId:this.account.sessionId,token:null},this.proxy,`${this.protocol}://${this.instance}`);return typeof e=="string"?e:e.error?e.error=="RATELIMITED"||e.error=="RATELMITED"?(await this.checkChiknWinner(),"on_cooldown"):e.error=="SESSION_EXPIRED"?"session_expired":(console.error("Unknown Chikn Winner response",e),"unknown_error"):e.reward?(this.account.eggBalance+=e.reward.eggsGiven,e.reward.itemIds.forEach(a=>this.account.ownedItemIds.push(a)),await this.checkChiknWinner(),e.reward):(console.error("Unknown Chikn Winner response",e),"unknown_error")}async resetChiknWinner(){if(this.account.eggBalance<200)return"not_enough_eggs";if(!this.account.cw.atLimit)return"not_at_limit";const t=await g({cmd:"chwReset",sessionId:this.account.sessionId});return typeof t=="string"?t:t.result!=="SUCCESS"?(console.error("Unknown Chikn Winner reset response",t),"unknown_error"):(this.account.eggBalance-=200,await this.checkChiknWinner(),this.account.cw)}canSee(t){if(!this.intents.includes(this.Intents.PATHFINDING))throw new Error("You must have the PATHFINDING intent to use this method.");return this.pathing.nodeList.hasLineOfSight(this.me.position,t.position)}getBestTarget(t=()=>!0){const a=Object.values(this.players).filter(n=>n?.playing).filter(n=>n.hp>0).filter(n=>n.id!==this.me.id).filter(n=>this.me.team===0||n.team!==this.me.team).filter(n=>!!t(n)).map(n=>({player:n,distance:Math.sqrt(Math.pow(n.position.x-this.me.position.x,2)+Math.pow(n.position.y-this.me.position.y,2)+Math.pow(n.position.z-this.me.position.z,2))})).sort((n,o)=>n.distance-o.distance);if(!a.length)return this.intents.includes(this.Intents.DEBUG_BEST_TARGET)&&console.log("no targets found"),null;const i=a.find(n=>this.canSee(n.player));return this.intents.includes(this.Intents.DEBUG_BEST_TARGET)&&(console.log("detected ",a.length,"targets"),console.log("closest target: ",a[0].player.name),console.log("all targets (ordered): ",a.map(n=>n.player.name)),console.log("found LoS player?",!!i),i&&console.log("closest LoS player: ",i.player.name)),i?{player:i.player,inLoS:!0}:{player:a[0].player,inLoS:!1}}async refreshChallenges(){const t=await g({cmd:"challengeGetDaily",sessionId:this.account.sessionId,playerId:this.account.id},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(t),this.account.challenges}async rerollChallenge(t){const e=await g({cmd:"challengeRerollSlot",sessionId:this.account.sessionId,slotId:t},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(e),this.account.challenges}async claimChallenge(t){const e=await g({cmd:"challengeClaimReward",sessionId:this.account.sessionId,slotId:t},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(e.challenges),e.reward>0&&(this.account.eggBalance+=e.reward),{eggReward:e.reward,updatedChallenges:this.account.challenges}}async refreshBalance(){const t=await g({cmd:"checkBalance",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId},this.proxy,`${this.protocol}://${this.instance}`);return this.account.eggBalance=t.currentBalance,t.currentBalance}async redeemCode(t){const e=await g({cmd:"redeem",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,id:this.account.id,code:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"?(this.account.eggBalance=e.eggs_given,e.item_ids.forEach(a=>this.account.ownedItemIds.push(a)),{result:e,eggsGiven:e.eggs_given,itemIds:e.item_ids}):e}async claimURLReward(t){const e=await g({cmd:"urlRewardParams",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,reward:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance+=e.eggsGiven,e.itemIds.forEach(a=>this.account.ownedItemIds.push(a))),e}async claimSocialReward(t){const e=await g({cmd:"reward",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,rewardTag:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance+=e.eggsGiven,e.itemIds.forEach(a=>this.account.ownedItemIds.push(a))),e}async buyItem(t){const e=await g({cmd:"buy",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,itemId:t,save:!0},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance=e.currentBalance,this.account.ownedItemIds.push(e.itemId)),e}leave(t=K.mainMenu){this.state.quit||(t>-1&&(this.game?.socket?.close(t),this.state.left=!0,this.emit("leave")),clearInterval(this.updateIntervalId),this.#e=[],this.state.reloading=!1,this.state.swappingGun=!1,this.state.usingMelee=!1,this.state.stateIdx=0,this.state.serverStateIdx=0,this.state.shotsFired=0,this.state.buffer=[],this.players={},this.me=new U({}),this.game=this.#o,this.ping=0,this.lastPingTime=-1,this.lastDeathTime=-1,this.lastChatTime=-1,this.lastUpdateTick=0,this.controlKeys=0,this.pathing={nodeList:null,followingPath:!1,activePath:null,activeNode:null,activeNodeIdx:0})}logout(){this.account=this.#n}quit(t=!1){this.state.quit||(this.leave(),this.matchmaker&&(this.matchmaker.close(),this.matchmaker=null),t||(delete this.account,delete this.game,delete this.me,delete this.players),this.state.quit=!0,this.emit("quit"))}}var yt=it;export{it as Bot,yt as default};
3
+ import{createAccount as z,loginAnonymously as H,loginWithCredentials as W,loginWithRefreshToken as j,queryServices as g}from"./api.js";import s from"./comm/CommIn.js";import f from"./comm/CommOut.js";import{CloseCode as K}from"./comm/Codes.js";import{CommCode as c}from"./constants/codes.js";import U from"./bot/GamePlayer.js";import q from"./matchmaker.js";import Y from"./socket.js";import{ChiknWinnerDailyLimit as Z,CollectTypes as T,CoopStates as y,findItemById as d,FramesBetweenSyncs as w,GameActions as E,GameModes as u,GameOptionFlags as G,GunList as X,ItemTypes as V,Movements as F,PlayTypes as J,ProxiesEnabled as Q,ShellStreaks as m,StateBufferSize as b}from"./constants/index.js";import R from"./dispatches/LookAtPosDispatch.js";import M from"./dispatches/MovementDispatch.js";import{NodeList as tt}from"./pathing/mapnode.js";import{fetchMap as et,initKotcZones as st}from"./util.js";import{Challenges as at}from"./constants/challenges.js";import{Maps as S}from"./constants/maps.js";const B=Object.fromEntries(Object.entries(y).map(([P,t])=>[t,P])),A=Object.fromEntries(Object.entries(u).map(([P,t])=>[t,P])),O={CHALLENGES:1,STATS:2,PATHFINDING:3,PING:5,COSMETIC_DATA:6,PLAYER_HEALTH:7,PACKET_HOOK:8,LOG_PACKETS:10,NO_LOGIN:11,DEBUG_BUFFER:12,DEBUG_BEST_TARGET:14},x=(P,t)=>(P%t+t)%t;class it{static Intents=O;Intents=O;#e=[];#t={};#i=[];#n;#o;constructor(t={}){if(t.proxy&&!Q)throw new Error("proxies do not work and hence are not supported in the browser");this.intents=t.intents||[],this.instance=t.instance||"shellshock.io",this.protocol=t.protocol||"wss",this.proxy=t.proxy||"",this.state={name:"yolkbot",weaponIdx:0,reloading:!1,swappingGun:!1,usingMelee:!1,stateIdx:0,serverStateIdx:0,shotsFired:0,buffer:[],left:!1,quit:!1},this.players={},this.me=new U({}),this.game={raw:{},code:"",socket:null,gameModeId:0,gameMode:A[0],mapIdx:0,map:{filename:"",hash:"",name:"",modes:{FFA:!1,Teams:!1,Spatula:!1,King:!1},availability:"both",numPlayers:"18",raw:{},nodes:{},zones:[]},playerLimit:0,isGameOwner:!1,isPrivate:!0,options:{gravity:1,damage:1,healthRegen:1,locked:!1,noTeamChange:!1,noTeamShuffle:!1,weaponsDisabled:Array(7).fill(!1),mustUseSecondary:!1},collectables:[[],[]],teamScore:[0,0,0],spatula:{coords:{x:0,y:0,z:0},controlledBy:0,controlledByTeam:0},stage:y.capturing,zoneNumber:0,activeZone:[],capturing:0,captureProgress:0,numCapturing:0,stageName:"",capturePercent:0},this.#o=this.game,this.account={id:0,firebaseId:"",sessionId:"",session:"",email:"",password:"",cw:{atLimit:!1,limit:0,secondsUntilPlay:0,canPlayAgain:Date.now()},loadout:{hatId:null,meleeId:0,stampId:null,classIdx:0,colorIdx:0,grenadeId:0,primaryId:[3100,3600,3400,3800,4e3,4200,4500],secondaryId:new Array(7).fill(3e3),stampPositionX:0,stampPositionY:0},ownedItemIds:[],vip:!1,accountAge:0,emailVerified:!1,eggBalance:0,rawLoginData:{}},this.#n=this.account,this.matchmaker=null,this.ping=0,this.lastPingTime=-1,this.lastDeathTime=-1,this.lastChatTime=-1,this.lastUpdateTick=0,this.controlKeys=0,this.pathing={nodeList:null,followingPath:!1,activePath:null,activeNode:null,activeNodeIdx:0}}dispatch(t){t.check(this)?t.execute(this):this.#e.push(t)}async createAccount(t,e){this.account.email=t,this.account.password=e;const a=await z(t,e,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(a)}async login(t,e){this.account.email=t,this.account.password=e;const a=await W(t,e,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(a)}async loginWithRefreshToken(t){const e=await j(t,this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(e)}async loginAnonymously(){delete this.account.email,delete this.account.password;const t=await H(this.proxy,`${this.protocol}://${this.instance}`);return await this.#s(t)}async#s(t){return typeof t!="object"?(this.emit("authFail",t),!1):t.banRemaining?(this.emit("banned",t.banRemaining),!1):t.playerOutput?(t=t.playerOutput,this.account.rawLoginData=t,this.account.accountAge=t.accountAge,this.account.eggBalance=t.currentBalance,this.account.emailVerified=t.emailVerified,this.account.firebaseId=t.firebaseId,this.account.id=t.id,this.account.loadout=t.loadout,this.account.ownedItemIds=t.ownedItemIds,this.account.session=t.session,this.account.sessionId=t.sessionId,this.account.vip=t.upgradeProductId&&!t.upgradeIsExpired,this.intents.includes(this.Intents.STATS)&&(this.account.stats={lifetime:t.statsLifetime,monthly:t.statsCurrent}),this.intents.includes(this.Intents.CHALLENGES)&&this.#a(t.challenges),this.emit("authSuccess",this.account),this.account):(this.emit("authFail",t),!1)}#a(t){this.account.challenges=[];for(const e of t){const a=at.find(i=>i.id==e.challengeId);a&&(delete e.playerId,this.account.challenges.push({raw:{challengeInfo:a,challengeData:e},id:e.challengeId,name:a.loc.title,desc:a.loc.desc,rewardEggs:a.reward,isRerolled:!!e.reset,isClaimed:!!e.claimed,isCompleted:!!e.completed,progressNum:e.progress,goalNum:a.goal}))}}async initMatchmaker(){return!this.account.sessionId&&!this.intents.includes(this.Intents.NO_LOGIN)&&!await this.loginAnonymously()?!1:(this.matchmaker||(this.matchmaker=new q({sessionId:this.account.sessionId,proxy:this.proxy,instance:this.instance,protocol:this.protocol,noLogin:this.intents.includes(this.Intents.NO_LOGIN)}),this.matchmaker.on("authFail",t=>this.emit("authFail",t)),await this.matchmaker.getRegions()),!0)}async#c(t){return await this.initMatchmaker()?await new Promise(e=>{const a=i=>{if(i.command=="gameFound"&&(this.matchmaker.off("msg",a),this.game.raw=i,this.game.code=i.id,e()),i.error&&i.error=="gameNotFound")throw new Error(`Game ${t} not found (likely expired).`)};this.matchmaker.on("msg",a),this.matchmaker.send({command:"joinGame",id:t,observe:!1,sessionId:this.account.sessionId})}):!1}async createPrivateGame(t={}){if(!await this.initMatchmaker())return!1;if(!t.region)throw new Error('pass a region: createPrivateGame({ region: "useast", ... })');if(!this.matchmaker.regionList.find(i=>i.id==t.region))throw new Error('invalid region, see <bot>.matchmaker.regionList for a region list (pass an "id")');if(!t.mode)throw new Error('pass a mode: createPrivateGame({ mode: "ffa", ... })');if(u[t.mode]==null)throw new Error("invalid mode, see GameModes for a list");if(!t.map)throw new Error('pass a map: createPrivateGame({ map: "downfall", ... })');const e=S.find(i=>i.name.toLowerCase()==t.map.toLowerCase()),a=S.indexOf(e);if(a==-1)throw new Error("invalid map, see the Maps constant for a list");return await new Promise(i=>{const n=o=>{o.command=="gameFound"&&(this.matchmaker.off("msg",n),this.game.raw=o,this.game.code=this.game.raw.id,i())};this.matchmaker.on("msg",n),this.matchmaker.send({command:"findGame",region:t.region,playType:J.createPrivate,gameType:u[t.mode],sessionId:this.account.sessionId,noobLobby:!1,map:a})}),this.game.raw}async join(t,e){if(this.state.name=t||"yolkbot",typeof e=="string"?(e.includes("#")&&(e=e.split("#")[1]),await this.#c(e)):typeof e=="object"&&(this.account.id==0&&await this.loginAnonymously(),this.game.raw=e,this.game.code=this.game.raw.id),!this.game.raw.id)throw new Error("invalid game data passed to <bot>.join");const a=async()=>{try{const i=this.instance.startsWith("localhost:")?this.instance:`${this.game.raw.subdomain}.${this.instance}`;this.game.socket=new Y(`${this.protocol}://${i}/game/${this.game.raw.id}`,this.proxy),this.game.socket.onerror=async n=>(console.error(n),await new Promise(o=>setTimeout(o,100)),await a())}catch{await new Promise(i=>setTimeout(i,100)),await a()}};await a(),this.game.socket.binaryType="arraybuffer",this.game.socket.onopen=()=>this.game.socket.onerror=null,this.game.socket.onmessage=i=>this.processPacket(i.data),this.game.socket.onclose=i=>{this.state.left?this.state.left=!1:(this.emit("close",i.code),this.leave(-1))}}#r(){if(Object.entries(this.me.position).map(e=>Math.floor(e[1])).join(",")==this.pathing.activePath[this.pathing.activePath.length-1].positionStr)this.pathing.followingPath=!1,this.pathing.activePath=null,this.pathing.activeNode=null,this.pathing.activeNodeIdx=0,this.dispatch(new M(0));else{let e;this.pathing.activeNodeIdx<this.pathing.activePath.length-1?(e=this.pathing.activePath[this.pathing.activeNodeIdx+1].flatCenter(),this.dispatch(new R(e))):(e=this.pathing.activePath[this.pathing.activeNodeIdx].flatCenter(),this.dispatch(new R(e)));for(const a of this.pathing.activePath)if(a.flatRadialDistance(this.me.position)<.1&&a.position.y==Math.floor(this.me.position.y)&&this.pathing.activePath.indexOf(a)>=this.pathing.activeNodeIdx){this.pathing.activeNodeIdx=this.pathing.activePath.indexOf(a)+1,this.pathing.activeNode=this.pathing.activePath[this.pathing.activeNodeIdx];break}this.controlKeys&F.FORWARD||this.dispatch(new M(F.FORWARD))}}update(){if(!this.state.quit){if(this.pathing.followingPath&&this.intents.includes(this.Intents.PATHFINDING)&&this.#r(),this.#e.length>0)for(let t=0;t<this.#e.length;t++){const e=this.#e[t];e.check(this)&&(e.execute(this),this.#e.splice(t,1))}if(this.me.playing){const t=this.state.stateIdx;if(this.intents.includes(this.Intents.DEBUG_BUFFER)&&(console.log("setting buffer for idx",t),console.log("checking...shotsFired",this.state.shotsFired)),this.state.buffer[t]={controlKeys:this.controlKeys,yaw:this.me.view.yaw,pitch:this.me.view.pitch,shotsFired:this.state.shotsFired},this.state.shotsFired=0,this.lastUpdateTick>=2){this.emit("tick");const e=f.getBuffer();e.packInt8(c.syncMe),e.packInt8(this.state.stateIdx),e.packInt8(this.state.serverStateIdx);const a=x(this.state.stateIdx-w+1,b);for(let i=0;i<w;i++){const n=x(a+i,b);this.intents.includes(this.Intents.DEBUG_BUFFER)&&console.log("going with",this.state.stateIdx,a,n,this.state.buffer[n]),e.packInt8(this.state.buffer[n]?.controlKeys||0),e.packInt8(this.state.buffer[n]?.shotsFired||0),e.packRadU(this.state.buffer[n]?.yaw||this.me.view.yaw),e.packRad(this.state.buffer[n]?.pitch||this.me.view.pitch),e.packInt8(100)}e.send(this.game.socket),this.state.buffer=[],this.lastUpdateTick=0}else this.lastUpdateTick++;this.state.stateIdx=x(this.state.stateIdx+1,b)}if(this.intents.includes(this.Intents.PLAYER_HEALTH))for(const t of Object.values(this.players)){if(t.playing&&t.hp>0){const e=.1*(this.game.isPrivate?this.game.options.healthRegen:1);t.streakRewards.includes(m.OverHeal)?t.hp=Math.max(100,t.hp-e):t.hp=Math.min(100,t.hp+e)}t.spawnShield>0&&(t.spawnShield-=6)}}}on(t,e){Object.keys(this.#t).includes(t)?this.#t[t].push(e):this.#t[t]=[e]}onAny(t){this.#i.push(t)}off(t,e){this.#t[t]=this.#t[t].filter(a=>a!==e)}emit(t,...e){if(!this.state.quit){if(this.#t[t])for(const a of this.#t[t])a(...e);for(const a of this.#i)a(t,...e)}}#h(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackString().valueOf(),i=this.players[t];this.emit("chat",i,a,e)}#l(){const t=s.unPackInt8U(),e=this.intents.includes(this.Intents.COSMETIC_DATA),a={id:t,uniqueId:s.unPackString(),name:s.unPackString(),safename:s.unPackString(),charClass:s.unPackInt8U(),team:s.unPackInt8U(),primaryWeaponItem:e?d(s.unPackInt16U()):s.unPackInt16U(),secondaryWeaponItem:e?d(s.unPackInt16U()):s.unPackInt16U(),shellColor:s.unPackInt8U(),hatItem:e?d(s.unPackInt16U()):s.unPackInt16U(),stampItem:e?d(s.unPackInt16U()):s.unPackInt16U(),stampPosX:s.unPackInt8(),stampPosY:s.unPackInt8(),grenadeItem:e?d(s.unPackInt16U()):s.unPackInt16U(),meleeItem:e?d(s.unPackInt16U()):s.unPackInt16U(),x:s.unPackFloat(),y:s.unPackFloat(),z:s.unPackFloat(),$dx:s.unPackFloat(),$dy:s.unPackFloat(),$dz:s.unPackFloat(),yaw:s.unPackRadU(),pitch:s.unPackRad(),score:s.unPackInt32U(),kills:s.unPackInt16U(),deaths:s.unPackInt16U(),streak:s.unPackInt16U(),totalKills:s.unPackInt32U(),totalDeaths:s.unPackInt32U(),bestGameStreak:s.unPackInt16U(),bestOverallStreak:s.unPackInt16U(),shield:s.unPackInt8U(),hp:s.unPackInt8U(),playing:s.unPackInt8U(),weaponIdx:s.unPackInt8U(),$controlKeys:s.unPackInt8U(),upgradeProductId:s.unPackInt8U(),activeShellStreaks:s.unPackInt8U(),social:s.unPackLongString(),hideBadge:s.unPackInt8U()};s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U(),this.players[a.id]||(this.players[a.id]=new U(a)),this.me.id==a.id&&(this.me=this.players[a.id]),this.emit("playerJoin",this.players[a.id])}#m(){const t=s.unPackInt8U(),e=s.unPackInt16U(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackInt8U(),h=s.unPackInt8U(),p=s.unPackInt8U(),I=s.unPackInt8U(),k=s.unPackInt8U(),r=this.players[t];r&&(r.playing=!0,r.randomSeed=e,r.weapons[0]&&r.weapons[0].ammo&&(r.weapons[0].ammo.rounds=o),r.weapons[0]&&r.weapons[0].ammo&&(r.weapons[0].ammo.store=h),r.weapons[1]&&r.weapons[1].ammo&&(r.weapons[1].ammo.rounds=p),r.weapons[1]&&r.weapons[1].ammo&&(r.weapons[1].ammo.store=I),r.grenades=k,r.position={x:a,y:i,z:n},r.spawnShield=120,this.emit("playerRespawn",r))}#d(){const t=s.unPackInt8U(),e=s.unPackFloat(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackInt8U(),o=this.players[t];if(!o||o.id==this.me.id){for(let h=0;h<w;h++)s.unPackInt8U(),s.unPackRadU(),s.unPackRad(),s.unPackInt8U();return}o.position.x!==e&&(o.position.x=e),o.position.z!==i&&(o.position.z=i),(!o.jumping||Math.abs(o.position.y-a)>.5&&o.position.y!==a)&&(o.position.y=a),o.climbing!==n&&(o.climbing=n);for(let h=0;h<w;h++)s.unPackInt8U(),s.unPackRadU(),s.unPackRad(),s.unPackInt8U()}#u(){const t=s.unPackInt8U(),e=this.players[t];e&&(e.playing=!1,this.emit("playerPause",e))}#p(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];a&&(a.activeGun=e,this.emit("playerSwapWeapon",a,e))}#g(){const t=s.unPackInt8U(),e=s.unPackInt8U();s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U();const a=this.players[t],i=this.players[e];a&&(a.playing=!1,a.streak=0,a.lastDeathTime=Date.now(),a.hp=100,a.spawnShield=0),i&&i.streak++,this.emit("playerDeath",a,i)}#k(){const t=s.unPackInt8U();for(let i=0;i<6;i++)s.unPackFloat();const e=this.players[t];if(!e)return;const a=e.weapons[e.activeGun];a&&a.ammo&&(a.ammo.rounds--,this.emit("playerFire",e,a))}#I(){const t=s.unPackInt16U(),e=s.unPackInt8U(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat();this.game.collectables[e].push({id:t,x:a,y:i,z:n}),this.emit("spawnItem",e,t,{x:a,y:i,z:n})}#f(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackInt8U(),i=s.unPackInt16U(),n=this.players[t];if(this.game.collectables[e]=this.game.collectables[e].filter(o=>o.id!=i),e==T.AMMO){const o=n.weapons[a];o&&o.ammo&&(o.ammo.store=Math.min(o.ammo.storeMax,o.ammo.store+o.ammo.pickup),this.emit("collectAmmo",n,o))}e==T.GRENADE&&(n.grenades++,n.grenades>3&&(n.grenades=3),this.emit("collectGrenade",n))}#P(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;const i=a.hp;a.hp=e,this.emit("playerDamaged",a,i,a.hp)}#y(){const t=s.unPackInt8U();s.unPackFloat(),s.unPackFloat();const e=this.me.hp;this.me.hp=t,this.emit("selfDamaged",e,this.me.hp)}#w(){const t=s.unPackInt8U(),e=this.players[t];s.unPackInt8U();const a=s.unPackInt8U(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackFloat();if(s.unPackInt8U(),s.unPackInt8U(),s.unPackInt8U(),!e)return;this.state.serverStateIdx=a;const h=e.position.x,p=e.position.y,I=e.position.z;e.position.x=i,e.position.y=n,e.position.z=o,(h!=i||p!=n||I!=o)&&this.emit("selfMoved",e,{x:h,y:p,z:I},{x:i,y:n,z:o})}#U(){const t=f.getBuffer();t.packInt8(c.eventModifier),t.send(this.game.socket)}#b(){const t=s.unPackInt8U(),e={...this.players[t]};delete this.players[t.toString()],this.emit("playerLeave",e)}#S(){if(this.game.gameModeId==u.spatula){this.game.teamScore[1]=s.unPackInt16U(),this.game.teamScore[2]=s.unPackInt16U();const t={x:s.unPackFloat(),y:s.unPackFloat(),z:s.unPackFloat()},e=s.unPackInt8U(),a=s.unPackInt8U();this.game.spatula={coords:t,controlledBy:e,controlledByTeam:a},this.emit("gameStateChange",this.game)}else this.game.gameModeId==u.kotc?(this.game.stage=s.unPackInt8U(),this.game.zoneNumber=s.unPackInt8U(),this.game.capturing=s.unPackInt8U(),this.game.captureProgress=s.unPackInt16U(),this.game.numCapturing=s.unPackInt8U(),this.game.teamScore[1]=s.unPackInt8U(),this.game.teamScore[2]=s.unPackInt8U(),this.game.stageName=B[this.game.stage],this.game.capturePercent=this.game.captureProgress/1e3,this.game.activeZone=this.game.map.zones?this.game.map.zones[this.game.zoneNumber-1]:null,this.emit("gameStateChange",this.game)):this.game.gameModeId==u.team&&(this.game.teamScore[1]=s.unPackInt16U(),this.game.teamScore[2]=s.unPackInt16U());this.game.gameModeId!==u.spatula&&delete this.game.spatula,this.game.gameModeId!==u.kotc&&(delete this.game.stage,delete this.game.zoneNumber,delete this.game.capturing,delete this.game.captureProgress,delete this.game.numCapturing,delete this.game.stageName,delete this.game.numCapturing,delete this.game.activeZone),this.game.gameModeId==u.ffa&&delete this.game.teamScore}#x(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];switch(e){case m.HardBoiled:t===this.me.id&&(this.me.shieldHp=100),a.streakRewards.push(m.HardBoiled);break;case m.EggBreaker:a.streakRewards.push(m.EggBreaker);break;case m.Restock:{a.grenades=3,a.weapons[0]&&a.weapons[0].ammo&&(a.weapons[0].ammo.rounds=a.weapons[0].ammo.capacity,a.weapons[0].ammo.store=a.weapons[0].ammo.storeMax),a.weapons[1]&&a.weapons[1].ammo&&(a.weapons[1].ammo.rounds=a.weapons[1].ammo.capacity,a.weapons[1].ammo.store=a.weapons[1].ammo.storeMax);break}case m.OverHeal:a.hp=Math.min(200,a.hp+100),a.streakRewards.push(m.OverHeal);break;case m.DoubleEggs:a.streakRewards.push(m.DoubleEggs);break;case m.MiniEgg:a.streakRewards.push(m.MiniEgg);break}this.emit("playerBeginStreak",a,e)}#v(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];[m.EggBreaker,m.OverHeal,m.DoubleEggs,m.MiniEgg].includes(e)&&a.streakRewards.includes(e)&&(a.streakRewards=a.streakRewards.filter(n=>n!=e)),this.emit("playerEndStreak",e,a)}#C(){const t=s.unPackInt8U(),e=s.unPackInt8U();s.unPackFloat(),s.unPackFloat(),this.me.shieldHp=t,this.me.hp=e,this.me.shieldHp<=0?(this.me.streakRewards=this.me.streakRewards.filter(a=>a!=m.HardBoiled),this.emit("selfShieldLost")):this.emit("selfShieldHit",this.me.shieldHp)}#T(){const t={...this.game.options};let e=s.unPackInt8U(),a=s.unPackInt8U(),i=s.unPackInt8U();(e<1||e>4)&&(e=4),(a<0||a>8)&&(a=4),i>16&&(i=4),this.game.options.gravity=e/4,this.game.options.damage=a/4,this.game.options.healthRegen=i/4;const n=s.unPackInt8U();return Object.keys(G).forEach(o=>{const h=n&G[o]?1:0;this.game.options[o]=h}),this.game.options.weaponsDisabled=Array.from({length:7},()=>s.unPackInt8U()===1),this.game.options.mustUseSecondary=this.game.options.weaponsDisabled.every(o=>o),this.emit("gameOptionsChange",t,this.game.options),!1}#E(){const t=s.unPackInt8U();t==E.pause&&(this.emit("gameForcePause"),setTimeout(()=>this.me.playing=!1,3e3)),t==E.reset&&(Object.values(this.players).forEach(e=>e.streak=0),this.game.gameModeId!==u.ffa&&(this.game.teamScore=[0,0,0]),this.game.gameModeId===u.spatula&&(this.game.spatula.controlledBy=0,this.game.spatula.controlledByTeam=0,this.game.spatula.coords={x:0,y:0,z:0}),this.game.gameModeId===u.kotc&&(this.game.stage=y.capturing,this.game.zoneNumber=0,this.game.activeZone=null,this.game.capturing=0,this.game.captureProgress=0,this.game.numCapturing=0,this.game.stageName=B[y.capturing],this.game.capturePercent=0),this.emit("gameReset"))}#G(){if(!this.intents.includes(this.Intents.PING))return;const t=this.ping;this.ping=Date.now()-this.lastPingTime,this.emit("pingUpdate",t,this.ping),setTimeout(()=>{const e=f.getBuffer();e.packInt8(c.ping),e.send(this.game.socket),this.lastPingTime=Date.now()},this.pingInterval)}#F(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;const i=a.team;a.team=e,a.streak=0,this.emit("playerSwitchTeam",a,i,e)}#R(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=s.unPackInt16U(),i=s.unPackInt16U(),n=s.unPackInt8U(),o=s.unPackInt16U(),h=s.unPackInt16U(),p=s.unPackInt16U(),I=s.unPackInt16U();s.unPackInt8(),s.unPackInt8();const k=this.intents.includes(this.Intents.COSMETIC_DATA),r=k?d(a):a,L=k?d(i):i,N=k?d(o):o,D=k?d(h):h,$=k?d(p):p,_=k?d(I):I,l=this.players[t];if(l){const v={...l.character},C=l.selectedGun;l.character.eggColor=n,l.character.primaryGun=r,l.character.secondaryGun=L,l.character.stamp=D,l.character.hat=N,l.character.grenade=$,l.character.melee=_,l.selectedGun=e,l.weapons[0]=new X[e],C!==l.selectedGun&&this.emit("playerChangeGun",l,C,l.selectedGun),v!==l.character&&this.emit("playerChangeCharacter",l,v,l.character)}}#M(){const t=s.unPackInt32U(),e=this.account.eggBalance;this.account.eggBalance=t,this.emit("balanceUpdate",t-e,t)}#B(){this.me.playing=!1,this.emit("selfRespawnFail")}#A(){const t=s.unPackInt8U(),e=this.players[t];e&&this.emit("playerMelee",e)}#O(){const t=s.unPackInt8U(),e=this.players[t];if(!e)return;const a=e.weapons[e.activeGun];if(a.ammo){const i=Math.min(Math.min(a.ammo.capacity,a.ammo.reload)-a.ammo.rounds,a.ammo.store);a.ammo.rounds+=i,a.ammo.store-=i}this.emit("playerReload",e,a)}#L(){const t=f.getBuffer();t.packInt8(c.gameOptions),t.packInt8(this.game.options.gravity*4),t.packInt8(this.game.options.damage*4),t.packInt8(this.game.options.healthRegen*4);const e=(this.game.options.locked?1:0)|(this.game.options.noTeamChange?2:0)|(this.game.options.noTeamShuffle?4:0);t.packInt8(e),this.game.options.weaponsDisabled.forEach(a=>{t.packInt8(a?1:0)}),t.send(this.game.socket)}#N(){const t=s.unPackInt8U();let e=s.unPackInt16U();const a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackInt8U(),h=s.unPackFloat();this.intents.includes(this.Intents.COSMETIC_DATA)&&(e=d(e)),t==V.Grenade?this.emit("grenadeExploded",e,{x:a,y:i,z:n},o,h):this.emit("rocketHit",{x:a,y:i,z:n},o,h)}#D(){const t=s.unPackInt8U(),e=s.unPackFloat(),a=s.unPackFloat(),i=s.unPackFloat(),n=s.unPackFloat(),o=s.unPackFloat(),h=s.unPackFloat(),p=this.players[t];p&&(p.grenades--,this.emit("playerThrowGrenade",p,{x:e,y:a,z:i},{x:n,y:o,z:h}))}#$(){const t=s.unPackInt8U(),e=s.unPackInt8U(),a=this.players[t];if(!a)return;if(!this.intents.includes(this.Intents.CHALLENGES))return this.emit("challengeComplete",a,e);const i=this.account.challenges.find(n=>n.id==e);this.emit("challengeComplete",a,i),a.id==this.me.id&&this.refreshChallenges()}#_(){const t=f.getBuffer();t.packInt8(c.joinGame),t.packString(this.state.name),t.packString(this.game.raw.uuid),t.packInt8(0),t.packInt8(this.state.weaponIdx||this.account?.loadout?.classIdx||0),t.packInt32(this.account.session),t.packString(this.account.firebaseId),t.packString(this.account.sessionId),t.send(this.game.socket)}async#z(){if(this.me.id=s.unPackInt8U(),this.me.team=s.unPackInt8U(),this.game.gameModeId=s.unPackInt8U(),this.game.gameMode=A[this.game.gameModeId],this.game.mapIdx=s.unPackInt8U(),this.game.map=S[this.game.mapIdx],this.intents.includes(this.Intents.PATHFINDING)&&(this.game.map.raw=await et(this.game.map.filename,this.game.map.hash),this.pathing.nodeList=new tt(this.game.map.raw),this.game.gameModeId===u.kotc)){const e=this.game.map.raw.data["DYNAMIC.capture-zone.none"];e?this.game.map.zones=st(e):delete this.game.map.zones}this.game.playerLimit=s.unPackInt8U(),this.game.isGameOwner=s.unPackInt8U()==1,this.game.isPrivate=s.unPackInt8U()==1,s.unPackInt8U(),this.state.joinedGame=!0,this.lastDeathTime=Date.now();const t=f.getBuffer();if(t.packInt8(c.clientReady),t.send(this.game.socket),this.game.socket.onmessage=e=>this.processPacket(e.data),this.updateIntervalId=setInterval(()=>this.update(),100/3),this.intents.includes(this.Intents.PING)){this.lastPingTime=Date.now();const e=f.getBuffer();e.packInt8(c.ping),e.send(this.game.socket)}this.emit("gameReady")}processPacket(t){s.init(t),this.intents.includes(this.Intents.PACKET_HOOK)&&this.emit("packet",t);let e=0,a=0,i=!1;for(;s.isMoreDataAvailable()&&!i;){const n=s.unPackInt8U();switch(n){case c.syncThem:this.#d();break;case c.fire:this.#k();break;case c.hitThem:this.#P();break;case c.syncMe:this.#w();break;case c.hitMe:this.#y();break;case c.swapWeapon:this.#p();break;case c.collectItem:this.#f();break;case c.respawn:this.#m();break;case c.die:this.#g();break;case c.pause:this.#u();break;case c.chat:this.#h();break;case c.addPlayer:this.#l();break;case c.removePlayer:this.#b();break;case c.eventModifier:this.#U();break;case c.metaGameState:this.#S();break;case c.beginShellStreak:this.#x();break;case c.endShellStreak:this.#v();break;case c.hitMeHardBoiled:this.#C();break;case c.gameOptions:this.#T();break;case c.ping:this.#G();break;case c.switchTeam:this.#F();break;case c.changeCharacter:this.#R();break;case c.reload:this.#O();break;case c.explode:this.#N();break;case c.throwGrenade:this.#D();break;case c.spawnItem:this.#I();break;case c.melee:this.#A();break;case c.updateBalance:this.#M();break;case c.challengeCompleted:this.#$();break;case c.socketReady:this.#_();break;case c.gameJoined:this.#z();break;case c.gameAction:this.#E();break;case c.requestGameOptions:this.#L();break;case c.respawnDenied:this.#B();break;case c.expireUpgrade:case c.clientReady:break;case c.musicInfo:s.unPackLongString();break;default:console.error(`handlePacket: I got but did not handle a: ${Object.keys(c).find(o=>c[o]===n)} ${n}`),e&&console.error(`handlePacket: It may be a result of the ${e} command (${a}).`),i=!0;break}e=Object.keys(c).find(o=>c[o]===n),a=n,this.intents.includes(this.Intents.LOG_PACKETS)&&console.log(`[LOG_PACKETS] Packet ${e}: ${a}`)}}async checkChiknWinner(){const t=await g({cmd:"chicknWinnerReady",id:this.account.id,sessionId:this.account.sessionId});return typeof t=="string"?t:(this.account.cw.limit=t.limit,this.account.cw.atLimit=t.limit>=4,this.account.cw.secondsUntilPlay=(this.account.cw.atLimit?t.period:t.span)||0,this.account.cw.canPlayAgain=Date.now()+this.account.cw.secondsUntilPlay*1e3,this.account.cw)}async playChiknWinner(t=!0){if(this.account.cw.atLimit||this.account.cw.limit>Z)return"hit_daily_limit";if(this.account.cw.canPlayAgain>Date.now()&&t)return"on_cooldown";const e=await g({cmd:"incentivizedVideoReward",firebaseId:this.account.firebaseId,id:this.account.id,sessionId:this.account.sessionId,token:null},this.proxy,`${this.protocol}://${this.instance}`);return typeof e=="string"?e:e.error?e.error=="RATELIMITED"||e.error=="RATELMITED"?(await this.checkChiknWinner(),"on_cooldown"):e.error=="SESSION_EXPIRED"?"session_expired":(console.error("Unknown Chikn Winner response",e),"unknown_error"):e.reward?(this.account.eggBalance+=e.reward.eggsGiven,e.reward.itemIds.forEach(a=>this.account.ownedItemIds.push(a)),await this.checkChiknWinner(),e.reward):(console.error("Unknown Chikn Winner response",e),"unknown_error")}async resetChiknWinner(){if(this.account.eggBalance<200)return"not_enough_eggs";if(!this.account.cw.atLimit)return"not_at_limit";const t=await g({cmd:"chwReset",sessionId:this.account.sessionId});return typeof t=="string"?t:t.result!=="SUCCESS"?(console.error("Unknown Chikn Winner reset response",t),"unknown_error"):(this.account.eggBalance-=200,await this.checkChiknWinner(),this.account.cw)}canSee(t){if(!this.intents.includes(this.Intents.PATHFINDING))throw new Error("You must have the PATHFINDING intent to use this method.");return this.pathing.nodeList.hasLineOfSight(this.me.position,t.position)}getBestTarget(t=()=>!0){const a=Object.values(this.players).filter(n=>n?.playing).filter(n=>n.hp>0).filter(n=>n.id!==this.me.id).filter(n=>this.me.team===0||n.team!==this.me.team).filter(n=>!!t(n)).map(n=>({player:n,distance:Math.sqrt(Math.pow(n.position.x-this.me.position.x,2)+Math.pow(n.position.y-this.me.position.y,2)+Math.pow(n.position.z-this.me.position.z,2))})).sort((n,o)=>n.distance-o.distance);if(!a.length)return this.intents.includes(this.Intents.DEBUG_BEST_TARGET)&&console.log("no targets found"),null;const i=a.find(n=>this.canSee(n.player));return this.intents.includes(this.Intents.DEBUG_BEST_TARGET)&&(console.log("detected ",a.length,"targets"),console.log("closest target: ",a[0].player.name),console.log("all targets (ordered): ",a.map(n=>n.player.name)),console.log("found LoS player?",!!i),i&&console.log("closest LoS player: ",i.player.name)),i?{player:i.player,inLoS:!0}:{player:a[0].player,inLoS:!1}}async refreshChallenges(){const t=await g({cmd:"challengeGetDaily",sessionId:this.account.sessionId,playerId:this.account.id},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(t),this.account.challenges}async rerollChallenge(t){const e=await g({cmd:"challengeRerollSlot",sessionId:this.account.sessionId,slotId:t},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(e),this.account.challenges}async claimChallenge(t){const e=await g({cmd:"challengeClaimReward",sessionId:this.account.sessionId,slotId:t},this.proxy,`${this.protocol}://${this.instance}`);return this.#a(e.challenges),e.reward>0&&(this.account.eggBalance+=e.reward),{eggReward:e.reward,updatedChallenges:this.account.challenges}}async refreshBalance(){const t=await g({cmd:"checkBalance",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId},this.proxy,`${this.protocol}://${this.instance}`);return this.account.eggBalance=t.currentBalance,t.currentBalance}async redeemCode(t){const e=await g({cmd:"redeem",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,id:this.account.id,code:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"?(this.account.eggBalance=e.eggs_given,e.item_ids.forEach(a=>this.account.ownedItemIds.push(a)),{result:e,eggsGiven:e.eggs_given,itemIds:e.item_ids}):e}async claimURLReward(t){const e=await g({cmd:"urlRewardParams",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,reward:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance+=e.eggsGiven,e.itemIds.forEach(a=>this.account.ownedItemIds.push(a))),e}async claimSocialReward(t){const e=await g({cmd:"reward",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,rewardTag:t},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance+=e.eggsGiven,e.itemIds.forEach(a=>this.account.ownedItemIds.push(a))),e}async buyItem(t){const e=await g({cmd:"buy",firebaseId:this.account.firebaseId,sessionId:this.account.sessionId,itemId:t,save:!0},this.proxy,`${this.protocol}://${this.instance}`);return e.result==="SUCCESS"&&(this.account.eggBalance=e.currentBalance,this.account.ownedItemIds.push(e.itemId)),e}leave(t=K.mainMenu){this.state.quit||(t>-1&&(this.game?.socket?.close(t),this.state.left=!0,this.emit("leave")),clearInterval(this.updateIntervalId),this.#e=[],this.state.reloading=!1,this.state.swappingGun=!1,this.state.usingMelee=!1,this.state.stateIdx=0,this.state.serverStateIdx=0,this.state.shotsFired=0,this.state.buffer=[],this.players={},this.me=new U({}),this.game=this.#o,this.ping=0,this.lastPingTime=-1,this.lastDeathTime=-1,this.lastChatTime=-1,this.lastUpdateTick=0,this.controlKeys=0,this.pathing={nodeList:null,followingPath:!1,activePath:null,activeNode:null,activeNodeIdx:0})}logout(){this.account=this.#n}quit(t=!1){this.state.quit||(this.leave(),this.matchmaker&&(this.matchmaker.close(),this.matchmaker=null),t||(delete this.account,delete this.game,delete this.me,delete this.players),this.state.quit=!0,this.emit("quit"))}}var yt=it;export{it as Bot,yt as default};
@@ -36,16 +36,19 @@ export interface PlayerStats {
36
36
  bestOverallStreak: number;
37
37
  }
38
38
 
39
+ export type PlayerTeam = 0 | 1 | 2;
40
+ export type ShellColor = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13;
41
+
39
42
  export interface PlayerData {
40
43
  id: string;
41
44
  uniqueId: string;
42
45
  name: string;
43
46
  safename: string;
44
47
  charClass: number;
45
- team: 0 | 1 | 2;
48
+ team: PlayerTeam;
46
49
  primaryWeaponItem: Item | number;
47
50
  secondaryWeaponItem: Item | number;
48
- shellColor: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13;
51
+ shellColor: ShellColor;
49
52
  hatItem: Item | number;
50
53
  stampItem: Item | number;
51
54
  stampPosX: number;
@@ -86,9 +89,11 @@ export interface Social {
86
89
  active: boolean;
87
90
  }
88
91
 
92
+ export type PlayerWeapons = [AnyGun, Cluck9mm];
93
+
89
94
  export class GamePlayer {
90
95
  id: string;
91
- team: 0 | 1 | 2;
96
+ team: PlayerTeam;
92
97
  raw: PlayerData;
93
98
  name: string;
94
99
  uniqueId: string;
@@ -104,7 +109,7 @@ export class GamePlayer {
104
109
  stats: PlayerStats;
105
110
  activeGun: number;
106
111
  selectedGun: number;
107
- weapons: [AnyGun, Cluck9mm];
112
+ weapons: PlayerWeapons;
108
113
  grenades: number;
109
114
  streak: number;
110
115
  hp: number;
@@ -14,7 +14,7 @@ type intents = {
14
14
 
15
15
  import { NodeList } from '../pathing/mapnode.js';
16
16
 
17
- import { Character, GamePlayer } from './bot/GamePlayer';
17
+ import { Character, GamePlayer, Position } from './bot/GamePlayer';
18
18
  import { Challenge } from './constants/challenges';
19
19
  import { AnyGun } from './constants/guns';
20
20
  import { Map } from './constants/maps';
@@ -38,24 +38,26 @@ export interface ChiknWinnerStatus {
38
38
  canPlayAgain: number;
39
39
  }
40
40
 
41
+ export interface StatDamageTypes {
42
+ pistol: number;
43
+ grenade: number;
44
+ rpegg: number;
45
+ eggk: number;
46
+ scrambler: number;
47
+ ranger: number;
48
+ whpper: number;
49
+ crackshot: number;
50
+ trihard: number;
51
+ melee: number;
52
+ }
53
+
41
54
  export interface StatKD {
42
55
  total: number;
43
56
  mode: {
44
57
  public: number;
45
58
  private: number;
46
59
  };
47
- dmgType: {
48
- pistol: number;
49
- grenade: number;
50
- rpegg: number;
51
- eggk: number;
52
- scrambler: number;
53
- ranger: number;
54
- whpper: number;
55
- crackshot: number;
56
- trihard: number;
57
- melee: number;
58
- };
60
+ dmgType: StatDamageTypes;
59
61
  gameType: {
60
62
  kotc: number;
61
63
  spatula: number;
@@ -76,18 +78,20 @@ export interface Stats {
76
78
  };
77
79
  }
78
80
 
79
- export interface Challenges {
80
- raw: {
81
- challengeInfo: Challenge;
82
- challengeData: {
83
- period: number;
84
- challengeId: number;
85
- reset: number;
86
- claimed: number;
87
- completed: number;
88
- data: number;
89
- }
81
+ export interface RawChallenge {
82
+ challengeInfo: Challenge;
83
+ challengeData: {
84
+ period: number;
85
+ challengeId: number;
86
+ reset: number;
87
+ claimed: number;
88
+ completed: number;
89
+ data: number;
90
90
  }
91
+ }
92
+
93
+ export interface Challenges {
94
+ raw: RawChallenge;
91
95
  id: number;
92
96
  name: string;
93
97
  desc: string;
@@ -99,6 +103,19 @@ export interface Challenges {
99
103
  goalNum: number;
100
104
  }
101
105
 
106
+ export interface AccountLoadout {
107
+ hatId: number | null;
108
+ meleeId: number;
109
+ stampId: number | null;
110
+ classIdx: number;
111
+ colorIdx: number;
112
+ grenadeId: number;
113
+ primaryId: number[];
114
+ secondaryId: number[];
115
+ stampPositionX: number;
116
+ stampPositionY: number;
117
+ }
118
+
102
119
  export interface Account {
103
120
  id: number;
104
121
  firebaseId: string;
@@ -107,18 +124,7 @@ export interface Account {
107
124
  email: string;
108
125
  password: string;
109
126
  cw: ChiknWinnerStatus;
110
- loadout: {
111
- hatId: number | null;
112
- meleeId: number;
113
- stampId: number | null;
114
- classIdx: number;
115
- colorIdx: number;
116
- grenadeId: number;
117
- primaryId: number[];
118
- secondaryId: number[];
119
- stampPositionX: number;
120
- stampPositionY: number;
121
- };
127
+ loadout: AccountLoadout;
122
128
  ownedItemIds: number[];
123
129
  vip: boolean;
124
130
  accountAge: number;
@@ -157,38 +163,42 @@ export interface Zone {
157
163
  zone: number;
158
164
  }
159
165
 
166
+ export interface GameMap {
167
+ filename: string;
168
+ hash: string;
169
+ name: string;
170
+ modes: {
171
+ FFA: boolean;
172
+ Teams: boolean;
173
+ Spatula: boolean;
174
+ King: boolean;
175
+ };
176
+ availability: string;
177
+ numPlayers: string;
178
+ raw: Map;
179
+ zones: Zone[][];
180
+ }
181
+
182
+ export interface GameSpatula {
183
+ coords: Position;
184
+ controlledBy: number;
185
+ controlledByTeam: number;
186
+ }
187
+
160
188
  export interface Game {
161
189
  raw: RawGameData;
162
190
  code: string;
163
191
  gameModeId: number;
164
192
  gameMode: string;
165
193
  mapIdx: number;
166
- map: {
167
- filename: string;
168
- hash: string;
169
- name: string;
170
- modes: {
171
- FFA: boolean;
172
- Teams: boolean;
173
- Spatula: boolean;
174
- King: boolean;
175
- };
176
- availability: string;
177
- numPlayers: string;
178
- raw: Map;
179
- zones: Zone[][];
180
- };
194
+ map: GameMap;
181
195
  playerLimit: number;
182
196
  isGameOwner: boolean;
183
197
  isPrivate: boolean;
184
198
  options: GameOptions;
185
199
  collectables: Collectable[][];
186
200
  teamScore: number[];
187
- spatula: {
188
- coords: { x: number; y: number; z: number };
189
- controlledBy: number;
190
- controlledByTeam: number;
191
- };
201
+ spatula: GameSpatula;
192
202
  stage: number;
193
203
  zoneNumber: number;
194
204
  activeZone: Zone[];
@@ -282,7 +292,7 @@ export class Bot {
282
292
  on(event: 'gameReady', cb: () => void): void;
283
293
  on(event: 'gameReset', cb: () => void): void;
284
294
  on(event: 'gameStateChange', cb: (oldState: Game, newState: Game) => void): void;
285
- on(event: 'grenadeExploded', cb: (item: Item | number, pos: { x: number; y: number; z: number }, damage: number, radius: number) => void): void;
295
+ on(event: 'grenadeExploded', cb: (item: Item | number, pos: Position, damage: number, radius: number) => void): void;
286
296
  on(event: 'leave', cb: () => void): void;
287
297
  on(event: 'packet', cb: (packet: ArrayBuffer) => void): void;
288
298
  on(event: 'pingUpdate', cb: (oldPing: number, newPing: number) => void): void;
@@ -301,13 +311,13 @@ export class Bot {
301
311
  on(event: 'playerSwapWeapon', cb: (player: GamePlayer, nowActive: number) => void): void;
302
312
  on(event: 'playerSwitchTeam', cb: (player: GamePlayer, oldTeam: number, newTeam: number) => void): void;
303
313
  on(event: 'quit', cb: () => void): void;
304
- on(event: 'rocketHit', cb: (pos: { x: number; y: number; z: number }, damage: number, radius: number) => void): void;
314
+ on(event: 'rocketHit', cb: (pos: Position, damage: number, radius: number) => void): void;
305
315
  on(event: 'selfDamaged', cb: (oldHp: number, newHp: number) => void): void;
306
- on(event: 'selfMoved', cb: (oldPos: { x: number; y: number; z: number }, newPos: { x: number; y: number; z: number }) => void): void;
316
+ on(event: 'selfMoved', cb: (oldPos: Position, newPos: Position) => void): void;
307
317
  on(event: 'selfRespawnFail', cb: () => void): void;
308
318
  on(event: 'selfShieldHit', cb: (oldShield: number, newShield: number) => void): void;
309
319
  on(event: 'selfShieldLost', cb: () => void): void;
310
- on(event: 'spawnItem', cb: (type: number, _id: number, pos: { x: number; y: number; z: number }) => void): void;
320
+ on(event: 'spawnItem', cb: (type: number, itemId: number, pos: Position) => void): void;
311
321
  on(event: 'tick', cb: () => void): void;
312
322
 
313
323
  checkChiknWinner(): Promise<ChiknWinnerStatus>;
@@ -325,6 +335,7 @@ export class Bot {
325
335
  buyItem(itemId: number): Promise<{ result: string; currentBalance: number; itemId: number; }>;
326
336
 
327
337
  leave(code?: number): void;
338
+ logout(): void;
328
339
  quit(noCleanup?: boolean): void;
329
340
  }
330
341
 
@@ -18,15 +18,17 @@ declare class Gun {
18
18
  reloadTimeMod: number;
19
19
  }
20
20
 
21
+ export interface GunAmmo {
22
+ rounds: number;
23
+ capacity: number;
24
+ reload: number;
25
+ store: number;
26
+ storeMax: number;
27
+ pickup: number;
28
+ }
29
+
21
30
  declare class Eggk47 extends Gun {
22
- ammo: {
23
- rounds: number;
24
- capacity: number;
25
- reload: number;
26
- store: number;
27
- storeMax: number;
28
- pickup: number;
29
- };
31
+ ammo: GunAmmo;
30
32
  longReloadTime: number;
31
33
  shortReloadTime: number;
32
34
  weaponName: string;
@@ -43,14 +45,7 @@ declare class Eggk47 extends Gun {
43
45
  }
44
46
 
45
47
  declare class DozenGauge extends Gun {
46
- ammo: {
47
- rounds: number;
48
- capacity: number;
49
- reload: number;
50
- store: number;
51
- storeMax: number;
52
- pickup: number;
53
- };
48
+ ammo: GunAmmo;
54
49
  longReloadTime: number;
55
50
  shortReloadTime: number;
56
51
  weaponName: string;
@@ -69,14 +64,7 @@ declare class DozenGauge extends Gun {
69
64
  }
70
65
 
71
66
  declare class CSG1 extends Gun {
72
- ammo: {
73
- rounds: number;
74
- capacity: number;
75
- reload: number;
76
- store: number;
77
- storeMax: number;
78
- pickup: number;
79
- };
67
+ ammo: GunAmmo;
80
68
  hasScope: boolean;
81
69
  longReloadTime: number;
82
70
  shortReloadTime: number;
@@ -95,14 +83,7 @@ declare class CSG1 extends Gun {
95
83
  }
96
84
 
97
85
  declare class Cluck9mm extends Gun {
98
- ammo: {
99
- rounds: number;
100
- capacity: number;
101
- reload: number;
102
- store: number;
103
- storeMax: number;
104
- pickup: number;
105
- };
86
+ ammo: GunAmmo;
106
87
  longReloadTime: number;
107
88
  shortReloadTime: number;
108
89
  weaponName: string;
@@ -121,14 +102,7 @@ declare class Cluck9mm extends Gun {
121
102
  }
122
103
 
123
104
  declare class RPEGG extends Gun {
124
- ammo: {
125
- rounds: number;
126
- capacity: number;
127
- reload: number;
128
- store: number;
129
- storeMax: number;
130
- pickup: number;
131
- };
105
+ ammo: GunAmmo;
132
106
  hasScope: boolean;
133
107
  longReloadTime: number;
134
108
  shortReloadTime: number;
@@ -152,14 +126,7 @@ declare class RPEGG extends Gun {
152
126
  }
153
127
 
154
128
  declare class SMG extends Gun {
155
- ammo: {
156
- rounds: number;
157
- capacity: number;
158
- reload: number;
159
- store: number;
160
- storeMax: number;
161
- pickup: number;
162
- };
129
+ ammo: GunAmmo;
163
130
  longReloadTime: number;
164
131
  shortReloadTime: number;
165
132
  weaponName: string;
@@ -178,14 +145,7 @@ declare class SMG extends Gun {
178
145
  }
179
146
 
180
147
  declare class M24 extends Gun {
181
- ammo: {
182
- rounds: number;
183
- capacity: number;
184
- reload: number;
185
- store: number;
186
- storeMax: number;
187
- pickup: number;
188
- };
148
+ ammo: GunAmmo;
189
149
  hasScope: boolean;
190
150
  longReloadTime: number;
191
151
  shortReloadTime: number;
@@ -206,14 +166,7 @@ declare class M24 extends Gun {
206
166
  }
207
167
 
208
168
  declare class AUG extends Gun {
209
- ammo: {
210
- rounds: number;
211
- capacity: number;
212
- reload: number;
213
- store: number;
214
- storeMax: number;
215
- pickup: number;
216
- };
169
+ ammo: GunAmmo;
217
170
  longReloadTime: number;
218
171
  shortReloadTime: number;
219
172
  weaponName: string;
@@ -1,21 +1,24 @@
1
+ import { Position } from '../bot/GamePlayer';
2
+
3
+ export type ItemTypeIds = 1 | 2 | 3 | 4 | 5 | 6 | 7;
4
+ export type ItemTypeNames = 'Hat' | 'Stamp' | 'Primary' | 'Secondary' | 'Melee' | 'Grenade';
5
+ export type ClassIds = 0 | 1 | 2 | 3 | 4 | 5 | 6;
6
+ export type UnlockMethods = 'default' | 'purchase' | 'physical' | 'manual' | 'premium' | 'vip';
7
+
1
8
  export interface Item {
2
9
  id: number;
3
10
  name: string;
4
11
  price: number;
5
- item_type_id: 1 | 2 | 3 | 4 | 5 | 6 | 7;
6
- item_type_name: 'Hat' | 'Stamp' | 'Primary' | 'Secondary' | 'Melee' | 'Grenade';
7
- exclusive_for_class: null | 0 | 1 | 2 | 3 | 4 | 5 | 6;
12
+ item_type_id: ItemTypeIds;
13
+ item_type_name: ItemTypeNames;
14
+ exclusive_for_class: ClassIds;
8
15
  item_data: {
9
16
  meshName: string;
10
17
  tags: string[];
11
18
  };
12
19
  is_available: boolean;
13
- unlock: 'default' | 'purchase' | 'physical' | 'manual' | 'premium' | 'vip';
14
- align: {
15
- x: number;
16
- y: number;
17
- z: number;
18
- };
20
+ unlock: UnlockMethods;
21
+ align: Position;
19
22
  }
20
23
 
21
24
  export const Items: Item[];
@@ -1,3 +1,5 @@
1
+ import { Position } from '../bot/GamePlayer';
2
+
1
3
  export interface MapModes {
2
4
  FFA: boolean;
3
5
  Teams: boolean;
@@ -30,11 +32,7 @@ export interface MapData {
30
32
  }
31
33
 
32
34
  export interface MapSun {
33
- direction: {
34
- x: number;
35
- y: number;
36
- z: number;
37
- }
35
+ direction: Position;
38
36
  color: string;
39
37
  }
40
38
 
@@ -72,14 +70,16 @@ export interface MapExtents {
72
70
  depth: number;
73
71
  }
74
72
 
73
+ export interface MapFog {
74
+ density: string;
75
+ color: string;
76
+ }
77
+
75
78
  export interface MapJSON {
76
79
  fileVersion: number;
77
80
  sun: MapSun;
78
81
  ambient: string;
79
- fog: {
80
- density: string;
81
- color: string;
82
- }
82
+ fog: MapFog;
83
83
  data: MapData;
84
84
  palette: string[];
85
85
  render: MapRender;
@@ -1,10 +1,5 @@
1
1
  import Bot from '../bot';
2
-
3
- type Position = {
4
- x: number;
5
- y: number;
6
- z: number;
7
- }
2
+ import { Position } from '../bot/GamePlayer';
8
3
 
9
4
  export declare class LookAtPosDispatch {
10
5
  pos: Position;
@@ -1,4 +1,6 @@
1
+ import { Zone } from './bot';
2
+ import { Position } from './bot/GamePlayer';
1
3
  import { MapJSON } from './constants/maps';
2
4
 
3
5
  export declare function fetchMap(name: string, hash: string): Promise<MapJSON>;
4
- export declare function initKotcZones(meshData: Array<{ x: number; y: number; z: number }>): Array<Array<{ x: number; y: number; z: number; zone: number }>>;
6
+ export declare function initKotcZones(meshData: Array<Position>): Array<Array<Zone>>;