Part 2 of the series Building a Screeps AI. Previous part: A Game You Play With Code: Why I Build a Screeps Bot
Every few seconds my bot forgets who it is — and then rebuilds itself in a few milliseconds.
That sounds dramatic, but it is simply how the bot works. In this part I want to show what happens inside one of those moments, why the order of things matters more than any class diagram, and which parts of the architecture I would build the same way again.
The tick: the only clock that counts
In Screeps nothing happens continuously. The world moves in ticks. Once per tick the server calls a single function in your code, usually named loop. Your code looks at the world, decides what every creep, tower and spawn should do, and returns. The server then applies all those decisions at once, and the next tick starts.
Two consequences shape everything else:
- Your decisions are intents, not actions. When a creep calls
harvest()in your code, nothing has been harvested yet. It is a wish that the server resolves after your code is done. You never see the result in the same tick. - You can’t count on memory between ticks. There is a persistent
Memoryobject (JSON, stored by the server), and there is the JavaScript heap. The heap usually survives from one tick to the next, but it can be thrown away at any time — after a deploy, a server restart, or just because the server decided so. Anything you keep there is a cache, never the truth.
Rebuilding instead of remembering
My answer to the second point was never a deliberate design decision. It grew that way: at the start of every tick the bot builds a fresh picture of its empire. A central orchestrator is constructed, and its constructor walks through the game state and indexes everything the rest of the code will need: spawns and structures per room, construction sites, creeps grouped by role and by room, and a classification of rooms into “mine” and “someone else’s”.
Only after that picture is complete does anything start to make decisions.
Why did it end up like this? Because the alternative bit me. In the early years I kept objects and IDs around between ticks, and the world kept changing under my feet. A creep died and a new one took its place with a new ID; a structure was destroyed and rebuilt; and my cleanup of dead creeps ran in the wrong order, so some systems still worked with creeps that no longer existed. Rebuilding everything from the current game state made a whole class of bugs disappear at once.
The price is CPU. Indexing hundreds of creeps and thousands of structures every single tick is not free, and that bill shows up later in this series, when we get to profiling. I am honestly not sure every part of this rebuild is still necessary today; some of the original problems may be gone. It is one of the places where I still see room to optimise.

The layers
From the outside the bot is one big loop. Inside, it has settled into a few layers, each with a clear job:
- The tick shell. The
loopfunction itself. It prepares memory, removes the memory of dead creeps, starts statistics and profiling — and then hands over to the orchestrator. It knows almost nothing about the game. - The empire orchestrator. The class that is rebuilt every tick. It owns the big picture: which rooms exist, which creeps belong where, which systems run in which order.
- Persistent strategy. Things that need to outlive a tick: the task queue, the assessment of rooms the bot might expand into, statistics.
- Room systems. One for the economy of each owned room, one for foreign rooms, plus defence, market, labs and maintenance. Most real decisions live here.
- Helpers. Small, isolated modules with pure functions: how strong should a rampart be, is a terminal full or desperate, which lab reaction is valid. These are the parts with the most unit tests.
- Unit behaviour. Every creep is mapped to a role class (harvester, hauler, upgrader, defender …), and that class decides what the creep does this tick.
In the first article I called this “four layers”; the persistent strategy and the helpers are the glue that the other four lean on.

Three kinds of state
The most useful idea in the whole architecture is boring: keep three kinds of state apart.
- Per-tick scratch. Lists and flags that only make sense during the current tick, and are cleared at the end of it.
- Per-tick indexes. The picture the orchestrator builds: creeps by role and room, structures by type. Rebuilt every tick, read by everyone.
- Persistent memory. Tasks, room plans, scouting results, statistics. This is the bot’s long-term memory, and it is the only thing that really survives.

Mixing these up is where most of my strange bugs came from. A value that should have been per-tick ended up in memory and was never cleaned up. A cache in the heap was treated like the truth and quietly went stale after a reset.
Separating them also solved a very practical problem. Shared per-tick state first lived in the orchestrator itself, so every module that needed it had to import the orchestrator — which in turn imported those modules. More on why that is a real problem in Screeps in a moment.
Order is architecture

