All files / my-screeps-repo/src/utils pathfinder.js

18.26% Statements 19/104
10.95% Branches 8/73
20% Functions 3/15
18.75% Lines 18/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360                      4x           4x 4x                                                                                                                                                                                                                                               2x                   2x       2x                                                                                                                                                                                                               2x 1x 1x 1x 2x 2x 1x 1x     1x                   1x 1x                                                                                                                                           4x                        
/**
 * src/utils/pathfinder.js
 * Screeps 経路探索ユーティリティ
 *
 * PathFinder API をラップし、道路優先・スワンプ回避・障害物回避などの
 * カスタムコストマトリクスを提供する。
 * パス結果はキャッシュに格納してCPU使用量を削減する。
 */
 
'use strict';
 
const { PATHFINDER_DEFAULTS, CACHE_TTL } = require('../constants');
 
// ============================================================
// グローバルキャッシュキー
// ============================================================
 
const PATH_CACHE_PREFIX = 'path_';
const COST_MATRIX_CACHE_PREFIX = 'cm_';
 
/**
 * global.cache を初期化する(未定義の場合)
 */
function ensureCache() {
    if (!global.cache) global.cache = {};
    return global.cache;
}
 
// ============================================================
// コストマトリクス構築
// ============================================================
 
/**
 * ルーム用のカスタムコストマトリクスを構築する
 * - 道路: コスト1(優先)
 * - コンテナ/リンク: 通行可能(コスト変更なし)
 * - ウォール: 通行不可
 * - 他のクリープ: 通行コスト増加
 *
 * @param {string} roomName
 * @param {Object} [options]
 * @param {boolean} [options.avoidCreeps=false] - クリープを障害物として扱うか
 * @param {boolean} [options.useCache=true] - キャッシュを使用するか
 * @returns {PathFinder.CostMatrix}
 */
function buildCostMatrix(roomName, options) {
    const opts = Object.assign({ avoidCreeps: false, useCache: true }, options);
    const cache = ensureCache();
 
    const cacheKey = `${COST_MATRIX_CACHE_PREFIX}${roomName}_${opts.avoidCreeps ? 1 : 0}`;
 
    if (opts.useCache) {
        const entry = cache[cacheKey];
        if (entry && entry.expires > Game.time) {
            return entry.data;
        }
    }
 
    const room = Game.rooms[roomName];
    const costs = new PathFinder.CostMatrix();
 
    if (!room) {
        return costs;
    }
 
    // 構造物のコストを設定
    const structures = room.find(FIND_STRUCTURES);
    for (const struct of structures) {
        switch (struct.structureType) {
            case STRUCTURE_ROAD:
                // 道路は平地コスト(2)より低いコスト(1)に設定
                costs.set(struct.pos.x, struct.pos.y, PATHFINDER_DEFAULTS.ROAD_COST);
                break;
            case STRUCTURE_WALL:
                // ウォールは通行不可
                costs.set(struct.pos.x, struct.pos.y, 255);
                break;
            case STRUCTURE_RAMPART:
                // 自分のランパートは通行可能、敵のランパートは通行不可
                if (!struct.my && !struct.isPublic) {
                    costs.set(struct.pos.x, struct.pos.y, 255);
                }
                break;
            default:
                // 敵や中立の構造物は通行不可
                if (struct.structureType !== STRUCTURE_CONTAINER &&
                    struct.structureType !== STRUCTURE_LINK) {
                    if (!struct.my) {
                        costs.set(struct.pos.x, struct.pos.y, 255);
                    }
                }
        }
    }
 
    // 建設中の構造物もコストに含める
    const sites = room.find(FIND_MY_CONSTRUCTION_SITES);
    for (const site of sites) {
        if (site.structureType !== STRUCTURE_ROAD &&
            site.structureType !== STRUCTURE_RAMPART &&
            site.structureType !== STRUCTURE_CONTAINER) {
            costs.set(site.pos.x, site.pos.y, 3);
        }
    }
 
    // クリープを障害物として設定(オプション)
    if (opts.avoidCreeps) {
        const creeps = room.find(FIND_CREEPS);
        for (const creep of creeps) {
            costs.set(creep.pos.x, creep.pos.y, 255);
        }
    }
 
    if (opts.useCache) {
        cache[cacheKey] = {
            data: costs,
            expires: Game.time + CACHE_TTL.PATH,
        };
    }
 
    return costs;
}
 
// ============================================================
// パス計算
// ============================================================
 
/**
 * PathFinder を使って creep からターゲットへの経路を計算する
 * @param {RoomPosition} origin - 出発地点
 * @param {RoomPosition|{ pos: RoomPosition, range: number }} goal - 目標地点
 * @param {Object} [options]
 * @param {boolean} [options.avoidCreeps=false]
 * @param {number} [options.maxRooms=1]
 * @param {number} [options.plainCost=2]
 * @param {number} [options.swampCost=10]
 * @returns {PathFinder.Path}
 */
function findPath(origin, goal, options) {
    const opts = Object.assign(
        {
            avoidCreeps: false,
            maxRooms: PATHFINDER_DEFAULTS.MAX_ROOMS,
            plainCost: PATHFINDER_DEFAULTS.PLAIN_COST,
            swampCost: PATHFINDER_DEFAULTS.SWAMP_COST,
        },
        options
    );
 
    const pfGoal = goal.pos
        ? { pos: goal.pos, range: goal.range || 1 }
        : { pos: goal, range: 1 };
 
    return PathFinder.search(origin, pfGoal, {
        plainCost: opts.plainCost,
        swampCost: opts.swampCost,
        maxRooms: opts.maxRooms,
        roomCallback: (roomName) => buildCostMatrix(roomName, { avoidCreeps: opts.avoidCreeps }),
    });
}
 
