### Hive Initialization and Room Operations - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt This snippet demonstrates how to initialize the Hive interface for a specific room and then perform various operations. It includes getting room statistics, requesting power processing, room upgrades, lab reactions, factory production, and nuker filling. It utilizes callbacks to handle the completion of asynchronous operations. ```javascript let hive = new Hive('W1N1'); let stats = hive.getStats(); console.log(`Processing ${stats.processPower} power`); console.log(`Upgrading with ${stats.upgrade} energy`); console.log(`Running reaction: ${stats.runReaction.type} (${stats.runReaction.amount})`); hive.processPower(function(completed) { if (completed) { console.log('Power processing complete'); this.logisticsManager.updatePowerRequests(); } }); hive.upgrade(function(completed) { if (completed && Game.rooms['W1N1'].controller.level === 8) { console.log('Room fully upgraded!'); this.transitionToMaintenanceMode(); } }); hive.runReaction(RESOURCE_CATALYZED_GHODIUM_ACID, function(amount) { console.log(`Produced ${amount} of XGH2O`); if (amount >= 3000) { this.boostManager.enableGHO2Boost(); } }); hive.produce(RESOURCE_BATTERY, function(produced) { if (produced >= 5000) { hive.send(function() { console.log('Batteries shipped to market'); }); } }); if (Game.rooms['W1N1'].nuker && Game.rooms['W1N1'].nuker.cooldown < 500) { hive.fillNuker(function() { console.log('Nuker ready to fire'); }); } ``` -------------------------------- ### Get Resource Type - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Retrieves a resource type from a structure's store, with options for specifying desired resources and checking them in a particular order. This is useful for efficiently managing resource withdrawals based on priorities. ```javascript let resourceType = global.get_resource_type( container.store, new Set([RESOURCE_ENERGY, RESOURCE_POWER]), true ); if (resourceType) { creep.withdraw(container, resourceType); } ``` -------------------------------- ### JavaScript Step System: Executing Individual Actions Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Manages individual work phases for creeps, such as resource acquisition and task performance. It includes methods for preparation, acquiring resources, performing actions, and marking steps as finished. This class is designed for individual actions within a larger task. ```javascript let repairStep = new Step_Labor({ name: 'repair_walls', sources: new Set([storage.id, terminal.id]), destinations: new Set(walls.map(w => w.id)) }); repairStep.prepare = function(creep) { this.targetWall = creep.pos.findClosestByPath(this.dsts); this.ready = true; }; repairStep.acquire = function(creep) { let source = Game.getObjectById([...this.srcs][0]); if (creep.pos.isNearTo(source)) { creep.withdraw(source, RESOURCE_ENERGY); if (creep.store.getFreeCapacity(RESOURCE_ENERGY) === 0) { this.working = true; } } else { creep.moveTo(source); } }; repairStep.perform = function(creep) { let target = Game.getObjectById(this.targetWall); if (target && target.hits < target.hitsMax) { if (creep.pos.inRangeTo(target, 3)) { creep.repair(target); } else { creep.moveTo(target); } if (creep.store[RESOURCE_ENERGY] === 0) { this.working = false; } } else { this.finished = true; } }; repairStep.work(creep); ``` -------------------------------- ### JavaScript Task System: Creating Multi-Step Tasks Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Defines a framework for creating complex, multi-step tasks for creeps in Screeps. It allows setting up task steps, defining expiration conditions, and handling completion callbacks. The system manages task progression and interruption. ```javascript let task1 = new Task({ steps: [ new Step_Labor({ name: 'harvest', sources: new Set([container.id]), destinations: new Set([storage.id]) }), new Step_Labor({ name: 'transfer', sources: new Set([storage.id]), destinations: new Set([spawn.id, ...extensions.map(e => e.id)]) }) ], name: 'energy_delivery' }); task1.is_expired = function() { return Game.time > this.createdAt + 1000 || Game.rooms['W1N1'].storage.store[RESOURCE_ENERGY] < 5000; }; task1.notify = function(success) { if (success) { console.log('Task completed successfully'); this.publishNextTask(); } else { console.log('Task expired or failed'); } }; let currentStep = task1.next_step(); if (currentStep && !currentStep.is_expired()) { creep.executeStep(currentStep); } if (creep.hits < creep.hitsMax * 0.5) { task1.recycle_unfinished_step(currentStep); } ``` -------------------------------- ### Spawn Manager Logic (JavaScript) Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt This snippet details the core logic of the Spawn Manager. It includes functions for adding spawn tasks to priority queues, finding optimal spawn rooms based on distance and energy, and processing these queues each tick to spawn creeps. It manages different priority levels and accounts for spawn times to ensure efficient creep production. ```javascript // Initialize spawn manager with three priority queues let spawnQueues = [{}, {}, {}]; // Priority levels const PRIORITY_HIGH = 0; // Haulers, defenders const PRIORITY_MID = 1; // Miners, repairers, combat squads const PRIORITY_LOW = 2; // Upgraders, remote miners, builders // Add spawn task function addSpawnTask(zergType, workPosition, time, priority) { let queue = spawnQueues[priority]; if (!queue[time]) { queue[time] = []; } let bodyParts = autoSizeBody(zergType, workPosition); // Assumed function let spawnRoom = findOptimalSpawnRoom(workPosition, bodyParts.cost); queue[time].push({ type: zergType, body: bodyParts.body, cost: bodyParts.cost, targetRoom: workPosition.roomName, spawnRoom: spawnRoom, name: `${zergType}_${Game.time}_${Math.random().toString(36).substr(2, 4)}` }); } // Find optimal spawn room based on distance and energy availability function findOptimalSpawnRoom(targetPos, energyCost) { let candidates = Object.values(Game.rooms).filter(room => room.controller && room.controller.my && room.energyCapacityAvailable >= energyCost && room.find(FIND_MY_SPAWNS).some(s => !s.spawning) ); if (candidates.length === 0) { // Fallback: find room with minimum body size candidates = Object.values(Game.rooms).filter(room => room.controller && room.controller.my && room.energyCapacityAvailable >= 300 // Minimum viable body ); } // Assuming targetPos has a findClosestByRange method or equivalent // For standard Screeps API, you might need a helper function or direct iteration. // This example uses a hypothetical method for brevity. let closestRoom = null; let minDistance = Infinity; for (const room of candidates) { const distance = Game.map.getRoomLinearDistance(targetPos.roomName, room.name); if (distance < 10 && distance < minDistance) { minDistance = distance; closestRoom = room; } } return closestRoom; } // Process spawn queues each tick function processSpawnQueues() { for (let priority = 0; priority < spawnQueues.length; priority++) { let queue = spawnQueues[priority]; if (queue[Game.time]) { for (let task of queue[Game.time]) { let room = Game.rooms[task.spawnRoom.name]; let availableSpawn = room.find(FIND_MY_SPAWNS).find(s => !s.spawning); if (availableSpawn && room.energyAvailable >= task.cost) { // Check if spawning would block higher priority tasks let spawnTime = task.body.length * CREEP_SPAWN_TIME; // Assumed constant let wouldBlockHigherPriority = false; for (let higherPriority = 0; higherPriority < priority; higherPriority++) { for (let futureTime = Game.time + 1; futureTime < Game.time + spawnTime; futureTime++) { if (spawnQueues[higherPriority][futureTime]) { // Spawn higher priority first wouldBlockHigherPriority = true; break; } } if (wouldBlockHigherPriority) break; } if (!wouldBlockHigherPriority) { let result = availableSpawn.spawnCreep(task.body, task.name, { memory: {role: task.type, targetRoom: task.targetRoom} }); if (result === OK) { console.log(`Spawning ${task.name} in ${room.name} for ${task.targetRoom}`); } else { console.log(`Failed to spawn ${task.name}: ${result}`); } } } } delete queue[Game.time]; // Prevent memory leak } } } // Example usage: Schedule hauler spawn when current one dies soon // Assuming 'hauler' is a valid Creep object available in scope // if (hauler && hauler.ticksToLive < 100) { // addSpawnTask('hauler', hauler.memory.workPosition, Game.time + 50, PRIORITY_HIGH); // } // Example usage: Schedule remote miner // Assuming RoomPosition constructor is available and 'W2N1' is a valid room name // addSpawnTask('remoteMiner', new RoomPosition(25, 25, 'W2N1'), Game.time, PRIORITY_MID); ``` -------------------------------- ### Register Transport Needs and Execute Matching Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt This JavaScript code snippet demonstrates how to register transport needs for resources and execute a matching algorithm. It defines source and target nodes with time constraints and priorities, then uses a function to match them based on proximity and availability. Dependencies include the Screeps API (Game, PathFinder, RESOURCE types) and a custom PriorityQueue implementation. ```javascript // Register transport needs by resource type let sourceNodes = {}; let targetNodes = {}; // Register energy source with time constraints sourceNodes[RESOURCE_ENERGY] = sourceNodes[RESOURCE_ENERGY] || []; sourceNodes[RESOURCE_ENERGY].push({ id: container.id, pos: container.pos, amount: 2000, startTime: Game.time, // Available from this tick endTime: Game.time + 50, // Must be collected by this tick priority: 1 // High priority (lower number = higher priority) }); // Register power spawn target targetNodes[RESOURCE_POWER] = targetNodes[RESOURCE_POWER] || []; targetNodes[RESOURCE_POWER].push({ id: powerSpawn.id, pos: powerSpawn.pos, amount: 100, startTime: Game.time + 5, // Can receive from this tick endTime: Game.time + 200, // Must be filled by this tick priority: 2 }); // Execute source-target matching using Gale-Shapley algorithm function matchSourcesAndTargets(sortedSources, sortedTargets) { // Phase 1: Sources propose to nearest targets for (let source of sortedSources) { let closestTarget = source.pos.findClosestByPath(sortedTargets, { filter: (target) => { let pathLength = PathFinder.search(source.pos, target.pos).path.length; return Game.time + pathLength >= target.startTime && Game.time + pathLength <= target.endTime; } }); if (closestTarget) { closestTarget.nearSources = closestTarget.nearSources || []; closestTarget.nearSources.push(source); } } // Phase 2: Targets choose nearest sources let matchedPairs = []; for (let target of sortedTargets) { while (target.amount > 0 && target.nearSources && target.nearSources.length > 0) { let closestSource = target.pos.findClosestByPath(target.nearSources); let transferAmount = Math.min(closestSource.amount, target.amount); matchedPairs.push({ source: closestSource, target: target, amount: transferAmount, priority: Math.min(closestSource.priority, target.priority) }); closestSource.amount -= transferAmount; target.amount -= transferAmount; if (closestSource.amount === 0) { target.nearSources = target.nearSources.filter(s => s.id !== closestSource.id); } } } return matchedPairs; } ``` -------------------------------- ### Calculate Free Capacity - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Calculates the available free capacity in a structure's store for a specific resource, handling potential storage bugs. This function is essential for determining if a structure can accept more resources. ```javascript let freeSpace = global.getFreeCapacity(storage.store, RESOURCE_ENERGY); if (freeSpace > 1000) { // Store has room for more energy } ``` -------------------------------- ### Larva Class for Creep Management (JavaScript) Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Defines the Larva class which manages individual creeps. It handles states like 'sleeping' and 'working', assigns tasks from a queue, executes tasks step-by-step, and manages creep death by scheduling respawns. Dependencies include global objects like Game, global.working, global.sleeping, global.spawnManager, global.timer, and PRIORITY_HIGH. ```javascript class Larva { constructor(creepName, workPosition, taskQueue) { this.name = creepName; this.workPosition = workPosition; this.taskQueue = taskQueue; this.state = 'sleeping'; // or 'working' this.currentTask = null; } // Activate creep (move from sleeping to working state) activate() { let creep = Game.creeps[this.name]; if (creep && creep.spawning === false) { this.state = 'working'; global.working.add(this.name); global.sleeping.delete(this.name); console.log(`${this.name} activated`); } } // Put creep to sleep (spawning or not yet spawned) sleep() { this.state = 'sleeping'; global.sleeping.add(this.name); global.working.delete(this.name); } // Assign new task assignTask(task) { if (!task.is_expired()) { this.currentTask = task; return true; } return false; } // Execute current task (called each tick for working creeps) run() { let creep = Game.creeps[this.name]; // Check if creep died if (!creep) { this.handleDeath(); return; } // Execute current task if (this.currentTask) { if (this.currentTask.is_expired()) { this.currentTask.notify(false); this.currentTask = null; this.requestNewTask(); } else { let step = this.currentTask.next_step(); if (step) { step.work(creep); if (step.finished) { // Continue to next step } } else { // Task complete this.currentTask.notify(true); this.currentTask = null; this.requestNewTask(); } } } else { this.requestNewTask(); } } // Handle creep death handleDeath() { console.log(`${this.name} died`); if (this.currentTask) { this.currentTask.recycle_unfinished_step(this.currentTask.currentStep); } this.sleep(); // Cache control object for reuse // Schedule replacement spawn global.spawnManager.addSpawnTask(this.type, this.workPosition, Game.time + 50, PRIORITY_HIGH); } // Request new task from queue requestNewTask() { while (this.taskQueue.length > 0) { let task = this.taskQueue.shift(); if (!task.is_expired()) { this.assignTask(task); return; } else { task.notify(false); // Notify task expired } } } } // Global initialization global.working = new Set(); global.sleeping = new Set(); // Initialize Larva for existing creeps (in OverSeer) for (let name in Game.creeps) { let creep = Game.creeps[name]; let larva = new Larva(name, creep.memory.workPosition, []); if (creep.spawning) { larva.sleep(); // Schedule activation when spawn completes global.timer[Game.time + creep.body.length * CREEP_SPAWN_TIME] = global.timer[Game.time + creep.body.length * CREEP_SPAWN_TIME] || []; global.timer[Game.time + creep.body.length * CREEP_SPAWN_TIME].push(() => larva.activate()); } else { larva.activate(); } } // Main loop: only process working creeps for (let creepName of global.working) { let larva = global.larvaRegistry[creepName]; larva.run(); } ``` -------------------------------- ### Assign Creeps to Tasks Using Priority Queue Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt This JavaScript code snippet outlines the process of assigning creeps to matched transport tasks using a priority queue. It initializes the queue with available haulers and then processes events to find and assign tasks, ensuring creeps are directed to the nearest available source and target within time constraints. Dependencies include the Screeps API (Game, PathFinder) and a custom PriorityQueue implementation. ```javascript // Assign creeps to matched tasks using priority queue let minHeap = new PriorityQueue(); // Initialize with available haulers for (let hauler of haulers) { if (hauler.store.getUsedCapacity() === 0) { minHeap.push(Game.time, {type: 'findTask', creep: hauler}); } } // Process events from priority queue while (!minHeap.isEmpty()) { let event = minHeap.pop(); if (event.type === 'findTask') { // Find all sources and register getTask events for (let pair of matchedPairs) { let arrivalTime = Game.time + PathFinder.search( event.creep.pos, pair.source.pos ).path.length; minHeap.push(arrivalTime, { type: 'getTask', creep: event.creep, pair: pair }); } } else if (event.type === 'getTask' && event.pair.amount > 0) { // Assign task to creep let completionTime = event.time + PathFinder.search( event.pair.source.pos, event.pair.target.pos ).path.length; event.creep.memory.task = { source: event.pair.source.id, target: event.pair.target.id, resourceType: RESOURCE_ENERGY, amount: Math.min(event.creep.store.getCapacity(), event.pair.amount) }; event.pair.amount -= event.creep.memory.task.amount; minHeap.push(completionTime, {type: 'findTask', creep: event.creep}); break; // Found assignment } } ``` -------------------------------- ### Find Serial Path to Destination - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Finds a path to a destination room using a serial pathfinding algorithm. This function is used to determine the next position for a creep to move towards a target room. ```javascript let exitPos = global.serial_dst(creep, {roomName: 'W2N1'}); if (exitPos) { creep.moveTo(exitPos); } ``` -------------------------------- ### Create Accumulator Function - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Generates an accumulator function for a given resource type, which can be used with array reduction methods like `reduce`. This simplifies summing up the total amount of a specific resource across multiple structures. ```javascript let energyAccumulator = global.accumulator(RESOURCE_ENERGY); let totalEnergy = containers.reduce(energyAccumulator, 0); console.log(`Total energy in containers: ${totalEnergy}`); ``` -------------------------------- ### Implement Class Inheritance - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Provides a mechanism for implementing class inheritance, allowing child classes to inherit properties and methods from one or more parent classes. This is a core pattern for the object-oriented design of OverDom. ```javascript function ChildClass(args) { global.super(this, [ParentClass1, ParentClass2], args); this.childProperty = args.childProperty; } global.inherit(ChildClass, [ParentClass1, ParentClass2]); ``` -------------------------------- ### Assemble Creep Body - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Assembles a creep's body based on a parts specification array. It returns an object containing the calculated body array and its total energy cost. This function is crucial for dynamically creating creeps with desired capabilities and cost. ```javascript let bodyConfig = [[WORK, 6], [CARRY, 3], [MOVE, 9]]; let assembly = global.makeup_body(bodyConfig); console.log(assembly.body); console.log(assembly.cost); ``` -------------------------------- ### Colorful Console Output - JavaScript Source: https://context7.com/lc150303/the-design-of-overdom/llms.txt Formats text for console output with specified colors. This utility aids in debugging and highlighting important messages in the Screeps console. ```javascript console.log(global.colourful('High priority alert!', 'red')); console.log(global.colourful('Task completed', 'green')); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.