├── tsconfig.json ├── index.d.ts ├── README.md ├── Traveler.ts ├── LICENSE └── Traveler.js /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "sourceMap": false 6 | } 7 | } -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | interface PathfinderReturn { 2 | path: RoomPosition[]; 3 | ops: number; 4 | cost: number; 5 | incomplete: boolean; 6 | } 7 | 8 | interface TravelToReturnData { 9 | nextPos?: RoomPosition; 10 | pathfinderReturn?: PathfinderReturn; 11 | state?: TravelState; 12 | path?: string; 13 | } 14 | 15 | interface TravelToOptions { 16 | ignoreRoads?: boolean; 17 | ignoreCreeps?: boolean; 18 | ignoreStructures?: boolean; 19 | preferHighway?: boolean; 20 | highwayBias?: number; 21 | allowHostile?: boolean; 22 | allowSK?: boolean; 23 | range?: number; 24 | obstacles?: {pos: RoomPosition}[]; 25 | roomCallback?: (roomName: string, matrix: CostMatrix) => CostMatrix | boolean; 26 | routeCallback?: (roomName: string) => number; 27 | returnData?: TravelToReturnData; 28 | restrictDistance?: number; 29 | useFindRoute?: boolean; 30 | maxOps?: number; 31 | movingTarget?: boolean; 32 | freshMatrix?: boolean; 33 | offRoad?: boolean; 34 | stuckValue?: number; 35 | maxRooms?: number; 36 | repath?: number; 37 | route?: {[roomName: string]: boolean}; 38 | ensurePath?: boolean; 39 | } 40 | 41 | interface TravelData { 42 | state: any[]; 43 | path: string; 44 | } 45 | 46 | interface TravelState { 47 | stuckCount: number; 48 | lastCoord: Coord; 49 | destination: RoomPosition; 50 | cpu: number; 51 | } 52 | 53 | interface Creep { 54 | travelTo(destination: HasPos|RoomPosition, ops?: TravelToOptions): number; 55 | } 56 | 57 | type Coord = {x: number, y: number}; 58 | type HasPos = {pos: RoomPosition} 59 | 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Traveler 2 | 3 | Traveler is a general-purpose tool for moving your creeps around. This version is forked from bonzaiferroni. Feel free to fork and use in other projects. 4 | - TypeScript is not updated. Please feel free to push it to me. 5 | #### Features: 6 | * Efficient path-caching and CPU-use (you can see how it compares with `creep.moveTo()` [here](https://github.com/bonzaiferroni/bonzAI/wiki/Improving-on-moveTo's-efficiency)) 7 | * Ignores creeps in pathing by default which allows for fewer PathFinder calls and [single-lane creep movement](https://github.com/bonzaiferroni/screepswiki/blob/master/gifs/s33-moveTo.gif) 8 | * Can detect hostile rooms and will [path around them once discovered](https://github.com/bonzaiferroni/bonzAI/wiki/Improving-on-moveTo's-efficiency#long-distances-path-length-400). 9 | * Effective [long-range pathing](https://github.com/bonzaiferroni/bonzAI/wiki/Improving-on-moveTo's-efficiency#very-long-distances-path-length-1200) 10 | * [Lots of options](https://github.com/bonzaiferroni/Traveler/wiki/Traveler-API) 11 | * [Visuals](https://github.com/bonzaiferroni/Traveler/wiki/Improving-Traveler:-Features#show-your-path) 12 | * [Intershard travel] Finds nearby portals and moves to the optimal position to get to the next shard. The more portals you find, the shorter the path across shards. 13 | * [Save on road maintenance] Creeps will path off of roads if they have enough move parts to transverse plains and swamps without losing time. 14 | * [Pushing/Swapping] If a creep is in the way, it will either push that creep towards the target, or swap with it if that creep is a lower priority. Use creep.Move() 15 | 16 | ![Push/Swap animation](https://i.imgur.com/w050niD.gif) 17 | 18 | ## Installation 19 | 20 | 1. Download Traveler.js into a new file using the screeps console. 21 | 22 | 2. Add a require statement to `main.js`: 23 | * `const Traveler = require('Traveler');` 24 | * (in the sim or some private servers you might need to use `'Traveler.js'`) 25 | 3. Replace situations where you used `moveTo` with `Move(target, range, priority, options)`. 26 | ``` 27 | creep.Move(myDestination, range, priority, opts = {}); (see wiki for more) 28 | ``` 29 | 30 | ![Installation animation](http://i.imgur.com/hUu0ozU.gif) 31 | 32 | #### Performance considerations 33 | 1. `Move` creates a new object in creep memory, `_trav`, which is analogous to the object used by `moveTo()` for caching the creeps path. For this reason, it will save memory to use either `Move()` or `moveTo()` with a given creep, but not both. 34 | 2. moveOffRoad() should be used only when needed. This function has a cooldown of 20 ticks to avoid spamming CPU. 35 | 36 | ## WishList 37 | - Intergrated quad/squad movement logic. This is being debated as to whether it should be allowed. Please send me your feedback. 38 | - Intergrated retreat logic. 39 | 40 | ## Documentation 41 | 42 | The file itself has comments, and you can also find documentation [in the wiki](https://github.com/crazydubc/Traveler/wiki). I'm also looking for feedback and collaboration to improve Traveler, pull requests welcome! 43 | 44 | ## Changelog 45 | 2021-03-26 46 | * OPTIMIZATION: Creeps will now force a push if they are on an exit tile. 47 | * BUG FIX: Protection for the user added. Traveler will now verify the range passed will land the creep in the destination room. Previously if you passed a range, pathfinder would potentially path to a location in an adjacent room. Thanks ChewbaccaWarrior for the report! 48 | * Other minor bug fixes and optimizations reported by several users. 49 | 50 | 2021-03-10 51 | * OPTIMIZATION: Minor speed optimizations 52 | * BUG FIX: Added a check to make sure map visuals are not near the limit prior to commanding a new visual. Don't ask me who used that entire bucket... 53 | * OPTIMIZATION: Packrat now added into portal caching. 54 | * BUG FIX: Fixed issue with cleaning up paths. 55 | * Path caching is now disabled by default. There is an issue where if a room massively changes road wise, creeps may use the cached path which is rendered less effective until an undate of that cache is called for. I will leave this up to the user until I think of a better solution. 56 | 57 | 2021-02-05 58 | * BUG FIX: Reported bug from the old traveler by msgerbs. Added room-level granularity to structure and creep matrix. Previously not all rooms requiring a cache update would update. 59 | * NEW: Added path caching and management. Paths are compressed to save memory space and are managed via user options. By default a max 1500 paths with a length of 5 moves or more are stored (you can change this in the options). Thanks to Muon for the [code snippets](https://github.com/bencbartlett/screeps-packrat) I stole and should be compatible with Muons snippets. 60 | 61 | 2021-01-27 62 | * BUG FIX: Changed path finding logic. Pathfinder can only take whole numbers and traveler has been changed to reflect that. This is a beta test.. But so far so good. Please provide input if you see something off. 63 | * OPTIMIZATION: Added Options.heuristic 64 | * Two VERY minor speed optimizations 65 | 66 | 2021-01-24 67 | * BUG FIX: Creeps would sometimes take a longer path to stay off roads when there was a shorter viable path. Fixed. Creeps will now always take the shortest path and only path off roads if it will cost no extra moves. 68 | 69 | 2021-01-15 70 | * BUG FIX: fixed a bug calculating creep move efficiency. 71 | * OPTIMIZATION: InterShard portal logic will now get, store, and use ALL shard portals when moving between shards. No need to scout them out! 72 | * OPTIMIZATION: Creeps will now attempt to stay off of roads if they have enough body parts to out fatigue plains/swamps. Due to restrictions in the built in path finder this is not 100%. This optimization saves on road wear and tear. 73 | * OPTIMIZATION: If a creep needs to push past a fat slow moving creep, the faster creep will swap with the slow one in order to pass instead of repathing. 74 | 75 | 2020-12-28 76 | * OPTIMIZATIONS: Traveler now gets all shard portals. This wont be commanded unless you are doing intershard movement. Working CPU optimizations on this and usage of room portals soon. 77 | 78 | 2020-12-25 79 | * Happy Holidays! 80 | * NEW: Alpha testing of creep/powerCreep.MoveToShard. See wiki for usage. 81 | * OPTIMIZATIONS: Traveler will now use Memory.Traveler to store all data except creep pathing. Traveler will store room information and portal locations here for users to reference. Makes it easier to uninstall if you decide not to use it at a later time. 82 | 83 | 2020-12-21 84 | * BUG FIX: Fixed two edge cases. One of which will set the range to 0 if the target is an exit tile to protect the user from themselves. 85 | 86 | 2020-12-17 87 | * BUG FIX: Changed a bit of logic around that could cause creeps to repath instead of passing each other. Thanks Misty for testing it. 88 | 89 | 2020-12-16 90 | * OPTIMIZATION/BUG FIX: Several changes to the push/swap logic. Now more effecient and a few edge cases eliminated thanks to MistySenpai's testing and reporting. 91 | 92 | 2020-12-14 93 | * OPTIMIZATION: Major optimizations in moveOffRoad. CPU usage reduced to an average of 0.25 from 0.7. 94 | * NEW: creep.Move() is the new standard and creep.travelTo is depreciated. Please see the wiki for usage. 95 | * FIX: Creeps will now push to other adjacent spots to that target and the creep when being pushed. 96 | * OTHER: minor bug fixes and quality of life improvements on the backend. 97 | * REMOVED: creep.MoveToRange() has been removed and merged into creep.Move() 98 | 99 | 2020-12-13 100 | * Recursive push added. Creeps will send a 'push' option to one another to force a move. 101 | * CPU optimization in push logic. Travel will now wait 1 tick prior to push and use significantly less CPU. 102 | * Traveler will now automatically look at a creeps body composition and determine if it can ignore roads and use swamps without fatigue. 103 | * Bug fix from u.283 involving power creeps. Thanks! If we are ever in prison together, I will watch your back in the shower. 104 | 105 | 2020-12-12 106 | * Initial build of this fork 107 | * Added swapping and pushing of creeps in the way. Pass {priority: number} to traveler (default is 1) to utilize swapping. If a creep is a higher priority, it will swap with the creep in the movement direction. 108 | * Traveler keeps track of when the last move was. This is used for the above logic. 109 | * Added function for moving a creep offroad when working on a target. 110 | * Added PowerCreep support for traveler 111 | * Other various quality of life functions 112 | * Code cleaned up by MistySenpai. Thanks! -------------------------------------------------------------------------------- /Traveler.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * To start using Traveler, require it in main.js: 3 | * Example: var Traveler = require('Traveler.js'); 4 | */ 5 | 6 | export class Traveler { 7 | 8 | private static structureMatrixCache: {[roomName: string]: CostMatrix} = {}; 9 | private static creepMatrixCache: {[roomName: string]: CostMatrix} = {}; 10 | private static creepMatrixTick: number; 11 | private static structureMatrixTick: number; 12 | 13 | /** 14 | * move creep to destination 15 | * @param creep 16 | * @param destination 17 | * @param options 18 | * @returns {number} 19 | */ 20 | 21 | public static travelTo(creep: Creep, destination: HasPos|RoomPosition, options: TravelToOptions = {}): number { 22 | 23 | // uncomment if you would like to register hostile rooms entered 24 | // this.updateRoomStatus(creep.room); 25 | 26 | if (!destination) { 27 | return ERR_INVALID_ARGS; 28 | } 29 | 30 | if (creep.fatigue > 0) { 31 | Traveler.circle(creep.pos, "aqua", .3); 32 | return ERR_TIRED; 33 | } 34 | 35 | destination = this.normalizePos(destination); 36 | 37 | // manage case where creep is nearby destination 38 | let rangeToDestination = creep.pos.getRangeTo(destination); 39 | if (options.range && rangeToDestination <= options.range) { 40 | return OK; 41 | } else if (rangeToDestination <= 1) { 42 | if (rangeToDestination === 1 && !options.range) { 43 | let direction = creep.pos.getDirectionTo(destination); 44 | if (options.returnData) { 45 | options.returnData.nextPos = destination; 46 | options.returnData.path = direction.toString(); 47 | } 48 | return creep.move(direction); 49 | } 50 | return OK; 51 | } 52 | 53 | // initialize data object 54 | if (!creep.memory._trav) { 55 | delete creep.memory._travel; 56 | creep.memory._trav = {}; 57 | } 58 | let travelData = creep.memory._trav as TravelData; 59 | 60 | let state = this.deserializeState(travelData, destination); 61 | 62 | // uncomment to visualize destination 63 | // this.circle(destination.pos, "orange"); 64 | 65 | // check if creep is stuck 66 | if (this.isStuck(creep, state)) { 67 | state.stuckCount++; 68 | Traveler.circle(creep.pos, "magenta", state.stuckCount * .2); 69 | } else { 70 | state.stuckCount = 0; 71 | } 72 | 73 | // handle case where creep is stuck 74 | if (!options.stuckValue) { options.stuckValue = DEFAULT_STUCK_VALUE; } 75 | if (state.stuckCount >= options.stuckValue && Math.random() > .5) { 76 | options.ignoreCreeps = false; 77 | options.freshMatrix = true; 78 | delete travelData.path; 79 | } 80 | 81 | // TODO:handle case where creep moved by some other function, but destination is still the same 82 | 83 | // delete path cache if destination is different 84 | if (!this.samePos(state.destination, destination)) { 85 | if (options.movingTarget && state.destination.isNearTo(destination)) { 86 | travelData.path += state.destination.getDirectionTo(destination); 87 | state.destination = destination; 88 | } else { 89 | delete travelData.path; 90 | } 91 | } 92 | 93 | if (options.repath && Math.random() < options.repath) { 94 | // add some chance that you will find a new path randomly 95 | delete travelData.path; 96 | } 97 | 98 | // pathfinding 99 | let newPath = false; 100 | if (!travelData.path) { 101 | newPath = true; 102 | if (creep.spawning) { return ERR_BUSY; } 103 | 104 | state.destination = destination; 105 | 106 | let cpu = Game.cpu.getUsed(); 107 | let ret = this.findTravelPath(creep.pos, destination, options); 108 | 109 | let cpuUsed = Game.cpu.getUsed() - cpu; 110 | state.cpu = _.round(cpuUsed + state.cpu); 111 | if (state.cpu > REPORT_CPU_THRESHOLD) { 112 | // see note at end of file for more info on this 113 | console.log(`TRAVELER: heavy cpu use: ${creep.name}, cpu: ${state.cpu} origin: ${ 114 | creep.pos}, dest: ${destination}`); 115 | } 116 | 117 | let color = "orange"; 118 | if (ret.incomplete) { 119 | // uncommenting this is a great way to diagnose creep behavior issues 120 | // console.log(`TRAVELER: incomplete path for ${creep.name}`); 121 | color = "red"; 122 | } 123 | 124 | if (options.returnData) { 125 | options.returnData.pathfinderReturn = ret; 126 | } 127 | 128 | travelData.path = Traveler.serializePath(creep.pos, ret.path, color); 129 | state.stuckCount = 0; 130 | } 131 | 132 | this.serializeState(creep, destination, state, travelData); 133 | 134 | if (!travelData.path || travelData.path.length === 0) { 135 | return ERR_NO_PATH; 136 | } 137 | 138 | // consume path 139 | if (state.stuckCount === 0 && !newPath) { 140 | travelData.path = travelData.path.substr(1); 141 | } 142 | 143 | let nextDirection = parseInt(travelData.path[0], 10); 144 | if (options.returnData) { 145 | if (nextDirection) { 146 | let nextPos = Traveler.positionAtDirection(creep.pos, nextDirection); 147 | if (nextPos) { options.returnData.nextPos = nextPos; } 148 | } 149 | options.returnData.state = state; 150 | options.returnData.path = travelData.path; 151 | } 152 | return creep.move(nextDirection); 153 | } 154 | 155 | /** 156 | * make position objects consistent so that either can be used as an argument 157 | * @param destination 158 | * @returns {any} 159 | */ 160 | 161 | public static normalizePos(destination: HasPos|RoomPosition): RoomPosition { 162 | if (!(destination instanceof RoomPosition)) { 163 | return destination.pos; 164 | } 165 | return destination; 166 | } 167 | 168 | /** 169 | * check if room should be avoided by findRoute algorithm 170 | * @param roomName 171 | * @returns {RoomMemory|number} 172 | */ 173 | 174 | public static checkAvoid(roomName: string) { 175 | return Memory.rooms && Memory.rooms[roomName] && Memory.rooms[roomName].avoid; 176 | } 177 | 178 | /** 179 | * check if a position is an exit 180 | * @param pos 181 | * @returns {boolean} 182 | */ 183 | 184 | public static isExit(pos: Coord): boolean { 185 | return pos.x === 0 || pos.y === 0 || pos.x === 49 || pos.y === 49; 186 | } 187 | 188 | /** 189 | * check two coordinates match 190 | * @param pos1 191 | * @param pos2 192 | * @returns {boolean} 193 | */ 194 | 195 | public static sameCoord(pos1: Coord, pos2: Coord): boolean { 196 | return pos1.x === pos2.x && pos1.y === pos2.y; 197 | } 198 | 199 | /** 200 | * check if two positions match 201 | * @param pos1 202 | * @param pos2 203 | * @returns {boolean} 204 | */ 205 | 206 | public static samePos(pos1: RoomPosition, pos2: RoomPosition) { 207 | return this.sameCoord(pos1, pos2) && pos1.roomName === pos2.roomName; 208 | } 209 | 210 | /** 211 | * draw a circle at position 212 | * @param pos 213 | * @param color 214 | * @param opacity 215 | */ 216 | 217 | public static circle(pos: RoomPosition, color: string, opacity?: number) { 218 | new RoomVisual(pos.roomName).circle(pos, { 219 | radius: .45, fill: "transparent", stroke: color, strokeWidth: .15, opacity: opacity}); 220 | } 221 | 222 | /** 223 | * update memory on whether a room should be avoided based on controller owner 224 | * @param room 225 | */ 226 | 227 | public static updateRoomStatus(room: Room) { 228 | if (!room) { return; } 229 | if (room.controller) { 230 | if (room.controller.owner && !room.controller.my) { 231 | room.memory.avoid = 1; 232 | } else { 233 | delete room.memory.avoid; 234 | } 235 | } 236 | } 237 | 238 | /** 239 | * find a path from origin to destination 240 | * @param origin 241 | * @param destination 242 | * @param options 243 | * @returns {PathfinderReturn} 244 | */ 245 | 246 | public static findTravelPath(origin: RoomPosition|HasPos, destination: RoomPosition|HasPos, 247 | options: TravelToOptions = {}): PathfinderReturn { 248 | 249 | _.defaults(options, { 250 | ignoreCreeps: true, 251 | maxOps: DEFAULT_MAXOPS, 252 | range: 1, 253 | }); 254 | 255 | if (options.movingTarget) { 256 | options.range = 0; 257 | } 258 | 259 | origin = this.normalizePos(origin); 260 | destination = this.normalizePos(destination); 261 | let originRoomName = origin.roomName; 262 | let destRoomName = destination.roomName; 263 | 264 | // check to see whether findRoute should be used 265 | let roomDistance = Game.map.getRoomLinearDistance(origin.roomName, destination.roomName); 266 | let allowedRooms = options.route; 267 | if (!allowedRooms && (options.useFindRoute || (options.useFindRoute === undefined && roomDistance > 2))) { 268 | let route = this.findRoute(origin.roomName, destination.roomName, options); 269 | if (route) { allowedRooms = route; } 270 | } 271 | 272 | let roomsSearched = 0; 273 | 274 | let callback = (roomName: string): CostMatrix | boolean => { 275 | 276 | if (allowedRooms) { 277 | if (!allowedRooms[roomName]) { 278 | return false; 279 | } 280 | } else if (!options.allowHostile && Traveler.checkAvoid(roomName) 281 | && roomName !== destRoomName && roomName !== originRoomName) { 282 | return false; 283 | } 284 | 285 | roomsSearched++; 286 | 287 | let matrix; 288 | let room = Game.rooms[roomName]; 289 | if (room) { 290 | if (options.ignoreStructures) { 291 | matrix = new PathFinder.CostMatrix(); 292 | if (!options.ignoreCreeps) { 293 | Traveler.addCreepsToMatrix(room, matrix); 294 | } 295 | } else if (options.ignoreCreeps || roomName !== originRoomName) { 296 | matrix = this.getStructureMatrix(room, options.freshMatrix); 297 | } else { 298 | matrix = this.getCreepMatrix(room); 299 | } 300 | 301 | if (options.obstacles) { 302 | matrix = matrix.clone(); 303 | for (let obstacle of options.obstacles) { 304 | if (obstacle.pos.roomName !== roomName) { continue; } 305 | matrix.set(obstacle.pos.x, obstacle.pos.y, 0xff); 306 | } 307 | } 308 | } 309 | 310 | if (options.roomCallback) { 311 | if (!matrix) { matrix = new PathFinder.CostMatrix(); } 312 | let outcome = options.roomCallback(roomName, matrix.clone()); 313 | if (outcome !== undefined) { 314 | return outcome; 315 | } 316 | } 317 | 318 | return matrix as CostMatrix; 319 | }; 320 | 321 | let ret = PathFinder.search(origin, {pos: destination, range: options.range!}, { 322 | maxOps: options.maxOps, 323 | maxRooms: options.maxRooms, 324 | plainCost: options.offRoad ? 1 : options.ignoreRoads ? 1 : 2, 325 | swampCost: options.offRoad ? 1 : options.ignoreRoads ? 5 : 10, 326 | roomCallback: callback, 327 | } ); 328 | 329 | if (ret.incomplete && options.ensurePath) { 330 | 331 | if (options.useFindRoute === undefined) { 332 | 333 | // handle case where pathfinder failed at a short distance due to not using findRoute 334 | // can happen for situations where the creep would have to take an uncommonly indirect path 335 | // options.allowedRooms and options.routeCallback can also be used to handle this situation 336 | if (roomDistance <= 2) { 337 | console.log(`TRAVELER: path failed without findroute, trying with options.useFindRoute = true`); 338 | console.log(`from: ${origin}, destination: ${destination}`); 339 | options.useFindRoute = true; 340 | ret = this.findTravelPath(origin, destination, options); 341 | console.log(`TRAVELER: second attempt was ${ret.incomplete ? "not " : ""}successful`); 342 | return ret; 343 | } 344 | 345 | // TODO: handle case where a wall or some other obstacle is blocking the exit assumed by findRoute 346 | } else { 347 | 348 | } 349 | } 350 | 351 | return ret; 352 | } 353 | 354 | /** 355 | * find a viable sequence of rooms that can be used to narrow down pathfinder's search algorithm 356 | * @param origin 357 | * @param destination 358 | * @param options 359 | * @returns {{}} 360 | */ 361 | 362 | public static findRoute(origin: string, destination: string, 363 | options: TravelToOptions = {}): {[roomName: string]: boolean } | void { 364 | 365 | let restrictDistance = options.restrictDistance || Game.map.getRoomLinearDistance(origin, destination) + 10; 366 | let allowedRooms = { [ origin ]: true, [ destination ]: true }; 367 | 368 | let highwayBias = 1; 369 | if (options.preferHighway) { 370 | highwayBias = 2.5; 371 | if (options.highwayBias) { 372 | highwayBias = options.highwayBias; 373 | } 374 | } 375 | 376 | let ret = Game.map.findRoute(origin, destination, { 377 | routeCallback: (roomName: string) => { 378 | 379 | if (options.routeCallback) { 380 | let outcome = options.routeCallback(roomName); 381 | if (outcome !== undefined) { 382 | return outcome; 383 | } 384 | } 385 | 386 | let rangeToRoom = Game.map.getRoomLinearDistance(origin, roomName); 387 | if (rangeToRoom > restrictDistance) { 388 | // room is too far out of the way 389 | return Number.POSITIVE_INFINITY; 390 | } 391 | 392 | if (!options.allowHostile && Traveler.checkAvoid(roomName) && 393 | roomName !== destination && roomName !== origin) { 394 | // room is marked as "avoid" in room memory 395 | return Number.POSITIVE_INFINITY; 396 | } 397 | 398 | let parsed; 399 | if (options.preferHighway) { 400 | parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName) as any; 401 | let isHighway = (parsed[1] % 10 === 0) || (parsed[2] % 10 === 0); 402 | if (isHighway) { 403 | return 1; 404 | } 405 | } 406 | // SK rooms are avoided when there is no vision in the room, harvested-from SK rooms are allowed 407 | if (!options.allowSK && !Game.rooms[roomName]) { 408 | if (!parsed) { parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName) as any; } 409 | let fMod = parsed[1] % 10; 410 | let sMod = parsed[2] % 10; 411 | let isSK = !(fMod === 5 && sMod === 5) && 412 | ((fMod >= 4) && (fMod <= 6)) && 413 | ((sMod >= 4) && (sMod <= 6)); 414 | if (isSK) { 415 | return 10 * highwayBias; 416 | } 417 | } 418 | 419 | return highwayBias; 420 | }, 421 | }); 422 | 423 | if (!_.isArray(ret)) { 424 | console.log(`couldn't findRoute to ${destination}`); 425 | return; 426 | } 427 | for (let value of ret) { 428 | allowedRooms[value.room] = true; 429 | } 430 | 431 | return allowedRooms; 432 | } 433 | 434 | /** 435 | * check how many rooms were included in a route returned by findRoute 436 | * @param origin 437 | * @param destination 438 | * @returns {number} 439 | */ 440 | 441 | public static routeDistance(origin: string, destination: string): number | void { 442 | let linearDistance = Game.map.getRoomLinearDistance(origin, destination); 443 | if (linearDistance >= 32) { 444 | return linearDistance; 445 | } 446 | 447 | let allowedRooms = this.findRoute(origin, destination); 448 | if (allowedRooms) { 449 | return Object.keys(allowedRooms).length; 450 | } 451 | } 452 | 453 | /** 454 | * build a cost matrix based on structures in the room. Will be cached for more than one tick. Requires vision. 455 | * @param room 456 | * @param freshMatrix 457 | * @returns {any} 458 | */ 459 | 460 | public static getStructureMatrix(room: Room, freshMatrix?: boolean): CostMatrix { 461 | if (!this.structureMatrixCache[room.name] || (freshMatrix && Game.time !== this.structureMatrixTick)) { 462 | this.structureMatrixTick = Game.time; 463 | let matrix = new PathFinder.CostMatrix(); 464 | this.structureMatrixCache[room.name] = Traveler.addStructuresToMatrix(room, matrix, 1); 465 | } 466 | return this.structureMatrixCache[room.name]; 467 | } 468 | 469 | /** 470 | * build a cost matrix based on creeps and structures in the room. Will be cached for one tick. Requires vision. 471 | * @param room 472 | * @returns {any} 473 | */ 474 | 475 | public static getCreepMatrix(room: Room) { 476 | if (!this.creepMatrixCache[room.name] || Game.time !== this.creepMatrixTick) { 477 | this.creepMatrixTick = Game.time; 478 | this.creepMatrixCache[room.name] = Traveler.addCreepsToMatrix(room, 479 | this.getStructureMatrix(room, true).clone()); 480 | } 481 | return this.creepMatrixCache[room.name]; 482 | } 483 | 484 | /** 485 | * add structures to matrix so that impassible structures can be avoided and roads given a lower cost 486 | * @param room 487 | * @param matrix 488 | * @param roadCost 489 | * @returns {CostMatrix} 490 | */ 491 | 492 | public static addStructuresToMatrix(room: Room, matrix: CostMatrix, roadCost: number): CostMatrix { 493 | 494 | let impassibleStructures: Structure[] = []; 495 | for (let structure of room.find(FIND_STRUCTURES)) { 496 | if (structure instanceof StructureRampart) { 497 | if (!structure.my && !structure.isPublic) { 498 | impassibleStructures.push(structure); 499 | } 500 | } else if (structure instanceof StructureRoad) { 501 | matrix.set(structure.pos.x, structure.pos.y, roadCost); 502 | } else if (structure instanceof StructureContainer) { 503 | matrix.set(structure.pos.x, structure.pos.y, 5); 504 | } else { 505 | impassibleStructures.push(structure); 506 | } 507 | } 508 | 509 | for (let site of room.find(FIND_MY_CONSTRUCTION_SITES)) { 510 | if (site.structureType === STRUCTURE_CONTAINER || site.structureType === STRUCTURE_ROAD 511 | || site.structureType === STRUCTURE_RAMPART) { continue; } 512 | matrix.set(site.pos.x, site.pos.y, 0xff); 513 | } 514 | 515 | for (let structure of impassibleStructures) { 516 | matrix.set(structure.pos.x, structure.pos.y, 0xff); 517 | } 518 | 519 | return matrix; 520 | } 521 | 522 | /** 523 | * add creeps to matrix so that they will be avoided by other creeps 524 | * @param room 525 | * @param matrix 526 | * @returns {CostMatrix} 527 | */ 528 | 529 | public static addCreepsToMatrix(room: Room, matrix: CostMatrix): CostMatrix { 530 | room.find(FIND_CREEPS).forEach((creep: Creep) => matrix.set(creep.pos.x, creep.pos.y, 0xff) ); 531 | return matrix; 532 | } 533 | 534 | /** 535 | * serialize a path, traveler style. Returns a string of directions. 536 | * @param startPos 537 | * @param path 538 | * @param color 539 | * @returns {string} 540 | */ 541 | 542 | public static serializePath(startPos: RoomPosition, path: RoomPosition[], color = "orange"): string { 543 | let serializedPath = ""; 544 | let lastPosition = startPos; 545 | this.circle(startPos, color); 546 | for (let position of path) { 547 | if (position.roomName === lastPosition.roomName) { 548 | new RoomVisual(position.roomName) 549 | .line(position, lastPosition, {color: color, lineStyle: "dashed"}); 550 | serializedPath += lastPosition.getDirectionTo(position); 551 | } 552 | lastPosition = position; 553 | } 554 | return serializedPath; 555 | } 556 | 557 | /** 558 | * returns a position at a direction relative to origin 559 | * @param origin 560 | * @param direction 561 | * @returns {RoomPosition} 562 | */ 563 | 564 | public static positionAtDirection(origin: RoomPosition, direction: number): RoomPosition | void { 565 | let offsetX = [0, 0, 1, 1, 1, 0, -1, -1, -1]; 566 | let offsetY = [0, -1, -1, 0, 1, 1, 1, 0, -1]; 567 | let x = origin.x + offsetX[direction]; 568 | let y = origin.y + offsetY[direction]; 569 | if (x > 49 || x < 0 || y > 49 || y < 0) { return; } 570 | return new RoomPosition(x, y, origin.roomName); 571 | } 572 | 573 | /** 574 | * convert room avoidance memory from the old pattern to the one currently used 575 | * @param cleanup 576 | */ 577 | 578 | public static patchMemory(cleanup = false) { 579 | if (!Memory.empire) { return; } 580 | if (!Memory.empire.hostileRooms) { return; } 581 | let count = 0; 582 | for (let roomName in Memory.empire.hostileRooms) { 583 | if (Memory.empire.hostileRooms[roomName]) { 584 | if (!Memory.rooms[roomName]) { Memory.rooms[roomName] = {} as any; } 585 | Memory.rooms[roomName].avoid = 1; 586 | count++; 587 | } 588 | if (cleanup) { 589 | delete Memory.empire.hostileRooms[roomName]; 590 | } 591 | } 592 | if (cleanup) { 593 | delete Memory.empire.hostileRooms; 594 | } 595 | 596 | console.log(`TRAVELER: room avoidance data patched for ${count} rooms`); 597 | } 598 | 599 | private static deserializeState(travelData: TravelData, destination: RoomPosition): TravelState { 600 | let state = {} as TravelState; 601 | if (travelData.state) { 602 | state.lastCoord = {x: travelData.state[STATE_PREV_X], y: travelData.state[STATE_PREV_Y] }; 603 | state.cpu = travelData.state[STATE_CPU]; 604 | state.stuckCount = travelData.state[STATE_STUCK]; 605 | state.destination = new RoomPosition(travelData.state[STATE_DEST_X], travelData.state[STATE_DEST_Y], 606 | travelData.state[STATE_DEST_ROOMNAME]); 607 | } else { 608 | state.cpu = 0; 609 | state.destination = destination; 610 | } 611 | return state; 612 | } 613 | 614 | private static serializeState(creep: Creep, destination: RoomPosition, state: TravelState, travelData: TravelData) { 615 | travelData.state = [creep.pos.x, creep.pos.y, state.stuckCount, state.cpu, destination.x, destination.y, 616 | destination.roomName]; 617 | } 618 | 619 | private static isStuck(creep: Creep, state: TravelState): boolean { 620 | let stuck = false; 621 | if (state.lastCoord !== undefined) { 622 | if (this.sameCoord(creep.pos, state.lastCoord)) { 623 | // didn't move 624 | stuck = true; 625 | } else if (this.isExit(creep.pos) && this.isExit(state.lastCoord)) { 626 | // moved against exit 627 | stuck = true; 628 | } 629 | } 630 | 631 | return stuck; 632 | } 633 | } 634 | 635 | // this might be higher than you wish, setting it lower is a great way to diagnose creep behavior issues. When creeps 636 | // need to repath to often or they aren't finding valid paths, it can sometimes point to problems elsewhere in your code 637 | const REPORT_CPU_THRESHOLD = 1000; 638 | 639 | const DEFAULT_MAXOPS = 20000; 640 | const DEFAULT_STUCK_VALUE = 2; 641 | const STATE_PREV_X = 0; 642 | const STATE_PREV_Y = 1; 643 | const STATE_STUCK = 2; 644 | const STATE_CPU = 3; 645 | const STATE_DEST_X = 4; 646 | const STATE_DEST_Y = 5; 647 | const STATE_DEST_ROOMNAME = 6; 648 | 649 | // assigns a function to Creep.prototype: creep.travelTo(destination) 650 | Creep.prototype.travelTo = function(destination: RoomPosition|{pos: RoomPosition}, options?: TravelToOptions) { 651 | return Traveler.travelTo(this, destination, options); 652 | }; 653 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Traveler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", {value: true}); 3 | class Traveler { 4 | static travelTo(creep, destination, options = {}) { 5 | // initialize data object 6 | if (!creep.memory._trav) { 7 | delete creep.memory._travel; 8 | creep.memory._trav = {}; 9 | } 10 | if (!Memory.Traveler) { 11 | Memory.Traveler = {}; 12 | Memory.Traveler.rooms = {}; 13 | } 14 | if (global.TravelerPathCacheClean !== Game.time) { 15 | global.TravelerPathCacheClean = Game.time 16 | this.cleanCacheByUsage(1) 17 | } 18 | this.updateRoomStatus(creep.room); 19 | if (!destination) { 20 | return ERR_INVALID_ARGS; 21 | } 22 | if (creep.fatigue > 0) { 23 | Traveler.circle(creep.pos, "aqua", .3); 24 | return ERR_TIRED; 25 | } 26 | if (creep.memory._trav.lastMove === Game.time) { 27 | return OK; 28 | } 29 | //initialize our options 30 | const range = options.range ? options.range : 1; 31 | const priority = options.priority ? options.priority : 1; 32 | destination = this.normalizePos(destination); 33 | // manage case where creep is nearby destination 34 | let rangeToDestination = creep.pos.getRangeTo(destination); 35 | if (!this.isExit(creep.pos) && destination.roomName === creep.pos.roomName) { 36 | if (options.range && rangeToDestination <= options.range) { 37 | return OK; 38 | } 39 | else if (rangeToDestination <= 1) { 40 | if (rangeToDestination === 1 && !options.range) { 41 | let direction = creep.pos.getDirectionTo(destination); 42 | if (options.returnData) { 43 | options.returnData.nextPos = destination; 44 | options.returnData.path = direction.toString(); 45 | } 46 | creep.memory._trav.lastMove = Game.time; 47 | return creep.move(direction); 48 | } 49 | return OK; 50 | } 51 | } 52 | 53 | //get body movement Efficiency and adjust options automatically 54 | const muscle = this.getCreepMoveEfficiency(creep); 55 | options.muscle = muscle //sets this hidden option to allow calculation into findPath. 56 | 57 | if (muscle >= 2) options.ignoreRoads = true; //able to out fatigue plains 58 | if (muscle >= 10) options.offRoad = true; //able to out fatigue swamps 59 | 60 | let travelData = creep.memory._trav; 61 | let state = this.deserializeState(travelData, destination); 62 | creep.memory._trav.lastMove = Game.time; 63 | // uncomment to visualize destination 64 | // this.circle(destination, "orange"); 65 | // check if creep is stuck 66 | if (this.isStuck(creep, state)) { 67 | state.stuckCount++; 68 | Traveler.circle(creep.pos, "magenta", state.stuckCount * .2); 69 | } else { 70 | state.stuckCount = 0; 71 | } 72 | // handle case where creep is stuck 73 | if (!options.stuckValue) { 74 | options.stuckValue = DEFAULT_STUCK_VALUE; 75 | } 76 | if (!options.push) { 77 | options.push = false; 78 | } 79 | if (state.stuckCount >= options.stuckValue && Math.random() > .5) { 80 | options.ignoreCreeps = false; 81 | options.freshMatrix = true; 82 | delete travelData.path; 83 | } 84 | // TODO:handle case where creep moved by some other function, but destination is still the same 85 | // delete path cache if destination is different 86 | if (!this.samePos(state.destination, destination)) { 87 | if (options.movingTarget && state.destination.isNearTo(destination)) { 88 | travelData.path += state.destination.getDirectionTo(destination); 89 | state.destination = destination; 90 | } else { 91 | delete travelData.path; 92 | } 93 | } 94 | //if a swap is called due to a slow moving creep 95 | if (travelData.swap) { 96 | const blocker = Game.getObjectById(travelData.swap) 97 | if (blocker && creep.pos.isNearTo(blocker)) { 98 | //console.log(Game.shard.name + ' Swapping ' + creep.name + ' with fast mover ' + blocker.name + ' ' + blocker.pos) 99 | creep.moveTo((blocker)) 100 | blocker.moveTo(creep) 101 | delete creep.memory._trav.path 102 | delete creep.memory._trav.swap 103 | delete blocker.memory._trav.path 104 | return OK 105 | } else { 106 | delete creep.memory._trav.swap 107 | } 108 | } 109 | if (options.repath && Math.random() < options.repath) { 110 | // add some chance that you will find a new path randomly 111 | delete travelData.path; 112 | } 113 | // pathfinding 114 | let newPath = false; 115 | if (!travelData.path) { 116 | newPath = true; 117 | if (creep.spawning) { 118 | return ERR_BUSY; 119 | } 120 | let ret = {}; 121 | state.destination = destination; 122 | let cpu = Game.cpu.getUsed(); 123 | ret.path = this.getPath(creep.pos, destination, options.muscle); 124 | if (!ret.path) { 125 | ret = this.findTravelPath(creep.pos, destination, options); 126 | } else { 127 | travelData.path = ret.path 128 | ret.incomplete = false; 129 | //console.log(Game.shard.name + ' cached path retrieved in ' + (Game.cpu.getUsed()-cpu)) 130 | } 131 | let cpuUsed = Game.cpu.getUsed() - cpu; 132 | state.cpu = _.round(cpuUsed + state.cpu); 133 | if (state.cpu > REPORT_CPU_THRESHOLD) { 134 | // see note at end of file for more info on this 135 | console.log(Game.shard.name +' TRAVELER: heavy cpu use: ' + creep.name + ', cpu: ' + state.cpu + ' origin: ' + creep.pos + ', dest: ' + destination); 136 | creep.memory._trav = {} 137 | } 138 | let color = "orange"; 139 | if (ret.incomplete) { 140 | // uncommenting this is a great way to diagnose creep behavior issues 141 | // console.log(`TRAVELER: incomplete path for ${creep.name}`); 142 | color = "red"; 143 | } 144 | if (options.returnData) { 145 | options.returnData.pathfinderReturn = ret; 146 | } 147 | if (!travelData.path) { 148 | travelData.path = Traveler.serializePath(creep.pos, ret.path, color); 149 | } 150 | if (travelData.path.length >= MIN_CACHED_PATH_LENGTH) { 151 | this.addPath(creep.pos, destination, travelData.path, options.muscle); 152 | } 153 | state.stuckCount = 0; 154 | } 155 | this.serializeState(creep, destination, state, travelData); 156 | if (!travelData.path || travelData.path.length === 0) { 157 | return ERR_NO_PATH; 158 | } 159 | // consume path 160 | if (state.stuckCount === 0 && !newPath) { 161 | travelData.path = travelData.path.substr(1); 162 | } 163 | let nextDirection = parseInt(travelData.path[0], 10); 164 | if (options.returnData) { 165 | if (nextDirection) { 166 | let nextPos = Traveler.positionAtDirection(creep.pos, nextDirection); 167 | if (nextPos) { 168 | options.returnData.nextPos = nextPos; 169 | } 170 | } 171 | options.returnData.state = state; 172 | options.returnData.path = travelData.path; 173 | } 174 | 175 | //Don't push 176 | if (!(state.stuckCount > 0 || options.push || this.isExit(creep.pos))) { 177 | return creep.move(nextDirection); 178 | } 179 | //Find if a creep is blocking our movement 180 | const blocker = creep.pos.findInRange(FIND_MY_CREEPS, 1, {filter: c => creep.pos.getDirectionTo(c) === nextDirection})[0]; 181 | if (blocker) { 182 | //ignore if fatigued and creeps that have already moved. 183 | if (!blocker.memory._trav || !blocker.memory._trav.target) { 184 | //hasn't run yet... Lets swap in case the creep is idle 185 | this.travelTo(blocker, creep.pos, {range: 0}); //swap 186 | if (blocker.memory._trav){ 187 | if (blocker.memory._trav.state) blocker.memory._trav.state[STATE_STUCK] = 999; //force repath in case it moved out of range 188 | } 189 | } else { 190 | if (blocker.memory._trav.lastMove < Game.time-2) { //blocker has not moved for 2 ticks.. Working or idle 191 | if (!blocker.fatigue) { //no fatigue, should be idle or poorly built. 192 | const blockerPriority = blocker.memory._trav.target.priority; 193 | const blockerTarget = new RoomPosition(blocker.memory._trav.target.x, blocker.memory._trav.target.y, blocker.memory._trav.target.roomName); 194 | const blockerRange = blocker.memory._trav.target.range; 195 | const currentRange = blocker.pos.getRangeTo(blockerTarget); 196 | //Can we move closer? 197 | if (currentRange > 1) { 198 | this.travelTo(blocker,blockerTarget, {push: true, range: 1, repath: true}); //push blocker closer to target 199 | } else { 200 | //if a higher priority, swap 201 | if (priority > blockerPriority) { 202 | //move to a new free position if able 203 | if (!this.moveToNewFreePosition(blocker, blockerTarget)) { 204 | this.travelTo(blocker, creep.pos, {push:true, range: 0}); 205 | delete blocker.memory._trav.path; //force repath in case it moved out of range 206 | } 207 | } else { 208 | if (blockerRange !== 0) { 209 | //less than or equal priority.. Can you move the blocker to an adjacent position and make room for us? 210 | if (!this.moveToNewFreePosition(blocker, blockerTarget)){ 211 | return this.repath(creep, destination, options); 212 | } 213 | } else { 214 | return this.repath(creep, destination, options); 215 | } 216 | } 217 | } 218 | } else { //blocker is fatigued, lets go around 219 | //Check for slow moving creep. 220 | const blockerMuscle = this.getCreepMoveEfficiency(blocker); 221 | const Muscle = this.getCreepMoveEfficiency(creep); 222 | if (blockerMuscle > Muscle) { 223 | //console.log(creep.name + ' Swapping slow blocker, memory set for ' + blocker.name + ' ' + blocker.pos) 224 | blocker.memory._trav.swap = creep.id; 225 | return creep.move(nextDirection); 226 | } else { 227 | return this.repath(creep, destination, options); 228 | } 229 | } 230 | } 231 | } 232 | } 233 | return creep.move(nextDirection); 234 | } 235 | //calls a same tick repath 236 | static repath(creep, destination, options) { 237 | creep.memory._trav.state[STATE_STUCK] = 999; //artificially set it to stuck and repath 238 | creep.memory._trav.lastMove = 0; 239 | options.repath = 1; 240 | return this.travelTo(creep, destination, options); 241 | 242 | } 243 | //Finds a new free position near the target and moves there 244 | static moveToNewFreePosition(blocker, blockerTarget) { 245 | const newPosition = this.findNewFreePosition(blocker, blockerTarget); 246 | if (newPosition) { 247 | this.travelTo(blocker, newPosition, {range: 0, push: true}); 248 | return true; 249 | } 250 | return false; 251 | } 252 | //normalized to desitnations passed to a position instead of a object with a pos in it 253 | static normalizePos(destination) { 254 | if (!(destination instanceof RoomPosition)) { 255 | return destination.pos; 256 | } 257 | return destination; 258 | } 259 | //registers the target with traveler for push logic 260 | static registerTarget(creep, target, range, priority) { 261 | if (!target) return; 262 | if (!creep) return; 263 | if (target.pos) target = target.pos; 264 | if (!range) range = 1; 265 | if (!priority) priority = 1; 266 | if (!creep.memory._trav) creep.memory._trav = {}; 267 | if (this.isExit(target)) range = 0 //protect the user from themselves. If it is an edge tile, we need a value of zero 268 | creep.memory._trav.target = {x: target.x, y: target.y, roomName: target.roomName, range: range, priority: priority}; 269 | } 270 | //get an x grid in a direction from a start point 271 | static GetXFromDirection(dir, sp) { 272 | return dir === LEFT || dir === TOP_LEFT || dir === BOTTOM_LEFT ? 273 | sp - 1 274 | : 275 | dir === RIGHT || dir === TOP_RIGHT || dir === BOTTOM_RIGHT ? 276 | sp + 1 277 | : 278 | sp; 279 | } 280 | //get an y grid in a direction from a start point 281 | static GetYFromDirection(dir, sp) { 282 | return dir === TOP || dir === TOP_LEFT || dir === TOP_RIGHT ? 283 | sp - 1 284 | : 285 | dir === BOTTOM || dir === BOTTOM_LEFT || dir === BOTTOM_RIGHT ? 286 | sp + 1 287 | : 288 | sp; 289 | } 290 | //finds and returns a new free position nearby to move to relative to it's target 291 | static findNewFreePosition(creep, target) { 292 | let direction = creep.pos.getDirectionTo(target);//get direction to target 293 | let positions = []; //hold positions we can move to 294 | let offsets = {}; 295 | let curDirection; 296 | switch(direction) { 297 | case TOP: 298 | case LEFT: 299 | case RIGHT: 300 | case BOTTOM: 301 | curDirection = direction -3; 302 | if (curDirection < 1) curDirection += 8; 303 | for (let i = 0; i < 5; i++){ 304 | curDirection += 1; 305 | if (curDirection > 8) curDirection -= 8; 306 | if (i === 2) continue; //don't move to the target 307 | offsets[_.size(offsets)] = {x: this.GetXFromDirection(curDirection, creep.pos.x), y: this.GetYFromDirection(curDirection, creep.pos.y)}; 308 | } 309 | break; 310 | case TOP_RIGHT: 311 | case BOTTOM_RIGHT: 312 | case BOTTOM_LEFT: 313 | case TOP_LEFT: 314 | curDirection = direction -2; 315 | if (curDirection < 1) curDirection += 8; 316 | for (let i = 0; i < 3; i++){ 317 | curDirection += 1; 318 | if (curDirection > 8) curDirection -= 8; 319 | if (i === 1) continue; //don't move to the target 320 | offsets[_.size(offsets)] = {x: this.GetXFromDirection(curDirection, creep.pos.x), y: this.GetYFromDirection(curDirection, creep.pos.y)}; 321 | } 322 | break; 323 | } 324 | const t = new Room.Terrain(creep.room.name); 325 | const structureMatrix = this.getStructureMatrix(creep.room, {freshMatrix: false}); 326 | const creepMatrix = this.getCreepMatrix(creep.room, false); 327 | for (let o in offsets) { 328 | //Out of bounds/exit 329 | if (offsets[o].x <= 0 || offsets[o].x >= 49 || offsets[o].y <= 0 || offsets[o].y >= 49) { 330 | continue; 331 | } 332 | //don't try to move on a wall. 333 | if (t.get(offsets[o].x,offsets[o].y) === TERRAIN_MASK_WALL) { 334 | continue; 335 | } 336 | if (structureMatrix.get(offsets[o].x, offsets[o].y) < 255 // No impassable structures 337 | && creepMatrix.get(offsets[o].x, offsets[o].y) < 255) { //no creep there 338 | return new RoomPosition(offsets[o].x, offsets[o].y, creep.room.name); 339 | } 340 | } 341 | return; 342 | } 343 | //moves to a nearby off of a road position 344 | static moveOffRoad(creep, targetpos, distance, priority) { 345 | if (!creep.memory._trav) { 346 | creep.memory._trav = {}; 347 | } 348 | if (!creep.memory._trav.offroad) { 349 | creep.memory._trav.offroad = 0; 350 | } 351 | if (creep.memory._trav.lastMove === Game.time) { 352 | return false; 353 | } 354 | if (creep.memory._trav.offroad > Game.time - 20) { 355 | return false; 356 | } 357 | // see if we are offroad 358 | if (!_.some(creep.pos.lookFor(LOOK_STRUCTURES), (s) => s instanceof StructureRoad)) { 359 | return true; 360 | } 361 | const t = new Room.Terrain(creep.room.name); 362 | const structureMatrix = this.getStructureMatrix(creep.room, {freshMatrix: false}); 363 | const creepMatrix = this.getCreepMatrix(creep.room, false); 364 | let positions = []; 365 | let offsets = [] 366 | for (let x = -distance; x <= distance; x++) { 367 | offsets.push(x); // ah, push it 368 | } 369 | // find each valid position around the target that does not have a road 370 | _.forEach(offsets, (x) => _.forEach(offsets, (y) => { 371 | let xpos = targetpos.x + x ; 372 | let ypos = targetpos.y + y; 373 | //not out of bounds/exit 374 | if (!(xpos <= 0 || xpos >= 49 || ypos <= 0 || ypos >= 49)) { 375 | if (t.get(x,y) !== TERRAIN_MASK_WALL//don't try to move on a wall. 376 | && structureMatrix.get(xpos, ypos) < 255 // No impassable structures 377 | && creepMatrix.get(xpos, ypos) < 255) { //no creep there 378 | positions.push(new RoomPosition(xpos, ypos, creep.room.name)); //ah, push it 379 | } 380 | } 381 | })); 382 | if (_.size(positions) === 0) { 383 | creep.memory._trav.offroad = Game.time; //don't spam this function if it fails! 384 | return false; // no positions, move towards the target to make room for people behind them 385 | } 386 | let posit = creep.pos.findClosestByPath(positions); // find the closest position to the creep 387 | return this.travelTo(creep, posit, {range: 0, priority: priority}); // move to that position 388 | } 389 | //gets the move efficiency of a creep based on it's number of move parts and boost realative to it's size 390 | static getCreepMoveEfficiency(creep) { 391 | if (!creep.body) return 9999; //no fatgiue! PowerCreep! 392 | let totalreduction= 0; 393 | let totalparts = 0; 394 | let used = creep.store.getUsedCapacity(); 395 | creep.body.forEach((b) => { 396 | switch(b.type) { 397 | case MOVE: 398 | totalreduction += b.hits > 0 ? b.boost ? (BOOSTS[b.type][b.boost].fatigue * -2) : -2 : 0; 399 | return; 400 | break; 401 | case CARRY: 402 | if (used > 0 && b.hits > 0) { 403 | used -= b.boost ? (BOOSTS[b.type][b.boost].capacity * CARRY_CAPACITY) : CARRY_CAPACITY; 404 | totalparts += 1; 405 | } 406 | break; 407 | default: 408 | totalparts += 1; 409 | break; 410 | } 411 | }) 412 | return totalparts > 0 ? 0-totalreduction/totalparts : totalreduction; 413 | } 414 | //check if room should be avoided by findRoute algorithm 415 | static checkAvoid(roomName) { 416 | return Memory.Traveler.rooms[roomName] && Memory.Traveler.rooms[roomName].avoid 417 | } 418 | //check if a position is an exit 419 | static isExit(pos) { 420 | return pos.x === 0 || pos.y === 0 || pos.x === 49 || pos.y === 49; 421 | } 422 | //check two coordinates match 423 | static sameCoord(pos1, pos2) { 424 | return pos1.x === pos2.x && pos1.y === pos2.y; 425 | } 426 | //check if two positions match 427 | static samePos(pos1, pos2) { 428 | return this.sameCoord(pos1, pos2) && pos1.roomName === pos2.roomName; 429 | } 430 | //draw a circle at position 431 | static circle(pos, color, opacity) { 432 | if(Game.map.visual.getSize() >= 1000000) { 433 | return 434 | } 435 | new RoomVisual(pos.roomName).circle(pos, { 436 | radius: .45, 437 | fill: "transparent", 438 | stroke: color, 439 | strokeWidth: .15, 440 | opacity: opacity, 441 | }); 442 | } 443 | //update memory on whether a room should be avoided based on controller owner 444 | //TODO: Add whitelist functionality..or add your own..whatever 445 | static updateRoomStatus(room) { 446 | if (!room) { 447 | return; 448 | } 449 | if (!Memory.Traveler) { 450 | Memory.Traveler = {} 451 | } 452 | if (!Memory.Traveler.rooms) { 453 | Memory.Traveler.rooms = {} 454 | } 455 | if (!Memory.Traveler.rooms[room.name]) { 456 | Memory.Traveler.rooms[room.name] = {} 457 | } 458 | if (room.controller) { 459 | if ((room.controller.owner && !room.controller.my) || (room.controller.reservation && room.controller.reservation.username !== MY_USERNAME)) { 460 | Memory.Traveler.rooms[room.name].avoid = 1 461 | } else { 462 | delete Memory.Traveler.rooms[room.name].avoid 463 | } 464 | } 465 | } 466 | //find a path from origin to destination 467 | static findTravelPath(origin, destination, options = {}) { 468 | _.defaults(options, { 469 | ignoreCreeps: true, 470 | maxOps: DEFAULT_MAXOPS, 471 | range: 1, 472 | }); 473 | if (options.movingTarget) { 474 | options.range = 0; 475 | } 476 | origin = this.normalizePos(origin); 477 | destination = this.normalizePos(destination); 478 | let originRoomName = origin.roomName; 479 | let destRoomName = destination.roomName; 480 | // check to see whether findRoute should be used 481 | let roomDistance = Game.map.getRoomLinearDistance(origin.roomName, destination.roomName); 482 | let allowedRooms = options.route; 483 | let heuristic = options.heuristic ? options.heuristic : 1.2 484 | if (!allowedRooms && (options.useFindRoute || (options.useFindRoute === undefined && roomDistance > 2))) { 485 | let route = this.findRoute(origin.roomName, destination.roomName, options); 486 | if (route) { 487 | allowedRooms = route; 488 | } 489 | } 490 | let roomsSearched = 0; 491 | let callback = (roomName) => { 492 | if (allowedRooms) { 493 | if (!allowedRooms[roomName]) { 494 | return false; 495 | } 496 | } else if (!options.allowHostile && Traveler.checkAvoid(roomName) && roomName !== destRoomName && roomName !== originRoomName) { 497 | return false; 498 | } 499 | roomsSearched++; 500 | let matrix; 501 | let room = Game.rooms[roomName]; 502 | if (room) { 503 | if (options.ignoreStructures) { 504 | matrix = new PathFinder.CostMatrix(); 505 | if (!options.ignoreCreeps) { 506 | Traveler.addCreepsToMatrix(room, matrix); 507 | } 508 | } else if (options.ignoreCreeps || roomName !== originRoomName) { 509 | matrix = this.getStructureMatrix(room, options); 510 | } else { 511 | matrix = this.getCreepMatrix(room); 512 | } 513 | if (options.obstacles) { 514 | matrix = matrix.clone(); 515 | for (let obstacle of options.obstacles) { 516 | if (obstacle.pos.roomName !== roomName) { 517 | continue; 518 | } 519 | matrix.set(obstacle.pos.x, obstacle.pos.y, 0xff); 520 | } 521 | } 522 | } 523 | if (options.roomCallback) { 524 | if (!matrix) { 525 | matrix = new PathFinder.CostMatrix(); 526 | } 527 | let outcome = options.roomCallback(roomName, matrix.clone()); 528 | if (outcome !== undefined) { 529 | return outcome; 530 | } 531 | } 532 | return matrix; 533 | }; 534 | let range = options.range 535 | //protect the user. make sure the range will not place them outside the target room. 536 | //this can lead to invalid pathing or a creep pathing to a position outside the room 537 | //the destination is in. We will compensate for that here. 538 | if (origin.roomName !== destination.roomName && range > 1) { 539 | if (destination.x + range > 48) { 540 | range = destination.x === 49 ? 0 : 48 - destination.x 541 | } else if (destination.y + range > 48) { 542 | range = destination.x === 49 ? 0 : 48 - destination.y 543 | } else if (range >= destination.x) { 544 | range = destination.x > 0 ? destination.x-1 : 0 545 | } else if (range >= destination.y) { 546 | range = destination.y > 0 ? destination.y-1 : 0 547 | } 548 | } 549 | let ret = PathFinder.search(origin, { 550 | pos: destination, 551 | range: range, 552 | }, { 553 | maxOps: options.maxOps, 554 | maxRooms: options.maxRooms, 555 | //Regular Creep road 1, plains 2, swamp 10 | path regular road 1, plains 2, swamp 10 556 | //creep off road: road 2, plains 1, swamp 1 | path off road raod 1, plains 1, swamp 10 557 | //creep ignore roads: roads 2, plains 1, swamp muscle | path ignore road 1, plains 1, swamp 5 558 | plainCost: options.offRoad ? 1 : options.ignoreRoads ? 1 : 2, 559 | swampCost: options.offRoad ? 1 : options.muscle ? Math.ceil(20/options.muscle) : options.ignoreRoads ? 5 : 10, 560 | roomCallback: callback, 561 | heuristicWeight: heuristic, 562 | }); 563 | if (ret.incomplete && options.ensurePath) { 564 | if (options.useFindRoute === undefined) { 565 | // handle case where pathfinder failed at a short distance due to not using findRoute 566 | // can happen for situations where the creep would have to take an uncommonly indirect path 567 | // options.allowedRooms and options.routeCallback can also be used to handle this situation 568 | if (roomDistance <= 2) { 569 | console.log(`${Game.shard.name} TRAVELER: path failed without findroute, trying with options.useFindRoute = true`); 570 | console.log(`from: ${origin}, destination: ${destination}`); 571 | options.useFindRoute = true; 572 | ret = this.findTravelPath(origin, destination, options); 573 | console.log(`TRAVELER: second attempt was ${ret.incomplete ? "not " : ""}successful`); 574 | return ret; 575 | } 576 | // TODO: handle case where a wall or some other obstacle is blocking the exit assumed by findRoute 577 | } else {} 578 | } 579 | return ret; 580 | } 581 | //find a viable sequence of rooms that can be used to narrow down pathfinder's search algorithm 582 | static findRoute(origin, destination, options = {}) { 583 | let restrictDistance = options.restrictDistance || Game.map.getRoomLinearDistance(origin, destination) + 10; 584 | let allowedRooms = {[origin]: true, [destination]: true}; 585 | let highwayBias = 1; 586 | if (options.preferHighway) { 587 | highwayBias = 2.5; 588 | if (options.highwayBias) { 589 | highwayBias = options.highwayBias; 590 | } 591 | } 592 | let ret = Game.map.findRoute(origin, destination, { 593 | routeCallback: (roomName) => { 594 | if (options.routeCallback) { 595 | let outcome = options.routeCallback(roomName); 596 | if (outcome !== undefined) { 597 | return outcome; 598 | } 599 | } 600 | let rangeToRoom = Game.map.getRoomLinearDistance(origin, roomName); 601 | if (rangeToRoom > restrictDistance) { 602 | // room is too far out of the way 603 | return Number.POSITIVE_INFINITY; 604 | } 605 | if (!options.allowHostile && Traveler.checkAvoid(roomName) && roomName !== destination && roomName !== origin) { 606 | // room is marked as "avoid" in room memory 607 | return Number.POSITIVE_INFINITY; 608 | } 609 | let parsed; 610 | if (options.preferHighway) { 611 | parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName); 612 | let isHighway = (parsed[1] % 10 === 0) || (parsed[2] % 10 === 0); 613 | if (isHighway) { 614 | return 1; 615 | } 616 | } 617 | // SK rooms are avoided when there is no vision in the room, harvested-from SK rooms are allowed 618 | if (!options.allowSK && !Game.rooms[roomName]) { 619 | if (!parsed) { 620 | parsed = /^[WE]([0-9]+)[NS]([0-9]+)$/.exec(roomName); 621 | } 622 | let fMod = parsed[1] % 10; 623 | let sMod = parsed[2] % 10; 624 | let isSK = !(fMod === 5 && sMod === 5) && ((fMod >= 4) && (fMod <= 6)) && ((sMod >= 4) && (sMod <= 6)); 625 | if (isSK) { 626 | return 10 * highwayBias; 627 | } 628 | } 629 | return highwayBias; 630 | }, 631 | }); 632 | if (!_.isArray(ret)) { 633 | console.log(`couldn't findRoute to ${destination}`); 634 | return; 635 | } 636 | for (let value of ret) { 637 | allowedRooms[value.room] = true; 638 | } 639 | return allowedRooms; 640 | } 641 | //check how many rooms were included in a route returned by findRoute 642 | static routeDistance(origin, destination) { 643 | let linearDistance = Game.map.getRoomLinearDistance(origin, destination); 644 | if (linearDistance >= 32) { 645 | return linearDistance; 646 | } 647 | let allowedRooms = this.findRoute(origin, destination); 648 | if (allowedRooms) { 649 | return Object.keys(allowedRooms).length; 650 | } 651 | } 652 | //build a cost matrix based on structures in the room. Will be cached for more than one tick. Requires vision. 653 | static getStructureMatrix(room, options) { 654 | let roadcost = options && (options.muscle && (options.ignoreRoads || options.offRoad)) ? 2 : 1 655 | if (!this.structureMatrixTick) { 656 | this.structureMatrixTick = {}; 657 | } 658 | 659 | if (!this.structureMatrixCache[room.name]) { 660 | this.structureMatrixCache[room.name] = {} 661 | } 662 | if (!this.structureMatrixCache[room.name][roadcost] || ((options && options.freshMatrix) && Game.time !== this.structureMatrixTick[room.name])) { 663 | this.structureMatrixTick[room.name] = Game.time; 664 | let matrix = new PathFinder.CostMatrix(); 665 | this.structureMatrixCache[room.name][roadcost] = Traveler.addStructuresToMatrix(room, matrix, roadcost); 666 | } 667 | return this.structureMatrixCache[room.name][roadcost]; 668 | } 669 | //build a cost matrix based on creeps and structures in the room. Will be cached for one tick. Requires vision. 670 | static getCreepMatrix(room) { 671 | if (!this.creepMatrixTick) { 672 | this.creepMatrixTick = {}; 673 | } 674 | if (!this.creepMatrixCache[room.name] || Game.time !== this.creepMatrixTick[room.name]) { 675 | this.creepMatrixTick[room.name] = Game.time; 676 | this.creepMatrixCache[room.name] = Traveler.addCreepsToMatrix(room, this.getStructureMatrix(room, {freshMatrix: true}).clone()); 677 | } 678 | return this.creepMatrixCache[room.name]; 679 | } 680 | //add structures to matrix so that impassible structures can be avoided and roads given a lower cost 681 | static addStructuresToMatrix(room, matrix, roadCost) { 682 | let impassibleStructures = []; 683 | for (let structure of room.find(FIND_STRUCTURES)) { 684 | if (structure.structureType === STRUCTURE_RAMPART) { 685 | if (!structure.my && !structure.isPublic) { 686 | impassibleStructures.push(structure); 687 | } 688 | } else if (structure.structureType === STRUCTURE_ROAD) { 689 | if (matrix.get(structure.pos.x, structure.pos.y) < 0xff) { 690 | matrix.set(structure.pos.x, structure.pos.y, roadCost); 691 | } 692 | } else if (structure.structureType === STRUCTURE_CONTAINER) { 693 | continue; 694 | //matrix.set(structure.pos.x, structure.pos.y, 5); //creeps can walk over containers. So this doesn't matter. Saving it just in case it breaks something 695 | } else { 696 | matrix.set(structure.pos.x, structure.pos.y, 0xff); 697 | } 698 | } 699 | for (let site of room.find(FIND_MY_CONSTRUCTION_SITES)) { 700 | if (site.structureType === STRUCTURE_CONTAINER || site.structureType === STRUCTURE_ROAD || site.structureType === STRUCTURE_RAMPART) { 701 | continue; 702 | } 703 | matrix.set(site.pos.x, site.pos.y, 0xff); 704 | } 705 | return matrix; 706 | } 707 | //add creeps to matrix so that they will be avoided by other creeps 708 | static addCreepsToMatrix(room, matrix) { 709 | room.find(FIND_CREEPS).forEach((creep) => matrix.set(creep.pos.x, creep.pos.y, 0xff)); 710 | return matrix; 711 | } 712 | //serialize a path, traveler style. Returns a string of directions. 713 | static serializePath(startPos, path, color = "orange") { 714 | if(Game.map.visual.getSize() >= 1000000) { 715 | return 716 | } 717 | let serializedPath = ""; 718 | let lastPosition = startPos; 719 | this.circle(startPos, color); 720 | for (let position of path) { 721 | if (position.roomName === lastPosition.roomName) { 722 | new RoomVisual(position.roomName).line(position, lastPosition, {color: color, lineStyle: "dashed"}); 723 | serializedPath += lastPosition.getDirectionTo(position); 724 | } 725 | lastPosition = position; 726 | } 727 | return serializedPath; 728 | } 729 | //returns a position at a direction relative to origin 730 | static positionAtDirection(origin, direction) { 731 | let offsetX = [0, 0, 1, 1, 1, 0, -1, -1, -1]; 732 | let offsetY = [0, -1, -1, 0, 1, 1, 1, 0, -1]; 733 | let x = origin.x + offsetX[direction]; 734 | let y = origin.y + offsetY[direction]; 735 | if (x > 49 || x < 0 || y > 49 || y < 0) { 736 | return; 737 | } 738 | return new RoomPosition(x, y, origin.roomName); 739 | } 740 | static deserializeState(travelData, destination) { 741 | let state = {}; 742 | if (travelData.state) { 743 | state.lastCoord = {x: travelData.state[STATE_PREV_X], y: travelData.state[STATE_PREV_Y]}; 744 | state.cpu = travelData.state[STATE_CPU]; 745 | state.stuckCount = travelData.state[STATE_STUCK]; 746 | state.destination = new RoomPosition(travelData.state[STATE_DEST_X], travelData.state[STATE_DEST_Y], travelData.state[STATE_DEST_ROOMNAME]); 747 | } else { 748 | state.cpu = 0; 749 | state.destination = destination; 750 | } 751 | return state; 752 | } 753 | static serializeState(creep, destination, state, travelData) { 754 | travelData.state = [creep.pos.x, creep.pos.y, state.stuckCount, state.cpu, destination.x, destination.y, destination.roomName]; 755 | } 756 | static isStuck(creep, state) { 757 | if (state.lastCoord !== undefined) { 758 | if (this.sameCoord(creep.pos, state.lastCoord)) { 759 | // didn't move 760 | return true; 761 | } else if (this.isExit(creep.pos) && this.isExit(state.lastCoord)) { 762 | // moved against exit 763 | return true; 764 | } 765 | } 766 | return false; 767 | } 768 | 769 | static updatePortals() { 770 | //Set the public data segment to active 771 | RawMemory.setActiveForeignSegment('LeagueOfAutomatedNations', 97); 772 | if (!RawMemory.foreignSegment.data) return false 773 | 774 | const data = JSON.parse(RawMemory.foreignSegment.data); //get the parsed data 775 | if (data.length < 10) { 776 | return; 777 | } 778 | Memory.Traveler.Portals = {} 779 | for (const i in data) { 780 | const room = this.packRoomName(data[i][0]); 781 | if (!Memory.Traveler.Portals[room]) { 782 | Memory.Traveler.Portals[room] = {}; 783 | } 784 | if (data[i][1] === Game.shard.name) { //portal to a room on same shard 785 | if (!Memory.Traveler.Portals[room].rooms) { 786 | Memory.Traveler.Portals[room].rooms = {}; 787 | } 788 | Memory.Traveler.Portals[room].rooms[this.packRoomName(data[i][2])] = ''; 789 | } else { 790 | if (!Memory.Traveler.Portals[room].shards) { 791 | Memory.Traveler.Portals[room].shards = {}; 792 | } 793 | if (!Memory.Traveler.Portals[room].shards[data[i][1]]) { 794 | Memory.Traveler.Portals[room].shards[data[i][1]] = {}; 795 | } 796 | Memory.Traveler.Portals[room].shards[data[i][1]][this.packRoomName(data[i][2])] = ''; 797 | } 798 | } 799 | console.log('Retrieved all portal information for ' + Game.shard.name); 800 | Memory.Traveler.portalUpdate = Game.time; 801 | } 802 | static findPathToNearestPortal(creep, shard, room) { 803 | const count = Game.cpu.getUsed() 804 | let shards = []; 805 | let shardDestIndex; 806 | let shardOrgIndex; 807 | //get shards (not hard coded so it can change later if the game is updated with new shards) 808 | for (let i in Game.cpu.shardLimits) { 809 | if (i === shard) { 810 | shardDestIndex = shards.length; 811 | } 812 | if (i === Game.shard.name) { 813 | shardOrgIndex = shards.length; 814 | } 815 | shards[shards.length] = i; 816 | } 817 | //find the nearest shard incase we don't have a portal to the destinaton shard 818 | const nearestShard = shardDestIndex > shardOrgIndex ? shards[shardOrgIndex+1] : shards[shardOrgIndex-1]; 819 | 820 | //find nearby shard portal rooms. They only appear in highway intersections 821 | let [name,h,x,v,y] = creep.room.name.match(/^([WE])([0-9]+)([NS])([0-9]+)$/); 822 | let x10 = Math.ceil(x/10)*10; 823 | let y10 = Math.ceil(y/10)*10; 824 | let xferRooms = []; 825 | 826 | xferRooms.push(h+x10+v+y10);//top Left of sector 827 | xferRooms.push(h+(x10-10)+v+y10); //top right of sector 828 | xferRooms.push(h+x10+v+(y10-10)); //bottom left of sector 829 | xferRooms.push(h+(x10-10)+v+(y10-10)); //bottom right of sector 830 | //if near the cross roads, get the rooms on the other side with portals 831 | const v1 = v === 'S' ? 'N' : 'S'; //swithing lat and long 832 | const h1 = h === 'W' ? 'E' : 'W'; 833 | //near the 0 axis cross road, get the rooms on the other side with portals 834 | if (x10 === 10) { 835 | xferRooms.push(h1+'0'+v+'0'); 836 | xferRooms.push(h1+'0'+v+'10'); 837 | } 838 | //near the 0 axis cross road, get the rooms on the other side with portals 839 | if (y10 === 10) { 840 | xferRooms.push(h+'0'+v1+'0'); 841 | xferRooms.push(h+'10'+v1+'0'); 842 | } 843 | //near the 0,0 axis cross road, get the roomscaddy corner 844 | if (x10 === 10 && y10 === 10) { 845 | xferRooms.push(h1+'0'+v1+'0'); 846 | } 847 | //look through all these portals for the best routing 848 | let dist = 999999; 849 | let xferroom; 850 | let nextRoom; 851 | let nextShard = nearestShard; 852 | const shardPortals = Memory.Traveler.Portals; 853 | 854 | for (let xroom of xferRooms) { 855 | let proom = this.packRoomName(xroom) 856 | if (!shardPortals[proom] || !shardPortals[proom].shards) { 857 | continue; //no shards in this rooms memory 858 | } 859 | for (const destRoom in shardPortals[proom].shards[shard]) { 860 | let pdestRoom = this.unpackRoomName(destRoom) 861 | //get the linear distance of travel from this room, to the transfer room, to the destination room, to the actual room number 862 | const newdist = Game.map.getRoomLinearDistance(creep.room.name, xroom) + Game.map.getRoomLinearDistance(pdestRoom, room); 863 | 864 | //if better set our new room 865 | if (newdist < dist) { 866 | dist = newdist; 867 | xferroom = xroom; 868 | nextRoom = pdestRoom; 869 | nextShard = shard; 870 | } 871 | } 872 | if (shard === nearestShard) continue; //same shard, skip 873 | //and check ones for the next shard on the 'z axis' of the game 874 | for (const destRoom in shardPortals[xroom].shards[nearestShard]) { 875 | let pdestRoom = this.unpackRoomName(destRoom) 876 | //get the linear distance of travel from this room, to the transfer room, to the destination room, to the actual room number 877 | //as of Dec 2020, shard 1 is the best place to make massive jumps due to the portals on shard0. We will attempt to get to that shard 878 | //and then find the best portal to make the shortest path. Until then, we are just going to push to the nearest portal. 879 | const newdist = ((Game.shard.name === 'shard3' || Game.shard.name === 'shard2') && shard === 'shard0') ? Game.map.getRoomLinearDistance(creep.room.name, xroom) 880 | : Game.map.getRoomLinearDistance(creep.room.name, xroom, pdestRoom, room); 881 | //if better set our new room 882 | if (newdist < dist) { 883 | dist = newdist; 884 | xferroom = xroom; 885 | nextRoom = pdestRoom; 886 | nextShard = nearestShard; 887 | } 888 | } 889 | } 890 | 891 | if (!xferroom) return false 892 | console.log('TRAVELER: ' + creep.name + ' found best move to ' + shard + ' destination of ' + room + ' through ' + nextShard + ' - ' + nextRoom + ' cpu ' + (Game.cpu.getUsed()-count)); 893 | creep.memory._trav.ISM = {currentShard: Game.shard.name, shard: shard, room: room, destShard: nextShard, xferRoom: xferroom, destRoom: nextRoom}; 894 | return true 895 | } 896 | static checkShardTransferData(creep, shard, room) { 897 | if (!creep.memory._trav) { 898 | creep.memory._trav = {}; 899 | } 900 | if (creep.memory._trav.ISM 901 | && creep.memory._trav.ISM.currentShard === Game.shard.name //this is in case the user pulls all their memory over to include movement 902 | && creep.memory._trav.ISM.shard === shard 903 | && creep.memory._trav.ISM.room === room) { 904 | return true; //yay! 905 | } 906 | //needs new path 907 | if (!this.findPathToNearestPortal(creep, shard, room)) { 908 | return ERR_NO_PATH; //well, damn 909 | } 910 | return true; 911 | } 912 | static moveToShard(creep, shard, room, priority) { 913 | if (!creep) { 914 | return; //dafuq? 915 | } 916 | if (!Memory.Traveler.Portals || !Memory.Traveler.portalUpdate || Memory.Traveler.portalUpdate <= Game.time-10000) { 917 | this.updatePortals(); 918 | } 919 | const check = this.checkShardTransferData(creep, shard, room); 920 | if (check !== true) { 921 | return ERR_NO_PATH; 922 | } 923 | 924 | const xferData = creep.memory._trav.ISM ; 925 | 926 | if (xferData.xferRoom === creep.room.name) { 927 | let portal 928 | //move to nearest portal 929 | if (!xferData.portalId) { 930 | portal = creep.pos.findClosestByRange(FIND_STRUCTURES, {filter: s => s.structureType === STRUCTURE_PORTAL 931 | && s.destination.shard === xferData.destShard 932 | && s.destination.room === xferData.destRoom}); 933 | } else { 934 | portal = Game.getObjectById(xferData.portalId); 935 | } 936 | 937 | if (!portal) { 938 | delete creep.memory._trav.ISM; 939 | return false; 940 | } 941 | creep.memory._trav.ISM.portalId = portal.id; 942 | this.registerTarget(creep, portal, 0, priority); 943 | this.travelTo(creep, portal); 944 | } else { 945 | let dest = new RoomPosition(25,25, xferData.xferRoom); 946 | this.registerTarget(creep, dest, 0, priority); 947 | this.travelTo(creep, dest, {preferHighway: true, ensurePath: true, useFindRoute: true}) 948 | } 949 | return true 950 | } 951 | static addPath(from, to, path, weight) { 952 | if (!Memory.Traveler.pCache) { 953 | Memory.Traveler.pCache = {}; 954 | } 955 | let cache = Memory.Traveler.pCache; 956 | let key = this.getPathKey(from, to) 957 | let cachedPath = cache[key]; 958 | 959 | const cost = weight >= 10 ? 2 : weight >= 2 ? 1 : 0; 960 | if (cachedPath) { 961 | cachedPath[cost] = this.packPath(path) 962 | cachedPath.uses += 1 963 | } else { 964 | Memory.Traveler.pCache[key] = { 965 | [cost]: this.packPath(path), 966 | uses: 1 967 | } 968 | } 969 | } 970 | static getPath(from, to, weight) { 971 | const cost = weight >= 10 ? 2 : weight >= 2 ? 1 : 0; 972 | let cache = Memory.Traveler.pCache; 973 | if (!cache) { 974 | return; 975 | } 976 | 977 | let key = this.getPathKey(from, to); 978 | let cachedPath = cache[key]; 979 | if(cachedPath) { 980 | cachedPath.uses += 1; 981 | //clear and re get every 100 uses. 982 | if (cachedPath.uses % 100 === 0) { 983 | delete cachedPath[0] 984 | delete cachedPath[1] 985 | delete cachedPath[2] 986 | return; 987 | } 988 | let path = this.unpackPath(cachedPath[cost]); 989 | if (!path) return 990 | if (!this.validatePath(from, path)) { 991 | delete cache[key] 992 | return 993 | } 994 | return path; 995 | } 996 | } 997 | //checks a path to make sure it is still valid via cost matrix. 998 | static validatePath(origin, path) { 999 | let offsetX = [0, 0, 1, 1, 1, 0, -1, -1, -1]; 1000 | let offsetY = [0, -1, -1, 0, 1, 1, 1, 0, -1]; 1001 | let roomName = origin.roomName; 1002 | let room = Game.rooms[roomName]; 1003 | let exits = Game.map.describeExits(roomName); 1004 | let x = origin.x; 1005 | let y = origin.y; 1006 | let matrix = this.getStructureMatrix(room); 1007 | 1008 | for (let i = 0; i < path.length; i ++) { 1009 | if (path[i] < 1 || path[i] > 8) return false 1010 | x += offsetX[path[i]]; 1011 | y += offsetY[path[i]]; 1012 | //if we are moving rooms 1013 | if(x < 0) { //left 1014 | x = 49; 1015 | roomName = exits[7]; 1016 | room = Game.rooms[roomName]; 1017 | if(!room) return true; 1018 | exits = Game.map.describeExits(roomName); 1019 | matrix = this.getStructureMatrix(room); 1020 | } 1021 | if (x > 49){ // right 1022 | x = 0; 1023 | roomName = exits[3]; 1024 | room = Game.rooms[roomName]; 1025 | if(!room) return true; 1026 | exits = Game.map.describeExits(roomName); 1027 | matrix = this.getStructureMatrix(room); 1028 | } 1029 | if(y < 0) { //up 1030 | y = 49; 1031 | roomName = exits[1]; 1032 | room = Game.rooms[roomName]; 1033 | if(!room) return true; 1034 | exits = Game.map.describeExits(roomName); 1035 | matrix = this.getStructureMatrix(room); 1036 | } 1037 | if (y > 49){ //down 1038 | y = 0; 1039 | roomName = exits[5]; 1040 | room = Game.rooms[roomName]; 1041 | if(!room) return true; 1042 | exits = Game.map.describeExits(roomName); 1043 | matrix = this.getStructureMatrix(room); 1044 | } 1045 | if(matrix.get(x,y) >= 128) { 1046 | return false; 1047 | } 1048 | } 1049 | return true; 1050 | } 1051 | //TODO: Disable logging 1052 | static cleanCacheByUsage(usage) { 1053 | if(!Memory.Traveler.pCache || _.size(Memory.Traveler.pCache) <= MAX_CACHED_PATH_MEM_USAGE) { 1054 | return; //not above the limit 1055 | } 1056 | let counter = 9999999; 1057 | for (const key in Memory.Traveler.pCache) { 1058 | if(Memory.Traveler.pCache[key].uses <= usage) { 1059 | delete Memory.Traveler.pCache[key]; 1060 | } else if (Memory.Traveler.pCache[key].uses < counter){ 1061 | counter = Memory.Traveler.pCache[key].uses; 1062 | } 1063 | } 1064 | this.cleanCacheByUsage(counter); 1065 | } 1066 | static getPathKey(from, to) { 1067 | return this.getPosKey(from) + this.getPosKey(to); 1068 | } 1069 | static getPosKey(pos) { 1070 | return this.packCoord(pos) + this.packRoomName(pos.roomName) 1071 | } 1072 | //packrat functions, stolen from Muon (Overmind). Thanks! 1073 | static packCoord(coord) { return String.fromCharCode(((coord.x << 6) | coord.y) + 65);} 1074 | static packRoomName(roomName) { 1075 | if (PERMACACHE._packedRoomNames[roomName] === undefined) { 1076 | const coordinateRegex = /(E|W)(\d+)(N|S)(\d+)/g; 1077 | const match = coordinateRegex.exec(roomName); 1078 | const xDir = match[1]; 1079 | const x = Number(match[2]); 1080 | const yDir = match[3]; 1081 | const y = Number(match[4]); 1082 | let quadrant = xDir == 'W' ? yDir == 'N' ? 0 : 1 : yDir == 'N' ? 2 : 3 1083 | // y is 6 bits, x is 6 bits, quadrant is 2 bits 1084 | const num = (quadrant << 12 | (x << 6) | y) + 65; 1085 | const char = String.fromCharCode(num); 1086 | PERMACACHE._packedRoomNames[roomName] = char; 1087 | PERMACACHE._unpackedRoomNames[char] = roomName; 1088 | } 1089 | return PERMACACHE._packedRoomNames[roomName]; 1090 | } 1091 | static unpackRoomName(char) { 1092 | if (PERMACACHE._unpackedRoomNames[char] === undefined) { 1093 | const num = char.charCodeAt(0) - 65; 1094 | const { q, x, y } = { 1095 | q: (num & 0b11000000111111) >>> 12, 1096 | x: (num & 0b00111111000000) >>> 6, 1097 | y: (num & 0b00000000111111), 1098 | }; 1099 | let roomName; 1100 | switch (q) { 1101 | case 0: 1102 | roomName = 'W' + x + 'N' + y; 1103 | break; 1104 | case 1: 1105 | roomName = 'W' + x + 'S' + y; 1106 | break; 1107 | case 2: 1108 | roomName = 'E' + x + 'N' + y; 1109 | break; 1110 | case 3: 1111 | roomName = 'E' + x + 'S' + y; 1112 | break; 1113 | default: 1114 | roomName = 'ERROR'; 1115 | } 1116 | PERMACACHE._packedRoomNames[roomName] = char; 1117 | PERMACACHE._unpackedRoomNames[char] = roomName; 1118 | } 1119 | return PERMACACHE._unpackedRoomNames[char]; 1120 | } 1121 | static packPath(path) { 1122 | let hash = '' 1123 | for (let i = 0; i < path.length; i += 4) { 1124 | hash += String.fromCharCode(path.substr(i, 4)) 1125 | } 1126 | return hash 1127 | } 1128 | static unpackPath(hash) { 1129 | if (!hash || hash.length === 0) return 1130 | let path = '' 1131 | for (let i = 0; i < hash.length; i++) { 1132 | path += Number(hash.charCodeAt(i)) 1133 | } 1134 | return path 1135 | } 1136 | } 1137 | Traveler.structureMatrixCache = {}; 1138 | Traveler.creepMatrixCache = {}; 1139 | global.PERMACACHE = {}; // Create a permanent cache for immutable items such as room names..compatible with code bases running packrat 1140 | PERMACACHE._packedRoomNames = PERMACACHE._packedRoomNames || {}; 1141 | PERMACACHE._unpackedRoomNames = PERMACACHE._unpackedRoomNames || {}; 1142 | exports.Traveler = Traveler; 1143 | // this might be higher than you wish, setting it lower is a great way to diagnose creep behavior issues. When creeps 1144 | // need to repath to often or they aren't finding valid paths, it can sometimes point to problems elsewhere in your code 1145 | const MAX_CACHED_PATH_MEM_USAGE = 2000 // approx 100kb 1146 | const MIN_CACHED_PATH_LENGTH = 999 // minimum path length to cache. Set to a very high value to stop caching. 1147 | const REPORT_CPU_THRESHOLD = 1000; 1148 | const DEFAULT_MAXOPS = 20000; 1149 | const DEFAULT_STUCK_VALUE = 2; 1150 | const STATE_PREV_X = 0; 1151 | const STATE_PREV_Y = 1; 1152 | const STATE_STUCK = 2; 1153 | const STATE_CPU = 3; 1154 | const STATE_DEST_X = 4; 1155 | const STATE_DEST_Y = 5; 1156 | const STATE_DEST_ROOMNAME = 6; 1157 | // assigns a function to Creep.prototype: creep.travelTo(destination) 1158 | Creep.prototype.travelTo = (function(destination, options) { 1159 | return Traveler.travelTo(this, destination, options); 1160 | }); 1161 | 1162 | PowerCreep.prototype.travelTo = Creep.prototype.travelTo; 1163 | // call this in every room to update it's status 1164 | Room.prototype.UpdateRoomStatus = (function() { 1165 | Traveler.updateRoomStatus(this); 1166 | }); 1167 | // Get a path to a destiniation... Good for building roads. 1168 | RoomPosition.prototype.FindPathTo = (function(destination, options) { 1169 | let ret = Traveler.findTravelPath(this, destination, options); 1170 | return ret.path; 1171 | }); 1172 | // Get the route distance to a room instead of linear distance 1173 | Room.prototype.GetDistanceToRoom = (function(destination) { 1174 | return Traveler.routeDistance(this.name, destination); 1175 | }); 1176 | // Moves to a target 1177 | // Add you own code here to interface with traveler 1178 | Creep.prototype.Move = (function(target, range, priority, opts = {}) { 1179 | if (!target) { 1180 | return ERR_INVALID_ARGS; 1181 | } 1182 | if (this.body && this.getActiveBodyparts(MOVE) === 0) { 1183 | return ERR_NO_BODYPART; 1184 | } 1185 | if (range === undefined) { 1186 | range = 1; 1187 | } 1188 | if (priority === undefined) { 1189 | priority = 1; 1190 | } 1191 | opts.range = range; 1192 | opts.priority = priority; 1193 | Traveler.registerTarget(this, target, opts.range, opts.priority); 1194 | 1195 | if (target.pos && target.pos.roomName !== this.room.name) { 1196 | opts.preferHighway = true; 1197 | opts.ensurePath = true; 1198 | opts.useFindRoute = true; 1199 | return Traveler.travelTo(this, target, opts); 1200 | } 1201 | return Traveler.travelTo(this, target, opts); 1202 | }); 1203 | PowerCreep.prototype.Move = Creep.prototype.Move; 1204 | 1205 | Creep.prototype.MoveToShard = function(shard, room, priority) { 1206 | if (!shard || !room) { 1207 | return ERR_INVALID_ARGS; 1208 | } 1209 | if (Game.shard.name !== shard) { 1210 | return Traveler.moveToShard(this, shard, room, priority); 1211 | } 1212 | return OK; 1213 | } 1214 | PowerCreep.prototype.MoveToShard = Creep.prototype.MoveToShard; 1215 | 1216 | // Move a creep off road... Good for building, repairing, idling. 1217 | Creep.prototype.MoveOffRoad = (function(target, dist, priority) { 1218 | if (!target) { 1219 | return ERR_INVALID_ARGS; 1220 | } 1221 | if (priority === undefined) { 1222 | priority = 1; 1223 | } 1224 | if (dist === undefined) { 1225 | dist = 3; 1226 | } 1227 | if (target.pos) { 1228 | target = target.pos; 1229 | } 1230 | if (this.pos.getRangeTo(target) > dist) { 1231 | return this.Move(target, dist, priority); 1232 | } 1233 | Traveler.registerTarget(this, target, dist, priority); 1234 | return Traveler.moveOffRoad(this, target, dist, priority); 1235 | }); 1236 | PowerCreep.prototype.MoveOffRoad = Creep.prototype.MoveOffRoad; --------------------------------------------------------------------------------