All files / my-screeps-repo auto.evolution.js

50% Statements 96/192
39.13% Branches 36/92
73.91% Functions 17/23
51.41% Lines 91/177

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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502                    3x 3x 3x   3x         10x 10x                                               1x     1x         1x       1x     1x             1x   1x   1x 1x 1x 1x 1x                                                                     2x 2x 1x 1x 1x       2x                         2x             3x 3x 3x   3x 2x 2x 2x   2x         3x                       2x               2x             2x 1x   1x     1x       1x 1x     2x                                                                                                         1x 1x                 1x               1x 1x                           1x                           1x 1x 1x 1x 1x             33x     33x 10x     23x   23x 91x 1x 1x       23x 22x 22x 22x               90x       90x       90x   90x   90x               90x 10x     90x   90x             90x   90x                           90x     90x               90x 50x     90x 90x             1x   1x                                                   1x             182x               182x                                                                                                   1x 1x       3x  
/**
 * Auto Evolution System - 自動進化AI
 * ゲーム状況に応じて自動的に新コードを生成・更新
 * CPU最適化版
 */
 
/**
 * Security: Limits for memory-intensive structures to prevent Memory DoS.
 * Screeps memory is limited to 2MB; unbounded arrays can crash the AI.
 */
const MAX_HISTORY = 50;
const MAX_QUEUE = 10;
const MAX_SUGGESTIONS = 20;
 
