Skip to content
All writing

Using Claude Code to create RTS Game Engine

I decided to check how good Claude Code 2.0 has become and used Game engine as my target problem. I was delighted that I was able to design my own version of Game and implemented it without writing any code by hand. I also convinced my Son that I am not cheating when I am talking to Coding agents and its a Valid way of getting work done.

Author
Tushar Khairnar
Published
Revised
Not revised
Length
17 min read
Cover image for Using Claude Code to create RTS Game Engine

Introduction

Recently another wave of AI Hype train was launched, this time its about Claude Code. Till now only programmers knew how good Claude Code(CC) is but now it seems lot of ai-hype crowd has learned about CC and now building the moment for it. It also possibly signals that other alternatives like Codex from OpenAI, Gemini from Google and opensource alternatives like OpenCode have gained a lot and are now comparable to CC, hence the PR game for CC. So I chose do test CC 2.0 with a multi-faceted problem and to my surprise CC did manage to produce a good output and only limitation is my imagination. This blog is 1st part of multi-post series where I am going to explore CC, how to use it to create complex games, solve complex multi-process network synchronization issues and use of coding agents to rewrite complex code for new environment.

I concluded finally - I wonder if one can train or finetune Anthropic Models on specific industry domain, we may not need SAAS and other domain specific softwares. A good Domain Expert can easily create a customized version for himself.

Recent release of Claude Cowork is definitely a step towards it.

Claude Code 2.0 Improvements

Claude's Code 2.0 has progressed so much that people are reporting it to run continuously for more than 24 hours. Even Karpathy called it "alien" - Cc has changed daily workflows for Coder so much that new process feels alien to a seasoned engineer. This Christmas holiday I tried to test it with unusual problem - Creating a strategy game. I played Age of Empires in my college days and being History nerd it always fascinated me. The dynamics of civilization, map geography, trading, multiplayer (in college we laid lan cables hidden in hostel rooms for network games) in addition to usual thrill associated with realtime strategy games. Games as ultimate Software - always fascinated me - Games need memory-hungry graphics, sounds, Networking, multi-tasking, shared state, distributed computing and had earliest application specific AI implementations and also early use of internet. I wondered what if I can create a lightweight version of AoE.

My son always said that I am cheating ie. using cc to write code for me instead me writing by hand. So this project also served a purpose - to show him how one can create something like a game using AI coding agents. He always wanted to create his own game. I can now show him he too can create Game if he can design one in his mind. In fact one the most delightful experience I had (thanks to AI) was my Son reporting bugs (like his Scout could walk over River and construct house in the River) and I am fixing them iteratively. He also identified himself that this is called Debugging - his Computer subject book has a small paragraph on Bugs in Algorithm Chapter. I realized that coding agents if used correctly can be very good way to teach computers to Kids as it can generate and build something iteratively - which Kids understand as they see it build it from scratch as opposed to trying them to learn something like MIT Scratch language which is Kiddified version of visual scripting.

Back to Vibecoding for AoE Kids edition - So started I prompting and brainstorming - My first task was to find out how can I draw large number of objects which interact with each other - The Simulation. Both chatgpt and Claude code agreed that this can be easily tackled using simple python framework like Pygame - once I specified that my main Aim is to create game to teach kids strategy both CC and Codex created decent working prototype. CC one was objectively better and my first impression was that its so eager to write code that it immediately applies knowledge it has seen during training - it re-produced AoE like simulation. Codex output was more generic and was actually objectively better output for given input prompt. I chose to continue with CC as I found it better to add complex elements incrementally. Codex was slow as it look longer to fix bugs reported.

AoE Kids Edition - Age of Builders

Following are the aspects that I want my new age-of-empires like Game to focus on 

  1. Act of economy building - so kids learn building good foundations 
  2. Build mental capacity to track multiple variables including their interdependence 
  3. Fighting which every kid would like. Along with usual strategy and gamification aspect like points, score, unlocking new game elements etc.
  4. Counters - The rock-paper-scissor analogy to military units.
  5. Series of Challenges that focus on one key aspect of Strategy - economy, military, defense

Here is my home screen for AoE Kids - I named it My Kingdom - Age of Builders. My first effort is to get Game Engine and Computer/AI algorithm correctly (which is almost 80% completed) and then it can be Kiddified ie. adding gamification aspect, Store where kids can buy exotic units etc.

Age of Builders

Below is the video capture of AI Player playing against a Passive Player ie. Observer - test rig I built to test AI Algorithm which clearly is not "intelligent" yet as below video shows. But the underlying Maths of combat and Resource mining, Map and Fog Of War, Camera System is complete.

