Screeps AI: Building an Operating System

Posted by Argha Sen on August 21, 2022

After playing through for some time in screeps, it is abundantly clear that CPU management is an important part of the game. I have been ignoring it for the most part because I was still far away from the original 20 CPU limit but I was beginning to see how it would be a limiting factor.

After going through the discord channel of Screeps, I decided to develop an operating system for the AI. The operating system model is used by quite a few top players so developing it early seemed a good idea.

Writing an Operating System for screeps

At the very least the operating system system needs a Kernel, which will be responsible for running the various processes in the AI. The processes are scheduled by a Scheduler and there is also a process framework.

Kernel

The Kernel is a very simple class which launches the base AI process. It is also responsible for running the processes that are scheduled by the scheduler. The Kernel also looks after the CPU limits. The rudimentary kernel is sufficient for now but will need to have more features as the OS evolves.

Scheduler

The scheduler of our OS is inspired by Quorum, an opensource bot for Screeps. Though Quorum’s scheduler is much more advanced, I have only implemented the basic parts needed for the OS to start working.

Current Features of the Scheduler

  1. The scheduler can launch new processes as a parent or a child process.
  2. There are multiple queues with a ReadyQueue, RunningQueue and CompletedQueue.
  3. At every tick the scheduler will reschedule completed processes for the next tick.
  4. Provides the kernel with a new process PID when the kernel asks.
  5. Stores metadata about a process so it can create the process on a tick.

Additional Features useful but not yet implemented

  1. Ability to suspend processes.
  2. Ability to kill processes
  3. Cleaning up of memory for killed processes.

Processes

At the heart of any OS is the ability to run user processes. The implementation of process in our OS follows the ideas of Java threads. Each process when launched can do some work for initialization and is analogus to how constructors work.

The runnable part of the process comes from the kernel calling it’s main function. As a result all our process must have a main function. This is enforced by the OS by having all runnable process inherit from a base Process class and having the main method abstract in the process class.

The code upto this point can be seen here