const autoEvolution = {
    /**
     * 初期化
     */
    init: function () {
        Eif (!Memory.evolution) {
            Memory.evolution = {
                history: [],
                queue: [],
                lastRCL: 0,
                lastCheck: 0,
                lastFullAnalysis: 0,
                suggestions: [],
                stats: {
                    totalEvolutions: 0,
                    successRate: 1.0,
                },
                cache: {
                    gameState: null,
                    cacheTime: 0,
                },
                analysisPhase: 0,
            };
        }
    },
 
    /**
     * メインループ - 毎ティック実行
     */
    run: function () {
        this.init();
 
        // CPU使用率チェック - 50%超えたら処理スキップ
        Iif (Game.cpu.getUsed() / Game.cpu.limit > 0.5) {
            return;
        }
 
        // 100ティックごとにチェック
        Iif (Game.time - Memory.evolution.lastCheck < 100) {
            return;
        }
 
        Memory.evolution.lastCheck = Game.time;
 
        // 段階的処理
        this.runPhase();
    },
 
    /**
     * 段階的処理実行
     */
    runPhase: function () {
        const phase = Memory.evolution.analysisPhase;
 
        switch (phase) {
            case 0: {
                const basicState = this.analyzeBasicState();
                Memory.evolution.cache.gameState = basicState;
                Memory.evolution.cache.cacheTime = Game.time;
                Memory.evolution.analysisPhase = 1;
                break;
            }
            case 1: {
                const state = Memory.evolution.cache.gameState;
                if (state) {
                    state.bottlenecks = this.analyzeBottlenecks();
                    Memory.evolution.cache.gameState = state;
                }
                Memory.evolution.analysisPhase = 2;
                break;
            }
            case 2: {
                const cachedState = Memory.evolution.cache.gameState;
                if (cachedState) {
                    const needs = this.needsEvolution(cachedState);
                    const self = this;
                    needs.forEach(function (need) {
                        self.addToQueue(need);
                    });
                }
                Memory.evolution.analysisPhase = 3;
                break;
            }
            case 3:
                this.processQueue();
                Memory.evolution.analysisPhase = 0;
                Memory.evolution.lastFullAnalysis = Game.time;
                break;
        }
    },
 
    /**
     * 基本状態分析(軽量版)
     */
    analyzeBasicState: function () {
        const myRooms = [];
        for (const roomName in Game.rooms) {
            const room = Game.rooms[roomName];
            Eif (room.controller && room.controller.my) {
                myRooms.push(room);
            }
        }
 
        const state = {
            rcl: myRooms.length > 0 ? myRooms[0].controller.level : 0,
            roomCount: myRooms.length,
            creepCount: Object.keys(Game.creeps).length,
            spawns: Object.keys(Game.spawns).length,
            gcl: Game.gcl.level,
            resources: this.analyzeResourcesLight(myRooms),
            structures: this.analyzeStructuresLight(myRooms),
            threats: [],
            opportunities: {},
            bottlenecks: [],
        };
 
        return state;
    },
 
    /**
     * リソース分析(軽量版)
     */
    analyzeResourcesLight: function (rooms) {
        let totalEnergy = 0;
        let storageEnergy = 0;
        let capacity = 0;
 
        for (let i = 0; i < rooms.length; i++) {
            const room = rooms[i];
            totalEnergy += room.energyAvailable;
            capacity += room.energyCapacityAvailable;
 
            Iif (room.storage) {
                storageEnergy += room.storage.store[RESOURCE_ENERGY] || 0;
            }
        }
 
        return {
            energy: totalEnergy,
            capacity: capacity,
            storage: storageEnergy,
            ratio: capacity > 0 ? totalEnergy / capacity : 0,
        };
    },
 
    /**
     * 構造物分析(軽量版)
     */
    analyzeStructuresLight: function (rooms) {
        const structures = {
            towers: 0,
            storage: 0,
            links: 0,
            labs: 0,
            terminals: 0,
        };
 
        const structureCounter = (structure) => {
            const type = structure.structureType;
            if (type === STRUCTURE_TOWER) structures.towers++;
            else if (type === STRUCTURE_LINK) structures.links++;
            else if (type === STRUCTURE_LAB) structures.labs++;
        };
 
        for (let i = 0; i < rooms.length; i++) {
            const room = rooms[i];
 
            Iif (room.storage) {
                structures.storage++;
            }
            Iif (room.terminal) {
                structures.terminals++;
            }
 
            const roomStructures = room.find(FIND_MY_STRUCTURES);
            roomStructures.forEach(structureCounter);
        }
 
        return structures;
    },
 
    /**
     * ボトルネック分析(必要最小限)
     */
    analyzeBottlenecks: function () {
        const bottlenecks = [];
 
        for (const roomName in Game.rooms) {
            const room = Game.rooms[roomName];
            if (!room.controller || !room.controller.my) {
                continue;
            }
 
            const creeps = room.find(FIND_MY_CREEPS);
 
            const harvesters = [];
            for (let i = 0; i < creeps.length; i++) {
                if (creeps[i].memory.role === 'harvester') {
                    harvesters.push(creeps[i]);
                }
            }
 
            const sources = room.find(FIND_SOURCES);
 
            if (harvesters.length < sources?.length * 2) {
                bottlenecks.push({
                    room: room.name,
                    type: 'insufficient_harvesters',
                    current: harvesters.length,
                    needed: sources.length * 2,
                });
            }
 
            if (room.energyAvailable < room.energyCapacityAvailable * 0.3) {
                bottlenecks.push({
                    room: room.name,
                    type: 'energy_shortage',
                    severity: 'high',
                });
            }
 
            break;
        }
 
        return bottlenecks;
    },
 
    /**
     * 進化必要性判定 - RCLアップグレード検知
     */
    _checkRclUpgrade: function (state, needs) {
        Eif (state.rcl > Memory.evolution.lastRCL) {
            needs.push({
                type: 'rcl_upgrade',
                priority: 10,
                data: {
                    oldRCL: Memory.evolution.lastRCL,
                    newRCL: state.rcl,
                },
                action: 'create_rcl_features',
            });
            Memory.evolution.lastRCL = state.rcl;
        }
    },
 
    /**
     * 進化必要性判定 - ボトルネック解消
     */
    _checkBottlenecks: function (state, needs) {
        const bottlenecks = state.bottlenecks || [];
        for (let i = 0; i < Math.min(bottlenecks.length, 2); i++) {
            needs.push({
                type: 'bottleneck_fix',
                priority: 7,
                data: bottlenecks[i],
                action: 'optimize_production',
            });
        }
    },
 
    /**
     * 進化必要性判定 - 新機能追加
     */
    _checkNewFeatures: function (state, needs) {
        Iif (state.rcl >= 3 && state.structures.towers === 0) {
            needs.push({
                type: 'new_feature',
                priority: 8,
                data: { feature: 'tower_management' },
                action: 'create_tower_logic',
            });
        }
    },
 
    /**
     * 進化必要性判定(簡略版)
     */
    needsEvolution: function (state) {
        const needs = [];
        this._checkRclUpgrade(state, needs);
        this._checkBottlenecks(state, needs);
        this._checkNewFeatures(state, needs);
        return needs;
    },
 
    /**
     * キューに追加
     */
    addToQueue: function (need) {
        const queue = Memory.evolution.queue;
 
        // Security: Prevent queue flooding (Memory DoS)
        if (queue.length >= MAX_QUEUE) {
            return;
        }
 
        let exists = false;
 
        for (let i = 0; i < queue.length; i++) {
            if (queue[i].type === need.type && queue[i].action === need.action) {
                exists = true;
                break;
            }
        }
 
        if (!exists) {
            need.timestamp = Game.time;
            Memory.evolution.queue.push(need);
            console.log('🤖 Evolution queued: ' + need.type + ' (Priority: ' + need.priority + ')');
        }
    },
 
    /**
     * キュー処理
     */
    processQueue: function () {
        Iif (Memory.evolution.queue.length === 0) {
            return;
        }
 
        Memory.evolution.queue.sort(function (a, b) {
            return b.priority - a.priority;
        });
 
        const item = Memory.evolution.queue[0];
 
        this.generateCodeSuggestion(item);
 
        Memory.evolution.history.push({
            time: Game.time,
            type: item.type,
            action: item.action,
            data: item.data,
        });
 
        // Security: Immediate rotation to prevent Memory DoS
        if (Memory.evolution.history.length > MAX_HISTORY) {
            Memory.evolution.history.shift();
        }
 
        Memory.evolution.stats.totalEvolutions++;
 
        Memory.evolution.queue.shift();
    },
 
    /**
     * コード生成提案
     */
    generateCodeSuggestion: function (item) {
        let suggestion = '';
 
        switch (item.action) {
            case 'create_rcl_features':
                suggestion = this.generateRCLFeatures(item.data);
                break;
 
            case 'optimize_production':
                suggestion = this.generateProductionOptimization(item.data);
                break;
 
            case 'create_tower_logic':
                suggestion = this.generateTowerLogic();
                break;
 
            default:
                suggestion = '// Evolution suggestion';
        }
 
        Memory.evolution.suggestions.push({
            time: Game.time,
            type: item.type,
            code: suggestion,
            filename: this.getFilename(item.action),
        });
 
        // Security: Immediate rotation (limited because suggestions contain large code blocks)
        if (Memory.evolution.suggestions.length > MAX_SUGGESTIONS) {
            Memory.evolution.suggestions.shift();
        }
 
        console.log('✨ Code suggestion generated: ' + this.getFilename(item.action));
        console.log('📝 Check Memory.evolution.suggestions for details');
    },
 
    /**
     * RCL機能生成
     */
    generateRCLFeatures: function (data) {
        const rcl = data.newRCL;
 
        Eif (rcl === 3) return '// Tower management code needed\n// Create structure.tower.js';
        if (rcl === 4) return '// Storage management needed\n// Create storage.manager.js';
        if (rcl === 5) return '// Link network needed\n// Create link.network.js';
        if (rcl === 6) return '// Mineral mining needed\n// Create role.miner.js';
 
        return '// RCL ' + rcl + ' features';
    },
 
    /**
     * 生産最適化コード生成
     */
    generateProductionOptimization: function (data) {
        return (
            '// Optimize ' +
            data.type +
            '\n// Current: ' +
            (data.current ?? 'N/A') +
            ', Needed: ' +
            (data.needed ?? 'N/A')
        );
    },
 
    /**
     * Towerロジック生成
     */
    generateTowerLogic: function () {
        return 'module.exports = {\n  run: function(tower) {\n    // Attack hostiles\n    // Repair structures\n  }\n};';
    },
 
    /**
     * ファイル名取得
     */
    getFilename: function (action) {
        const map = {
            create_tower_logic: 'structure.tower.js',
            create_storage_logic: 'storage.manager.js',
            create_link_logic: 'link.network.js',
            create_defense: 'role.defender.js',
            optimize_production: 'spawn.optimizer.js',
        };
 
        return map[action] || 'evolution.code.js';
    },
 
    /**
     * ダッシュボード表示
     */
    showDashboard: function () {
        this.init();
        const evo = Memory.evolution;
 
        console.log('\n🤖 === AUTO EVOLUTION DASHBOARD === 🤖');
        console.log('Total Evolutions: ' + evo.stats.totalEvolutions);
        console.log('Success Rate: ' + evo.stats.successRate * 100 + '%');
        console.log('Queue Length: ' + evo.queue.length);
        console.log('Current Phase: ' + evo.analysisPhase);
        console.log('Last Full Analysis: ' + (Game.time - evo.lastFullAnalysis) + ' ticks ago');
 
        if (evo.history.length > 0) {
            console.log('\n📜 Recent Evolution History:');
            const recentHistory = evo.history.slice(-5);
            for (let i = 0; i < recentHistory.length; i++) {
                const h = recentHistory[i];
                console.log('  [' + h.time + '] ' + h.type + ': ' + h.action);
            }
        }
 
        if (evo.queue.length > 0) {
            console.log('\n⏳ Pending Evolutions:');
            const pendingQueue = evo.queue.slice(0, 5);
            for (let i = 0; i < pendingQueue.length; i++) {
                const q = pendingQueue[i];
                console.log('  Priority ' + q.priority + ': ' + q.type + ' (' + q.action + ')');
            }
        }
 
        if (evo.suggestions.length > 0) {
            console.log('\n💡 Code Suggestions:');
            const recentSuggestions = evo.suggestions.slice(-3);
            for (let i = 0; i < recentSuggestions.length; i++) {
                const s = recentSuggestions[i];
                console.log('  [' + s.time + '] ' + s.filename);
                console.log('  ' + s.code.split('\n')[0]);
            }
        }
    },
 
    /**
     * リセット
     */
    reset: function () {
        delete Memory.evolution;
        console.log('🔄 Evolution system reset!');
    },
};
 
module.exports = autoEvolution;