Progress So Far

Basic framework for Free Play against Computer Player, Tutorials, Challenges, Multi-Player Network play is implemented and working to alpha level. I have also added basic Sound Effects. Whats missing is - Good graphics, AoE like Camera Projection instead of Top View of the Map and robust AI Gameplay algorithm. Once its good enough I plan to release the binary so that one can download and play locally. I may also host a free Network Server so one can also play multi-plyer over the internet connection.

Why AoE can be good way to teach Kids strategy

There are multiple reasons and I feel main reason is - its simplicity and maths. AoE version 2 is simple does not have 3d graphics and lot of effects, has just-enough sound effects that are core to the game play. Foreg. when enemy attacks you you are alerted by the specific sound. Kids are attacked to shiny bits and lot of games capture that psyche and build upon it. Even if game is educative - it leads to lot of side effects and kids essentially learn shiny graphics and animation effects is what Games are - not get in to all strategy aspect. AOE2 is simple enough that who wins fights can be explained using simple maths. Maths of Hitpoints, armors, counters and ranges. No matter how good the fight gets - Maths still rules in AOE. AOE can be great vehicle to teach - probably most important concept that human can learn - Compounding. To spawn One Villager you require 50 food but over game-life time villager generates hundreds of resources so if you can generate lot of villagers early in the game you will have steady continuous stream of resources which you can use later to build continuous army units. Booming of economy is essential to master AOE. This aspect of AOE as a strategy game can be great learning for kids.

AOE has two levels of strategy - Macro and Micro. Macro is your overall stance - do you concentrate on building economy or you want to harass your opponents constantly and score a victory by thin margin. Micro is moving units or buildings to gain small advantage. Micro strategy elements also compound over time. A plyer with good micro can overcome Maths ie. overpowering military units from opponent side to considerable extent to change the outcome of the game.

AOE makers have released version 3 and 4 as well but AOE2 still the most popular version. And I feel reason are the same. AoE2 has lot of aspects - Choosing correct civilization, building your village to "map control" strategic positions like hills and important resources and of course choosing correct military units.

Another important aspect of AOE2 Gameplay is Resilience and Defense - Building of village, Walls and Castles, Map Control. use of Military Counters. It can teach Kids real-time problem solving. It makes one think on the spot under pressure.

Choosing military units

AOE2 can often become quite involved as it not only has Rock-Paper-Scissors triangle Infantry-Calvary-Archer counters but also has siege weapons, towers, gun units etc. In AoE for Kids - I have simplified this aspect and restricted it to Rock-Paper-Scissor version only. This makes it relatable to concept kids already familiar with.

My Kids version of AoE

Below list describes final Game elements that I have selected. Some of these are approved by my son when I wanted to do age-check ie. can kids handle complexity levels

  1. I removed Civilization aspect as its quite a meta-level strategic element. I also do not want Kids to learn that Koreans and Chinese work faster and Byzantines are defensive which is wrong version of History. World history is nuanced and games or movies oversimplify it.
  2. Designed Military fights around Rock-Paper-Scissors
  3. Added Tutorials and Challenges - similar to AOE but designed specifically for Kids to engage, learn every aspect of game before playing full game
  4. Added A Companion Character with distinct personality as a guide during play. Currently it lacks Sound effects and text-to-speech ability
  5. Converted Specific Macro Strategies as AI Opponent - I am going to write a separate blog post on this part
  6. Simplified Tech-Tree into a single building - Research Center
  7. Retained foraging-farming-mining aspect along with defense ie Castle and Wall
  8. Multiple Maps and Fog Of War - Map Exploration aspect is also retained as it adds element of Unknown
  9. Added Multi-Player Game play where two kids can play against each other with different victory criteria like Destroy Opponent's Town Center, Build Castle First, Timed Match - player with greater score wins and most important of all - Hold Castle

I am kind of delighted that one can create such comprehensive version of AoE using just vibe-coding. I later had to do lot of debugging to solve multi-player networking issues but I never had to modify code by hand.

Base architecture for RTS Game

The base architecture that was suggested by both ChatGPt and CC was - Entity-Component System (ECS) Architecture. You define an Entity class and list of component system(that define their behavior and properties) that entity can have. For eg. Villager have Position on the Map.

Entity

python
class Entity:
    _next_id = 0

    def __init__(self, name: str = "entity"):
        self.id = Entity._next_id
        Entity._next_id += 1
        self.name = name
        self.components: Dict[type, Any] = {}
        self.alive = True

Component Access Methods

