All files defense.manager.js

51.87% Statements 69/133
41.17% Branches 35/85
55% Functions 11/20
53.17% Lines 67/126

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      2x                     1x 1x 1x   1x 1x   1x 1x                                                                                                                         2x       2x   2x 1x     1x       1x 1x 1x 1x 3x   1x     1x     1x   1x 1x     1x         1x     1x       1x 1x     1x   1x     1x       1x 1x 1x     1x 1x         1x         3x 3x   3x     3x                                         3x     3x   2x   1x     2x 2x       2x 2x     2x           1x       1x 1x   1x   1x             1x         1x                                                   1x       1x 1x   1x       1x 1x   1x   1x 1x       2x  
// 🛡️ Advanced Defense Manager
// 自動防衛システム - タワー制御と緊急防衛creep生成
 
const defenseManager = {
    // メイン防衛ループ
    run: function (room) {
        this.manageTowers(room);
        this.checkThreats(room);
        this.manageDefenders(room);
    },
 
    // タワー自動制御
    manageTowers: function (room) {
        // ⚡ PERFORMANCE: Reuse cached room structures and creeps if available (populated by dashboard)
        Eif (room._myStructuresTick !== Game.time) {
            room._myStructures = room.find(FIND_MY_STRUCTURES);
            room._myStructuresTick = Game.time;
        }
        const myStructures = room._myStructures;
        const towers = myStructures.filter((s) => s.structureType === STRUCTURE_TOWER);
 
        Eif (towers.length === 0) {
            return;
        }
 
        // 脅威の優先順位付け
        if (room._hostileCreepsTick !== Game.time) {
            room._hostileCreeps = room.find(FIND_HOSTILE_CREEPS);
            room._hostileCreepsTick = Game.time;
        }
        const hostiles = room._hostileCreeps;
 
        if (room._myCreepsTick !== Game.time) {
            room._myCreeps = room.find(FIND_MY_CREEPS);
            room._myCreepsTick = Game.time;
        }
        const myCreeps = room._myCreeps;
 
        const damagedCreeps = myCreeps.filter((c) => c.hits < c.hitsMax);
 
        // ⚡ PERFORMANCE: Shared per-tick caching for damaged structures
        if (room._damagedStructuresTick !== Game.time) {
            room._damagedStructures = room.find(FIND_STRUCTURES, {
                filter: (s) => s.hits < s.hitsMax && s.structureType !== STRUCTURE_WALL,
            });
            room._damagedStructuresTick = Game.time;
        }
        const damagedStructures = room._damagedStructures;
 
        towers.forEach((tower) => {
            // 優先度1: 敵creepへの攻撃
            if (hostiles.length > 0) {
                const target = tower.pos.findClosestByRange(hostiles);
                if (target) {
                    tower.attack(target);
                    return;
                }
            }
 
            // 優先度2: 味方creepの回復
            if (damagedCreeps.length > 0) {
                const critical = damagedCreeps.find((c) => c.hits < c.hitsMax * 0.5);
                if (critical) {
                    tower.heal(critical);
                    return;
                }
            }
 
            // 優先度3: 構造物の修理(エネルギーが十分な時のみ)
            if (tower.store[RESOURCE_ENERGY] > 500) {
                const criticalStructure = damagedStructures.find(
                    (s) => s.hits < s.hitsMax * 0.3 && s.structureType !== STRUCTURE_RAMPART
                );
                if (criticalStructure) {
                    tower.repair(criticalStructure);
                }
            }
        });
    },
 
    // 脅威レベル評価
    checkThreats: function (room) {
        // ⚡ PERFORMANCE: Reuse cached hostile creeps
        Iif (room._hostileCreepsTick !== Game.time) {
            room._hostileCreeps = room.find(FIND_HOSTILE_CREEPS);
            room._hostileCreepsTick = Game.time;
        }
        const hostiles = room._hostileCreeps;
 
        if (hostiles.length === 0) {
            Iif (Memory.defenseLevel) {
                delete Memory.defenseLevel;
            }
            return 0;
        }
 
        // 脅威レベル計算
        let threatLevel = 0;
        hostiles.forEach((hostile) => {
            const parts = hostile.body;
            const attackParts = parts.filter(
                (p) => p.type === ATTACK || p.type === RANGED_ATTACK || p.type === HEAL
            ).length;
            threatLevel += attackParts;
        });
 
        Memory.defenseLevel = threatLevel;
 
        // 警告表示
        Iif (threatLevel > 5) {
            console.log(`🚨 HIGH THREAT in ${room.name}: Level ${threatLevel}`);
        } else Eif (threatLevel > 0) {
            console.log(`⚠️ Threat detected in ${room.name}: Level ${threatLevel}`);
        }
 
        return threatLevel;
    },
 
    // 防衛creep管理
    manageDefenders: function (room) {
        const threatLevel = Memory.defenseLevel || 0;
 
        // ⚡ PERFORMANCE: Use cached room creeps to find defenders instead of global filter
        Iif (room._myCreepsTick !== Game.time) {
            room._myCreeps = room.find(FIND_MY_CREEPS);
            room._myCreepsTick = Game.time;
        }
        const myCreeps = room._myCreeps;
        const defenders = myCreeps.filter((c) => c.memory.role === 'defender');
 
        // 脅威に応じて必要な防衛creep数を決定
        const requiredDefenders = Math.min(Math.ceil(threatLevel / 3), 4);
 
        Eif (defenders.length < requiredDefenders && threatLevel > 0) {
            // スポーン準備
            // ⚡ PERFORMANCE: Use cached room structures to find spawns
            Iif (room._myStructuresTick !== Game.time) {
                room._myStructures = room.find(FIND_MY_STRUCTURES);
                room._myStructuresTick = Game.time;
            }
            const myStructures = room._myStructures;
            const spawns = myStructures.filter(
                (s) => s.structureType === STRUCTURE_SPAWN && !s.spawning
            );
 
            Eif (spawns.length > 0) {
                this.spawnDefender(spawns[0], threatLevel);
            }
        }
 
        // 既存のdefenderに指示
        defenders.forEach((defender) => this.runDefender(defender));
    },
 
    // Defender creepの生成
    spawnDefender: function (spawn, threatLevel) {
        const room = spawn.room;
        const energy = room.energyAvailable;
 
        let body = [];
 
        // エネルギーと脅威レベルに応じたbody構成
        Iif (energy >= 1300 && threatLevel > 10) {
            // 強力な脅威用
            body = [
                TOUGH,
                TOUGH,
                MOVE,
                MOVE,
                MOVE,
                MOVE,
                MOVE,
                MOVE,
                ATTACK,
                ATTACK,
                ATTACK,
                ATTACK,
                ATTACK,
                ATTACK,
                RANGED_ATTACK,
                RANGED_ATTACK,
                HEAL,
            ];
        } else Iif (energy >= 800) {
            // 中程度の脅威用
            body = [TOUGH, MOVE, MOVE, MOVE, MOVE, ATTACK, ATTACK, ATTACK, RANGED_ATTACK, HEAL];
        } else if (energy >= 400) {
            // 最小構成
            body = [MOVE, MOVE, ATTACK, ATTACK, RANGED_ATTACK];
        } else {
            return ERR_NOT_ENOUGH_ENERGY;
        }
 
        const name = `Defender_${Game.time}`;
        const result = spawn.spawnCreep(body, name, {
            memory: { role: 'defender', mode: 'patrol' },
        });
 
        Eif (result === OK) {
            console.log(`🛡️ Spawning defender: ${name}`);
        }
 
        return result;
    },
 
    // Defender creepの行動制御
    runDefender: function (creep) {
        // ⚡ PERFORMANCE: Use cached hostile creeps
        Iif (creep.room._hostileCreepsTick !== Game.time) {
            creep.room._hostileCreeps = creep.room.find(FIND_HOSTILE_CREEPS);
            creep.room._hostileCreepsTick = Game.time;
        }
        const hostiles = creep.room._hostileCreeps;
        const hostile = creep.pos.findClosestByRange(hostiles);
 
        if (hostile) {
            // 敵を発見
            Iif (creep.pos.getRangeTo(hostile) > 1) {
                creep.moveTo(hostile, {
                    visualizePathStyle: { stroke: '#ff0000' },
                });
            }
 
            // 攻撃
            Iif (creep.attack(hostile) === ERR_NOT_IN_RANGE) {
                creep.rangedAttack(hostile);
            }
 
            // 自己回復
            Iif (creep.hits < creep.hitsMax * 0.6) {
                creep.heal(creep);
            }
        } else E{
            // パトロールモード
            if (!creep.memory.patrolTarget) {
                const flag = Game.flags['Patrol'];
                if (flag) {
                    creep.memory.patrolTarget = flag.pos;
                } else {
                    // 部屋の中央をパトロール
                    creep.memory.patrolTarget = new RoomPosition(25, 25, creep.room.name);
                }
            }
 
            if (creep.pos.getRangeTo(creep.memory.patrolTarget) > 3) {
                creep.moveTo(creep.memory.patrolTarget, {
                    visualizePathStyle: { stroke: '#00ff00' },
                });
            }
        }
    },
 
    // 統計情報表示
    showStats: function (room) {
        // ⚡ PERFORMANCE: Use cached room objects
        Iif (room._myStructuresTick !== Game.time) {
            room._myStructures = room.find(FIND_MY_STRUCTURES);
            room._myStructuresTick = Game.time;
        }
        const myStructures = room._myStructures;
        const towers = myStructures.filter((s) => s.structureType === STRUCTURE_TOWER).length;
 
        Iif (room._myCreepsTick !== Game.time) {
            room._myCreeps = room.find(FIND_MY_CREEPS);
            room._myCreepsTick = Game.time;
        }
        const myCreeps = room._myCreeps;
        const defenders = myCreeps.filter((c) => c.memory.role === 'defender').length;
 
        const threatLevel = Memory.defenseLevel || 0;
 
        console.log(`🛡️ Defense Status [${room.name}]:`);
        console.log(`   Towers: ${towers} | Defenders: ${defenders} | Threat: ${threatLevel}`);
    },
};
 
module.exports = defenseManager;