// ============================================================
// クリープ移動ラッパー
// ============================================================
 
/**
 * クリープをターゲットへ移動させる
 * メモリにパスをキャッシュし、REUSE_PATH ティック間は再計算しない
 *
 * @param {Creep} creep
 * @param {RoomPosition|RoomObject} target
 * @param {Object} [options]
 * @param {number} [options.range=1] - ターゲットへの接近距離
 * @param {boolean} [options.avoidCreeps=false]
 * @param {boolean} [options.visualizePath=true]
 * @returns {number} 移動結果コード(OK, ERR_TIRED, ERR_NO_PATH など)
 */
function moveTo(creep, target, options) {
    const opts = Object.assign(
        {
            range: 1,
            avoidCreeps: false,
            visualizePath: true,
            reusePath: PATHFINDER_DEFAULTS.REUSE_PATH,
        },
        options
    );
 
    const moveOptions = {
        reusePath: opts.reusePath,
        maxRooms: opts.avoidCreeps ? 1 : PATHFINDER_DEFAULTS.MAX_ROOMS,
        costCallback: (roomName, costMatrix) => {
            return buildCostMatrix(roomName, {
                avoidCreeps: opts.avoidCreeps,
                useCache: true,
            });
        },
    };
 
    if (opts.visualizePath) {
        moveOptions.visualizePathStyle = {
            fill: 'transparent',
            stroke: '#00bfff',
            lineStyle: 'dashed',
            strokeWidth: 0.15,
            opacity: 0.3,
        };
    }
 
    return creep.moveTo(target, moveOptions);
}
 
// ============================================================
// 距離・位置ユーティリティ
// ============================================================
 
/**
 * 2つの位置間のチェビシェフ距離(範囲内判定用)を返す
 * @param {RoomPosition} a
 * @param {RoomPosition} b
 * @returns {number}
 */
function chebyshev(a, b) {
    return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y));
}
 
/**
 * 2つの位置間のマンハッタン距離を返す
 * @param {RoomPosition} a
 * @param {RoomPosition} b
 * @returns {number}
 */
function manhattan(a, b) {
    return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
}
 
/**
 * 対象オブジェクト一覧を距離でソートして返す
 * @param {RoomPosition} origin
 * @param {RoomObject[]} objects
 * @returns {RoomObject[]}
 */
function sortByDistance(origin, objects) {
    return objects.slice().sort((a, b) => {
        const da = origin.getRangeTo(a);
        const db = origin.getRangeTo(b);
        return da - db;
    });
}
 
/**
 * 最も近い対象オブジェクトを返す
 * @param {RoomPosition} origin
 * @param {RoomObject[]} objects
 * @returns {RoomObject|null}
 */
function closest(origin, objects) {
    if (!objects || objects.length === 0) return null;
    let best = null;
    let bestDist = Infinity;
    for (const obj of objects) {
        const d = origin.getRangeTo(obj);
        if (d < bestDist) {
            bestDist = d;
            best = obj;
        }
    }
    return best;
}
 
/**
 * 出発地から最も近い空きタイルを見つける
 * @param {RoomPosition} pos
 * @param {number} [range=3]
 * @returns {RoomPosition|null}
 */
function findNearestOpenTile(pos, range) {
    const r = range || 3;
    const room = Game.rooms[pos.roomName];
    if (!room) return null;
 
    for (let dx = -r; dx <= r; dx++) {
        for (let dy = -r; dy <= r; dy++) {
            const x = pos.x + dx;
            const y = pos.y + dy;
            if (x < 1 || x > 48 || y < 1 || y > 48) continue;
 
            const terrain = room.getTerrain().get(x, y);
            if (terrain === TERRAIN_MASK_WALL) continue;
 
            const atPos = room.lookAt(x, y);
            let blocked = false;
            for (const item of atPos) {
                if (item.type === 'structure' || item.type === 'creep') {
                    blocked = true;
                    break;
                }
            }
            if (!blocked) {
                return new RoomPosition(x, y, pos.roomName);
            }
        }
    }
    return null;
}
 
/**
 * ルーム内の道路上のタイル一覧を返す
 * @param {Room} room
 * @returns {RoomPosition[]}
 */
function getRoadPositions(room) {
    const roads = room.find(FIND_STRUCTURES, {
        filter: { structureType: STRUCTURE_ROAD },
    });
    return roads.map((r) => r.pos);
}
 
// ============================================================
// 経路コスト評価
// ============================================================
 
/**
 * 2地点間の実際の歩数(道路考慮)を推定する
 * PathFinder を使って計算するため、CPU コストに注意
 * @param {RoomPosition} origin
 * @param {RoomPosition} goal
 * @returns {number} ステップ数、到達不可の場合は Infinity
 */
function estimateDistance(origin, goal) {
    const cache = ensureCache();
    const key = `${PATH_CACHE_PREFIX}${origin.roomName}_${origin.x}_${origin.y}_${goal.roomName}_${goal.x}_${goal.y}`;
    const entry = cache[key];
    if (entry && entry.expires > Game.time) {
        return entry.data;
    }
 
    const result = findPath(origin, goal);
    const dist = result.incomplete ? Infinity : result.path.length;
 
    cache[key] = {
        data: dist,
        expires: Game.time + CACHE_TTL.PATH,
    };
 
    return dist;
}
 
module.exports = {
    buildCostMatrix,
    findPath,
    moveTo,
    chebyshev,
    manhattan,
    sortByDistance,
    closest,
    findNearestOpenTile,
    getRoadPositions,
    estimateDistance,
};