Method Description
add(component) Adds component, returns self for method chaining
get(component_type) Retrieves component by type or None
has(component_type) Boolean check for component existence

Once this base class is defined we can define series of Components like

text
- Position - location on the map
- Movement - speed of moving
- StateMachine - that describes Gathering Or Pursue Attack
- Carrier(for carrying resources)
- ResourceSource - source from where resources are being gathered
- DropOff - destination for dropping gathered resources
- Health - Hit Points ie. 
- Combat
- Armor
- Farm
- House

So a Villager = Position + Movement + StateMachine + Carrier + ResourceSource + Health + .....

Below is how a village is created programmatically at the start of the Simulation.

python
def create_villager(x, y, player_id=0) -> Entity:
    return (Entity("villager")
        .add(Position(x, y))
        .add(Movement(speed=VILLAGER.movement_speed))
        .add(Carrier(capacity=VILLAGER.carry_capacity))
        .add(Gatherer(gather_rate=VILLAGER.gather_rate))
        .add(MoveTarget())
        .add(Owner(player_id))
        .add(StateMachine(UnitState.IDLE))
        .add(Vision(sight_radius=FOG_OF_WAR.villager_vision))
        .add(Health(...))
        .add(Combat(...))
        .add(Armor(...))
        .add(Fleeable())
        .add(Attackable())
        .add(Renderable(...)))

State Machine

State Machine is attached to certain kinds of entities which enable them to participate in the Simulation. For eg. Villagers Gathering food or Farming. Below is one such StateMachine. Central element in StateMachines are States Defined which are as follows. Currently StateMachines are defined for villager gathering, farm management, military combat, building production, age progression, and research systems. The game uses finite state machines to control entity behavior:

  • 12 Unit States - From IDLE to DEAD
  • 7 Major Systems - Each managing specific state transitions
  • Research Bonuses - Modify state machine behavior dynamically
  • Tick-Based Updates - All systems update every game tick
python
class UnitState(Enum):
    IDLE = "idle"
    MOVING_TO_POSITION = "moving_to_position"
    MOVING_TO_TARGET = "moving_to_target"
    GATHERING = "gathering"
    MOVING_TO_DROPOFF = "moving_to_dropoff"
    DEPOSITING = "depositing"
    FARMING = "farming"
    BLOCKED = "blocked"
    ATTACKING = "attacking"
    PURSUING = "pursuing"
    FLEEING = "fleeing"
    DEAD = "dead"
  • Each unit has a StateMachine component
  • Systems transition states based on conditions
  • State determines available behaviors
  • Transitions are explicit (set in system update methods)

Lets take an example of Farming

Farm Management State Machine

Farm Status Enum
python
class FarmStatus(Enum):
    UNALLOCATED = "unallocated"  # No worker
    WORKING = "working"          # Worker assigned + has wood
    WAITING_WOOD = "waiting"     # Worker assigned but no wood
State Diagram
text
┌──────────────────────────────┐
│  Farm.status = UNALLOCATED   │
│  - No worker assigned        │
│  - Idle, no production       │
└──────────────┬───────────────┘
               │
     WorkFarmCommand executes
               │
               ▼
     Check Player Wood >= 20
               │
      ┌────────┴────────┐
     YES               NO
      │                 │
      ▼                 ▼
┌──────────────┐  ┌─────────────────┐
│   WORKING    │  │  WAITING_WOOD   │
│ - Wood avail │  │  - No wood      │
└──────┬───────┘  └────────┬────────┘
       │                   │
       │  work_progress += 1
       │
       ▼
    progress >= 50 ticks
       │
       ├─► Has wood: Consume 20 wood
       │   Generate 10 food (+bonus)
       │   Reset progress to 0
       │
       └─► No wood: Reset progress
           Return to WAITING_WOOD

World

Once you have entities we need to define how World will be defined - The World class is the central container for all game state. World needs to have methods for modification and querying current state

python
class World:
    def __init__(self):
        self.entities: Dict[int, Entity] = {}
        self.players: Dict[int, PlayerState] = {}
        self.tick = 0
        self.bounds: Optional[WorldBounds] = None
        self.terrain: Optional[TerrainGrid] = None

Entity Management Methods

Method Description
add_entity(entity) Add entity to world
remove_entity(entity_id) Mark entity dead and remove
get_entity(entity_id) Get entity by ID or None
get_all_entities() Return all living entities
get_entities_with_components(*types) Query by component

Entity Query Methods