Here is the tick, simplified:
export const loop = () => {
restoreMemory(); // nothing may touch Memory before this
removeMemoryOfDeadCreeps();
releaseTasksOfDeadCreeps();
const empire = new Empire(); // rebuild all indexes from the game state
empire.run(); // rooms → assessment → market → flags → creeps
empire.shutdown(); // persist tasks, statistics, clear per-tick state
};
class Empire {
run() {
for (const room of this.ownedRooms) room.runEconomy();
for (const room of this.foreignRooms) room.queueTasks();
this.assessment.run();
this.market.run();
this.flags.run();
for (const creep of this.creeps) creep.run();
}
}
There is nothing clever in it, and that is the point. The order carries rules that you won’t find in any type signature:
- The indexes must exist before any room system asks “how many haulers does this room have?”.
- Dead creeps must be gone from memory before tasks are handed out, or a task is assigned to a ghost.
- Rooms queue their tasks before creeps run, so a creep can pick up work that was created in the same tick.
- Statistics and task persistence come last, after every system has had its say.
Swap two of those lines and nothing crashes. The bot just behaves a little wrong, in a way that takes days to notice.
The bug class that taught me the most
The hardest lessons, though, were not about the order of my systems. They were about the order of the game’s rules: which creep may do which action, and which actions are allowed together in the same tick.
Remember that every action is only an intent. The engine collects them and resolves them after your code is done. Some actions can be combined freely — a creep can move and work in the same tick. Others exclude each other, and the engine does not tell you. It keeps one intent and silently drops the other.
Imagine your code tells a single creep, within one tick: move left, heal, attack, move right, and while you’re at it, clap your hands. Every one of those calls happily returns “OK”. What actually happens is decided later, by two simple rules:
- The same action twice: the last call wins. Two move orders don’t add up; the creep simply takes the last one.
- Related actions compete: a fixed priority wins. Actions are grouped into what the game calls pipelines. Within a pipeline only one action is executed, and which one is decided by a fixed priority list, not by the order in which your code called them. Actions from different pipelines run side by side: moving, healing, picking something up and handing it over can all happen in the same tick.
creep.move(LEFT);
creep.heal(friend); // may be dropped if a higher-priority action in its pipeline was ordered too
creep.attack(enemy);
creep.move(RIGHT); // the creep moves right; the first move is forgotten
The nasty part: a dropped intent still returned “OK”. Even a pointless one counts — healing a creep that is already at full health blocks the other actions in its pipeline just as well. Nothing in your logs tells you which wishes were quietly ignored. So the code has to know these rules and decide up front what matters most this tick, instead of asking for everything and hoping. (The official documentation has a page on simultaneous actions with the full priority diagram.)
My favourite example: two different parts of the bot wanted to use the same spawn in the same tick. First the military code asked for a squad member, then the room economy asked for a hauler. Both calls returned “OK”. But the engine only keeps the last intent of a kind per object, so only the hauler was ever born. The squad member’s memory entry existed, the creep never did — and the war planner counted it as killed in action. The fix was a one-line rule: one spawn request per spawn per tick. Finding it took much longer.
Combat is full of these trade-offs. A creep with both ranged attack and healing parts cannot shoot and heal at range in the same tick. So every tick it has to decide: keep shooting, or save a friend who is about to die two tiles away? For a long time my defenders always shot. They lost fights against smaller groups that simply healed each other.
Rewriting — but not everything
With a codebase that grew over eight years, the question of a full rewrite comes up regularly. I did rewrite parts: defence and ramparts got a new model, and warfare was rebuilt from scratch only recently. The old version could defend a room and launch a basic attack, but it had no idea how to bring in help from other rooms or move a squad as one unit. That rewrite alone cost me around three months on my private test server.
What I never rewrote is the core: the task system and the creep roles. I was — and still am — convinced that the basic idea is right. Instead of a big bang, new systems are built next to the old core as small, isolated islands with pure functions and their own tests. The old core stays as the stable centre that keeps the economy running while the islands around it get better. In a world that never pauses, that is the only kind of rewrite you can afford.
No bundle, but a cycle guard
One Screeps quirk deserves its own short section. Screeps only runs JavaScript, but my bot is written in TypeScript: types catch a whole class of mistakes before the code ever reaches the live world, and in a codebase this size they are also the best documentation I have. So every deploy starts with a build step that compiles TypeScript to JavaScript.
Most projects bundle the result into a single file. My bot does not: every TypeScript file becomes its own JavaScript module in the game, and the build only rewrites the import paths so that Screeps can find them.
That keeps errors local — a stack trace points to the real file — but it comes with a trap. The Screeps runtime does not tolerate circular imports. If module A imports B and B imports A, the bot doesn’t run slightly wrong, it doesn’t run at all. That is exactly why the shared per-tick state moved out of the orchestrator into its own small module, and why every build now runs an automatic check for import cycles before anything is deployed.
Flags as a control panel
The last piece of the tick is an old friend from the first article: flags. In 2018 they were the whole bot — a remote control with coloured buttons. Today the bot runs without them, but they did not disappear. They changed their job.
For me, flags are now two things. First, a window into the bot: they show what it is planning in a room. A red flag, for example, means the bot wants to take that room down.
Screeps has a much richer tool for this: room visuals, lines, shapes and text drawn over the map. My bot can draw the whole planned layout of a room, or the path every creep would like to take next. It is great for debugging, but it costs CPU every tick to draw, and with hundreds of creeps my browser struggles to render it all. So the visuals stay switched off most of the time, and the flags remain the main indicator: cheap, persistent, and visible at a glance on the world map.
Second, flags are a way to step in when I want to. When I focus on a particular room, I can place a flag and the bot will prioritise claiming it. For a long time that was more necessary than I liked, because the automatic expansion did not pay enough attention to resources, or happily walked its claimers straight through hostile territory.
That is the difference between a remote control and a steering wheel: the bot drives, and I can still point it in a direction.
What’s next
So far we have looked at a single tick, from the outside in. But a tick is just a frame. The interesting part is how hundreds of creeps work together across thousands of those frames without stepping on each other’s toes.
Next time: the task system — how “something should be done” becomes “this creep does it”, and how the bot remembers what it was doing.