Overmind Screeps AI

repository·master·Indexed 20 days ago

https://github.com/bencbartlett/overmind

An automated AI codebase for the MMO strategy game Screeps featuring a swarm-intelligence architecture. Overmind manages colonies via Overlords and Overseers using a directive-based system and can optionally link multiple players into a collective hivemind via an Assimilator. It supports fully automated, manual, and semiautomatic modes, as well as a specialized Reinforcement Learning (RL) training mode. Version 0.5.2 includes integrated Grafana dashboard support for tracking operating statistics.

Tokens
7.6K
Snippets
31
Records
42
Agent score
70%

What's inside Overmind

  1. Understand the Overmind AI architecture

    master

    Overmind is a swarm-intelligence-themed AI for Screeps. Its architecture is composed of several key abstractions:

    • Overlords: Orchestrate Creep actions within a specific Colony.
    • Colony: A grouping of units and resources.
    • Overseer: Monitors the colony and places Directives to adapt to environmental stimuli.
    • Directives: Specific instructions or goals issued by the Overseer.
    • Assimilator: A collective component that allows multiple players running Overmind to act as a single hivemind by sharing creeps, resources, and a master ledger of directives.

    The AI can operate in fully automated, manual, or semiautomatic modes.

  2. Install Overmind for Screeps

    master

    You can use Overmind in two ways: using a pre-compiled version or compiling from the source code.

    Option 1: Out of the box (Pre-compiled)

    If you do not want to modify the codebase, download the main.js file from the latest release and copy it directly into your Screeps script.

    Option 2: Compiling from source

    To install the full codebase and allow for modifications:

    1. Clone or download the repository.
    2. Navigate to the root directory and run npm install.
    3. Create a screeps.json file based on the example file.
    4. Use the following commands to build and deploy:
      • Public Server: npm run push-main
      • Private Server: npm run push-pserver
      • Compile only: npm run compile

    Note on Rollup: Overmind uses rollup to bundle TypeScript into main.js. To ensure internal checksum validation works correctly, ensure the local rollup installation in node_modules is used rather than a global version.

    npm install
    npm run push-main
  3. Set up the Overmind Grafana dashboard

    master

    Overmind includes a Grafana dashboard to track operating statistics. To set it up:

    1. Register for the Grafana service at screepspl.us.
    2. Set up either the ScreepsPlus hosted agent or a NodeJS agent on a micro instance (e.g., Google Compute).
    3. Import the dashboard configuration from assets/Grafana Dashboards/Overmind.json.
    4. In the dashboard settings, replace the $User variable with your actual Screeps username.
  4. Configure the Overmind controller signature

    master

    Overmind uses a specific controller signature to avoid penalties. If your signature does not contain the substring overmind (or its small-caps variant), your operation will be penalized by skipping every 3rd tick.

    The default signature is defined using the OVERMIND_SMALL_CAPS constant. You can override your signature using the console command setSignature().

  5. Reinforcement Learning (RL) mode execution

    master

    If RL_TRAINING_MODE is enabled in your settings, Overmind switches to a specialized execution path designed for training reinforcement learning models.

    In RL mode:

    • The loop uses main_RL, which skips the standard lifecycle and instead performs a fresh instantiation of _Overmind every tick and runs ActionParser.run().
    • The onGlobalReset function is replaced by onGlobalReset_RL, which only performs Mem.format().
    • The console will print a training message via OvermindConsole.printTrainingMessage().
  6. Understand the Overmind execution lifecycle

    master

    When running in standard mode, the loop follows a specific sequence of operations every tick:

    1. Memory Operations: Loads previous memory via Mem.load(), checks if the loop should proceed via Mem.shouldRun(), and cleans memory via Mem.clean().
    2. Instantiation:
      • If Overmind.shouldBuild is true or the object has expired, it deletes the old global.Overmind, runs garbage collection, and instantiates a new _Overmind object.
      • Otherwise, it calls Overmind.refresh() to update the existing state.
    3. Tick Loop Cycle:
      • Overmind.init(): Handles spawning and energy requests.
      • Overmind.run(): Executes state-changing actions.
      • Overmind.visuals(): Renders visuals.
      • Stats.run(): Records statistics.
    4. Post-run: Executes sandbox() code, runs the remoteDebugger, and finally calls Overmind.postRun() for error catching.
  7. Configure Overmind environment settings

    master

    Overmind uses several global constants in ~settings.ts to control its behavior, profiling, and operational modes. While many are managed automatically, certain settings can be adjusted to tune performance or enable specific modes like Reinforcement Learning (RL) training.

    Profiling Settings

    Profiling is computationally expensive and can cause script timeouts. You can control its impact using:

    • USE_PROFILER: Set to true to build from source including screeps-profiler.
    • PROFILER_COLONY_LIMIT: Limits the number of colonies handled while profiling. Colonies above this limit are skipped.
    • PROFILER_INCLUDE_COLONIES: A list of specific colony names to ensure are included in the random selection when profiling.

    Operational Modes and Limits

    • DEFAULT_OPERATION_MODE: Sets the initial mode (e.g., 'automatic'). If enabled, Memory.bot will default to true.
    • MAX_OWNED_ROOMS: The global limit for how many rooms you can claim across all shards.
    • SHARD3_MAX_OWNED_ROOMS: A specific limit for shard3 (where CPU limits are lower).
    • USE_TRY_CATCH: When true, wraps evaluations of constructor, init, and run phases for each colony in try...catch statements to prevent total script failure.

    Reinforcement Learning (RL) Training Mode

    WARNING: Enabling RL_TRAINING_MODE will wipe the contents of your memory!

    When RL_TRAINING_MODE is true:

    • A stripped-down version of Overmind is run, suitable for training with a Python Screeps environment.
    • The main loop is disabled.
    • Creeps are controlled via serialized actions communicated from the RL model through Memory.
    • RL_TRAINING_VERBOSITY controls console logging levels:
      • 0: No logging.
      • 1: Log every 100th or 101st tick.
      • 2: Log every tick.
  8. Configure RoadLogistics settings

    master

    The RoadLogistics class uses a static settings object to control how road repairs are prioritized and managed. You can tune these values to change the sensitivity of the repair logic.

    • allowedPaversPerRoom: The maximum number of workers allowed to be assigned to repaving roads in a single room simultaneously.
    • criticalThreshold: A percentage (0.0 to 1.0) representing the HP level below which a road is considered 'critical' and triggers an immediate repair request.
    • repairThreshold: A percentage (0.0 to 1.0) representing the HP level below which a road is considered 'repairable'.
    ```typescript
    RoadLogistics.settings = {
    	allowedPaversPerRoom: 1,
    	criticalThreshold: 0.25,
    	repairThreshold: 0.9
    };
    ```埋
  9. Check if a position is reachable with isReachable()

    master

    Use Pathing.isReachable() to determine if a target position can be reached from a starting position within the same room, given a set of obstacles. It returns true if a valid path exists and false otherwise.

    const reachable = Pathing.isReachable(startPos, endPos, [obstaclePos1, obstaclePos2]);
  10. Find a kiting path with findKitingPath()

    master

    Use Pathing.findKitingPath() to find a path that moves away from specific threats. It calculates a path that maximizes distance from the provided fleeFrom positions (which can be RoomPosition or any object with a pos property).

    const path = Pathing.findKitingPath(creepPos, [hostilePos1, hostilePos2], {
      fleeRange: 5,
      terrainCosts: { plainCost: 1, swampCost: 5 }
    });
  11. Execute the ActionParser loop

    master

    To enable reinforcement learning control over your creeps, call ActionParser.run().

    When called, the parser:

    1. Identifies controllable actors (creeps where isBot is false) and uncontrollable actors (scripted bots).
    2. Reads the JSON-serialized actions from RawMemory.segments[RL_ACTION_SEGMENT].
    3. Executes the commands for controllable actors.
    4. Runs TrainingOpponents.simpleCombat(bot) for uncontrollable actors.
    5. Clears the action segment to prepare for the next tick.

    Note: The parser automatically calls actor.autoEngage() after executing a valid command unless configured otherwise internally.

    // In your main game loop
    ActionParser.run();