Method Location Description
find_nearest_resource(pos, type, max_dist) Find closest resource
find_nearest_dropoff(pos, type, player_id) Find closest dropoff
get_entities_in_radius(center, radius) Spatial query
get_units_for_player(player_id) Get player's units
get_all_units_for_player(player_id) Get all player entities
get_population(player_id) Current population count
get_population_cap(player_id) Maximum population
get_scout(player_id) Get player's scout unit

Systems

To implement certain behaviors like how Villager Gathers food or how military unit pursue attacks once instructed, following systems are defined

  • Movement system
  • Gathering system
  • Farming system
  • Barracks consumption
  • Research progress
  • Combat updates
  • Projectile updates
  • Castle defense
  • Death system
  • Resource depletion

Certain systems do not affect entities but the entire world - these behaviors will use World query methods to get the data and then modify the World State including multiple entities at once.

  • Age advancement
  • Auto-aggro checks
  • Farm status updates
  • Vision/fog of war
  • Discovery detection

Ticks

Now we come to most important concepts - Ticks. Each tick is like callback where system state is calculated ie. where should be villager based on this current speed, location and its destination. If villager has reached its destination then villager's state-machine would transition to 'DropOff" behavior. Each tick state changes are calculated and applied.

Commands

One can treat World and Entities interactive with each other as autonomous simulation. In this simulation, each entity ultimately would reach terminal state in its State Machines and eventually becomes inactive. To move further Human player has to issue commands. Following are set of commands that are defined. Commands are what makes Simulation a Game ie. in-deterministic. Every Game is different due to commands issued.

Command Description
GatherCommand Assign villager to gather resource
MoveCommand Move unit to position
AttackCommand Attack target entity
CreateVillagerCommand Train new villager
PlaceBuildingCommand Construct building
StopCommand Stop current action
WorkFarmCommand Assign villager to farm
StartResearchCommand Begin research
AdvanceAgeCommand Progress to next age

Commands in Multi-player Games

Commands are used as core mechanism during Multi-player Games - each game engine starts with exactly same state and then only command are replicated. Since both sides, engine is same if commands are applied in exact same manner then both engine will arrive as the same state. This is the core algorithm behind multi-player games.

How Computer(AI) opponent is designed using commands

Commands are also how AI Computer player "plays" opposite Human player. Level of Computer player difficulty is directly related to speed and correctness of the commands generated. To create a very tough opponent, Computer player has to generate specific set of commands which builds economy correctly and then create units and raids. A "easy" level would react slowly to events like Idle/Blocked villagers and wont generate military units aggressively and become susceptible to enemy raids.

Configuration of Entities

All game parameters are centralized in data-class configurations: for eg. VillagerConfig. When a research is achieved or player advances his Age, these parameters are positively bumped up which automatically results into better units and resources.

VillagerConfig (lines 25-35)
python
@dataclass
class VillagerConfig:
    movement_speed: float = 2.0
    carry_capacity: int = 10
    gather_rate: float = 0.4
    creation_cost_food: int = 50
    collision_radius: int = 8

Renderer-Engine Interaction

The renderer maintains a reference to the game engine and reads state each frame. Note that Renderer is the ONLY Pygame specific object, rest of the code is pure python. In later blog-post we will specifically talk about this Renderer and how to build one for Web Canvas.

python
class PygameRenderer:
    def __init__(self, engine: GameEngine, ...):
        self.engine = engine
        self.camera = Camera()
        self.selected_entity_id: Optional[int] = None
        self.paused = False
        self.show_debug = debug

Responsibilities

Task Description
Entity Rendering Draw sprites at world positions
UI Overlay Resources, selection info, action buttons
Camera System Panning, zoom, world-to-screen transform
Input Handling Mouse clicks, keyboard shortcuts
Fog of War Darken unexplored areas
Building Placement Preview mode with validity checking

Render Loop

  1. Clear screen
  2. Draw terrain (with fog)
  3. Draw entities (filtered by visibility)
  4. Draw projectiles
  5. Draw selection indicators
  6. Draw UI overlays
  7. Draw debug panel (if enabled)
  8. Display frame

Conclusion

Claude Code has managed to create significant portion of Age of Empires, in fact many times I had to restrict CC to remove certain aspects and limit the functionality. What is credible is that If CC (ie. model behind cc agent) has seen the data in its training, CC can generate very complex programs with user-driven malleability ie. CC understands the domain thoroughly so much that it can create variations by correctly mapping dependencies often modifying downstream components as upstream components change. This is remarkable behavior I have observed. I wonder if one can train or fine-tune Anthropic Models on specific industry domain, we may not need SAAS and other domain specific software. A good Domain Expert can easily create a customized version for himself.