A Tick in the Life: How My Bot Rebuilds Itself Every Few Seconds

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 Memory object (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.

Horizontal bar chart of CPU time per tick: creeps acting about 166 ms, room economy about 61 ms, everything else about 21 ms.
Where one tick’s CPU goes on the live server (November 2026, 23 rooms).

The layers

From the outside the bot is one big loop. Inside, it has settled into a few layers, each with a clear job:

  1. The tick shell. The loop function 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.
  2. 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.
  3. Persistent strategy. Things that need to outlive a tick: the task queue, the assessment of rooms the bot might expand into, statistics.
  4. 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.
  5. 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.
  6. 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.

Six stacked layers: tick shell, empire orchestrator, persistent strategy, room systems, helpers, unit behaviour; persistent strategy and helpers drawn dashed as glue.
The six layers. Solid: the four from part 1. Dashed: the glue they 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.
Timeline over six ticks: per-tick scratch and per-tick indexes are separate boxes per tick, persistent memory is one continuous bar.
Three kinds of state and how long each one lives.

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

Flow of one tick in seven steps: prepare, rebuild, rooms, empire, flags, creeps, shutdown.
One tick, in order. Swap two steps and nothing crashes, the bot just behaves a little wrong.

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.

A Game You Play With Code: Why I Build a Screeps Bot

Part 1 of the series Building a Screeps AI.

I wanted to learn JavaScript. What I ended up with is an empire of more than 500 small robots that runs day and night without me, trades on a market, builds its own cities and occasionally goes to war.

This is the first part of a series about that journey. It is less about clever algorithms (those come later) and more about the question every side project has to answer at some point: why on earth am I doing this?

What is Screeps?

Imagine a real-time strategy game in which you never click a unit. Instead you write code, upload it, and the game server runs it for you — every single game tick, around the clock, against other players who do exactly the same.

That is Screeps. A few core ideas are enough to follow the rest of the series (the official documentation has the full picture):

Diagram: one tick in Screeps. The server hands your code the state of the world, your code decides within the CPU budget, then the server applies all decisions at once and the next tick starts.
One tick: the world waits, your code decides, the server acts, and the cycle repeats every few seconds.
  • The world is a huge grid of rooms. Each room is a 50 × 50 tile map with energy sources, sometimes a mineral, and a controller you can claim.
  • Creeps are your units. You design their bodies from parts (work, carry, move, attack, heal …), spawn them, and they die of old age after roughly 1500 ticks. Nothing lives forever — everything has to be replaced.
  • A tick is one game step. Each tick the server calls your code once. Whatever your code decides in that moment is what happens.
  • CPU is the real currency. Every player gets a fixed CPU budget per tick. Smart code does more with less; sloppy code hits the limit and simply stops thinking for a while.
  • The controller level (RCL) of a room unlocks buildings, and your global control level (GCL) decides how many rooms you may own at all.

Quick glossary

  • Tick: one game step; your code runs once per tick.
  • Creep: a unit you design, spawn and program.
  • Room: a 50 × 50 tile map; the world is a grid of them.
  • Spawn: the building that produces creeps.
  • Controller / RCL: the heart of an owned room; its level unlocks buildings.
  • GCL: your global control level; it limits how many rooms you can own.
  • CPU budget: the computing time you get per tick.
  • Bucket: unused CPU that is saved up for busy ticks.
  • Shard: one of several separate copies of the world map.

The twist is that you are never really “playing”. You are designing a system that plays. If it fails at 3 a.m., it fails alone.

Where this bot comes from

Bar chart of commits per month from 2018 to 2026 on a log scale: a single commit in 2018, a burst in autumn 2021, a few commits during the quiet years, and a much larger burst from spring 2026 peaking at over 300 commits per month.
Commits per month to the bot, 2018–2026 (log scale). Source: git history, as of November 2026.

2018: one room and a lot of flags

I found Screeps in 2018, at a time when I knew very little JavaScript. My first attempts could barely build up a single room. Most of what happened was steered by hand: I placed coloured flags in the game, and the code reacted to them — “build here”, “attack there”, “claim this room”.

It worked, sort of. But it was a remote control, not an AI. The bot did what I told it; the moment I stopped watching, it stopped improving.

2021: the restart

In 2021 I came back with more experience from my day job as a developer, and I saw Screeps as the perfect place to try out things I could not easily try at work. TypeScript replaced plain JavaScript early on.

What kept me going was simple: the deeper I went, the more complex and interesting it became. Every solved problem revealed two new “construction sites”. Energy logistics led to remote mining, remote mining led to neighbours who did not like that, neighbours led to defence, defence led to CPU problems. The autumn of 2021 was the most intense phase of that first restart — November alone saw more than fifty commits.

The quiet years

Then life happened. A professional change and a personal reorientation, and between 2022 and 2025 again a lot going on at work and at home. The bot kept running in the background with only occasional touches. Screeps is forgiving in that way: a decent bot survives a long time on autopilot. It just doesn’t get any smarter.

2026: a proper engineering setup

The real comeback in 2026 had a lot to do with AI. With it I could finally set up what a project like this deserves: an automatic build pipeline, full CI/CD, linting, and an extensive test suite — almost entirely generated, and the code quality went up massively. For the first time the bot became something I could change confidently without breaking a live world that never pauses.

Since then the history looks very different: hundreds of commits per month, more than a thousand unit tests, a private test server as a laboratory, and features I would never have dared to ship before.

What the bot is supposed to do

Today the bot runs on the persistent main world with more than twenty rooms and over five hundred creeps. Its job, roughly from the bottom up:

  1. Keep every room economically stable — energy must flow, spawns must stay full, nothing may starve.
  2. Grow — raise new rooms quickly, mine neighbouring rooms, expand into new territory.
  3. Defend — towers, ramparts, defenders, and knowing when to avoid a room entirely.
  4. Scale — trade on the market, run labs and boosts, plan buildings, remember what it has learned.

Architecturally that maps onto four layers: a thin tick shell, an empire-level orchestrator, room systems, and unit behaviour. Part 2 of this series walks through a single tick from start to finish.

Diagram of four stacked layers: tick shell, empire orchestrator, room systems and unit behaviour, each with a few keywords.
The bot in four layers, from the game loop down to a single creep.

The rules I gave myself

Over the years a few principles turned out to matter more than any single feature:

  • Autonomy first. The bot should claim, build, defend, trade and even fight without me. The 2018 flag remote control is the opposite of what I want today.
  • Never fix the game by hand. If the bot is stuck because it believes something wrong about the world, I don’t correct its memory or plant a flag. I fix the code so it detects the situation itself. Manual fixes hide the bug.
  • Measure before optimising. CPU is the scarcest resource; every new feature has to pay for itself, and the only way to know is to measure.
  • Test first, document everything. Every change gets a test; every session gets written down. A live world forgives slow code, but not a broken economy.

The moments that keep me hooked

People sometimes ask what the highlight was. Honestly: all of them.

  • My first room — watching the first spawn produce the first creep that actually did what I wrote.
  • My first lost room — painful, and the best teacher this game has.
  • The first autonomous expansion — the bot picked a room, sent a claimer and started building, without me.
  • The first lab jobs — chemistry running in the background, boosts appearing in a terminal.
  • The first market sales — my code trading with other players’ code, while I was asleep.
  • Every reset — whether I got wiped out or gave up all my rooms myself. Each restart is a clean slate, and each one showed me which parts of the bot were really robust and which only worked because the world happened to be kind.

Where I want to go

My goal is a bot that can react to anything new that comes along — new neighbours, new threats, new game mechanics — without me stepping in. That means optimising again and again, so there is always CPU left for the next feature.

The next big step is to go beyond a single shard: a bot that is present on all shards of the world, purely through its own automatic expansion.

What you can expect from this series

Roughly in the order the bot grew up:

  • How a tick is structured, and why the order of things matters.
  • The task system that turns “something should be done” into “this creep does it”.
  • Room planning, bunkers and extension crosses.
  • Creep roles, body design and the energy logistics that keep everything alive.
  • Remote mining, expansion, towers, ramparts and the minimum-cut trick for walls.
  • Markets, terminals, labs and boosts — and the industrial features that weren’t worth it.
  • CPU: profiling, a near-death spiral, and a bot that learned to throttle itself.
  • The private server as a lab, and then warfare: scouting, squads, formations, sieges and strongholds.
  • A season server, a loss, and peace.
  • The “cycle room”: turning surplus energy into control level by claiming, maxing and releasing a room over and over.
  • And finally: what I learned.

Next time: what actually happens inside a single tick?

Polaroid Workshop, by Marco / JG35

Another workshop?!

Yes, indeed. And totally worth it. It was in Vienna again, though on a different location. It was held by Marco (again) / JG35. We used the new developed films from The-Impossible-Project, again. It was awesome, again.

Little changes? Well, first and foremost, this time this article is written in english. (You should have noticed by now) Also, we sized down from 8×10″ to our old, beloved and known SX-70 and Polaroid 600* series. And well prepared we started into the workshop.

films from the-impossible-project
films from the-impossible-project

I have to admit that Macro has a gift to communicate his knowledge and you feel that he has fun in what he is doing. From the first moment you get well dragged along and fall in line with his enthusiasm.

just chillin
just chillin

 

getting situated
getting situated

smalltalk about different polaroids
smalltalk about different polaroids

 

eager to start
eager to start

For all who reached this article, I will not go into depth about polaroid cameras as you will most likely already know more about them than I do. Furthermore, I think Marco got it all covered.

So, what is left before we can go into the process of lift-offs and do cool stuff?

Oh, right, actually taking some pictures!

first contact
first contact

It's always in the details
It’s always in the details

After some time we were through with all the films and evaluated the outcome.

the shots
the shots

Finally we were itching to test the methods shown by Marco.

As hard as it looked some months ago with the 8×10″ film. I have to admit that it actually is not that hard. Given that we had someone to show us the process first and keep a steady eye on use during our experiments.

cut the film open
cut the film open

cut off borders
cut off borders

 

rinse the film before lift-off
rinse the film before lift-off

 

be careful
be careful

float the image onto the paper
float the image onto the paper

 

Looks easy, is easy … after you have done it a couple of times! It is doable and for sure it is a heck of fun! Try it, grab your Polaroid, get some film, cut it open and rinse it in warm water, then float it onto paper/glas/wood/… really … anything, you name it, you try it!

Thanks to

Marco for making this happen and guiding us through,

Brick-5 for a wonderful location for this workshop and for our exhibition,

The-Impossible-Project for reinvented the polaroid films and supplying us with them,

and well, us, the JG35 for making this workshop.

 

More photos us having fun and from the final results are shown here: