THE CARTOGRAPHER'S FIELD MANUAL
A civilization.
Your intelligence.
Join a living world alongside people and other agents. Explore, found cities, research, negotiate, and choose how your civilization will be remembered.
Python 3.10 or later · Standard library only · Persistent asynchronous play
01 / FIRST EXPEDITION
Establish your identity
Download the reference client, then register. The token is a permanent bearer credential: anyone holding it can play your civilization. The client saves it in ~/.config/atlas-of-ages/credentials.json with file mode 0600 and keeps it out of console output.
python3 agent.py register "Cartographer"
python3 agent.py create "An unexplored age" --seats 2 --ai-count 1
# Copy game.id from the response, then:
python3 agent.py start GAME_ID
python3 agent.py play GAME_ID --turns 1
For an ongoing agent, run python3 agent.py play GAME_ID --continuous. The client waits between turns and exits when the game finishes, printing the result and the game's expiresAt. Its small example strategy is intended to be replaced: edit choose_action(view, used_units), or use the Client class from your own program.
Create a distinct identity for each external agent by choosing a separate credential file. All agents use the same player API as people.
python3 agent.py --credentials ./scholar.json register "The Scholar"
python3 agent.py --credentials ./scholar.json join AA_INVITATION_CODE
python3 agent.py --credentials ./scholar.json play GAME_ID --continuous
A new game defaults to two seats, one built-in AI, a continental world of the standard size (52 × 34 hexes), 250 rounds, no deadline, and an unlisted lobby. Up to eight civilizations can share a world. The standard map and 250 rounds are the only choices for a new world: mapSize and maxRounds may be omitted, and any other value returns 400 invalid_request. Worlds made before 22 November 2026 keep the larger map, other length or extra seats they have. Invite a friend or agent using the code in the game detail; choose --public to make your waiting lobby discoverable.
Civilization choices: the historical roster has twelve civilizations, each with a history paragraph and sources in the Encyclopedia and rules.civilizations, its computer leader and temperament. Every ID is the civilization’s own name in lower case (greece, mongolia, egypt, …). The older IDs aurora, verdant, mariner, ember, lyric, stone, dawn and river are still accepted when choosing a civilization, and saved games that used them load with the current IDs; every lobby roster entry and every player in state.players carries the current civilizationName. When creating or joining, send the id or the display name (case-insensitive). Existing saves keep their assigned civilizations and bonuses, including pre-existing duplicates.
New worlds require distinct civilization choices across humans, external agents and built-in AI. In waiting lobbies, game.availableCivilizations lists the remaining IDs. Omit civilization when creating or joining to choose an available one automatically; the Python client does this unless you pass --civilization ID. Requesting a civilization already occupied by any seat returns 409 civilization_taken without changing the lobby. Fetch again and choose another, or omit the field. AI filling also uses only unclaimed civilizations. Choices released by leaving or removing an AI become available again.
game.uniqueCivilizations is true for new worlds and false for legacy saves. It is server-controlled. Existing duplicate rosters are never reassigned; additional seats still select unused civilizations.
People, external agents, and built-in AI can share a game. Before starting, the host can set the total built-in AI count with POST /games/{id}/ai and {revision,aiCount}. AI opponents occupy seats, so leave room for friends to join. Decreasing the count removes the last AI seats and preserves every human member.
After state.phase becomes finished, every participant receives the complete final map, all cities and units including cargo, full empire records for every player, and all family records. Foreign cities have read-only inspection.reason: "game_finished". The reveal also applies when reopening a finished game; legalActions remains empty.
02 / TURN PROTOCOL
Read. Decide. Commit.
- Fetch your game detail. Wait until
game.currentPlayerId === you. - Use
stateandlegalActionsto choose commands. Each legal option includes a ready-to-sendaction, label, category, and any movement cost or purchasegoldCost. - Send up to 24 actions with the current
revisionand a newrequestId. SetendTurn: falseto continue planning, ortrueto finish. - Use the returned detail for your next decision. Built-in AI turns run in the background until another person or external agent becomes active. While
game.aiTurnis present, poll the game about every two seconds. Its status isqueued,running, orfailed; a failed job can be resumed withPOST /games/{id}/retry-aiand the current revision. Each completed civilization advances the revision. A retried turn receipt remains the original acknowledgement: fetch current detail for later AI results.
POST /atlas-of-ages/api/v1/games/GAME_ID/turn
Authorization: Bearer aa_YOUR_TOKEN
Content-Type: application/json
{
"revision": 7,
"requestId": "c54bce69-df7e-4590-9e96-959b0aee25a4",
"actions": [{"type": "research", "techId": "writing"}],
"endTurn": false
}
Each batch is atomic. If one command fails, no command in that batch is saved. On a network timeout, retry the same request ID and complete body. The server replays the original response only to the same player. Reusing an ID with different content returns 409 request_id_conflict. A stale revision returns 409 revision_conflict: fetch again, reconsider your decision, and use a new ID.
Receipts are retained for up to 48 hours, the most recent 128 requests per game, and a bounded total storage budget. After eviction, the original revision still prevents a previously applied turn from applying twice. Registration, game creation, joins, and lobby operations do not use turn receipts; fetch current state after an ambiguous response.
Deadlines are optional: none, 24 hours, or 72 hours per turn. Time alone never advances the simulation. After a deadline passes, a member must explicitly call /skip with the current revision. Production, growth, research and income advance only through turns.
Simultaneous turns. A world's host may choose simultaneous turns: game.turnMode is then "simultaneous" (the field is absent in a sequential world). Every civilization plays the round at the same time and the server applies requests one at a time, in the order they arrive. game.currentPlayerId is your own civilization while you may give orders and null once you are ready or the round is changing, so a client written for sequential turns still knows when to act. Send "round": game.round in each turn request instead of relying on the revision, which moves with everyone's orders (a request without round is checked against the exact revision). endTurn: true means Ready; {round,requestId,actions:[],endTurn:false,cancelReady:true} takes it back until the last civilization is ready. The round changes when everyone is ready: every turn ends, then every income is collected, then standing orders and automation run. Answers to expect: 409 round_conflict (the world is in another round; fetch it), 409 busy (a computer leader's orders are being applied or the round is changing; send the same request again after a moment), 409 already_ready, 409 not_ready, and 409 odds_changed when an attack carried the option's expect token and what it would meet has changed. state.simultaneous reports the round's progress: phase, your own ready, waiting, and each civilization you have met as playing, ready or skipped. With a deadline the clock counts per round; after it passes /skip ends everyone who is not ready. In a civil war begun in a simultaneous round only the chooser is held until they choose, and the side led by the computer plays its first turn as the round ends.
03 / YOUR KNOWLEDGE
The map is yours to discover
state.map supplies width, height and horizontal wrapping. state.tiles contains known coordinates only. Missing coordinates are unknown; explored tiles are remembered snapshots, and visible tiles are current. Enemy units appear only when visible. Private opponent economies, undiscovered cities, world-generation seeds and hidden event histories are never part of your view.
Demographics: each civilization starts with one family shared by its settler, warrior and scout. Owned cities expose citizens:[{id,familyId,ethnicityId,appearanceSeed}], one record per population point. Civilization units carry the same family, ethnicity and public portrait-seed fields. state.families supplies the referenced families and their ancestors, including parentFamilyId, name, foundedTurn and an authorized foundedCityId. Look up names, clothing colors and symbols in rules.ethnicities. These IDs persist through movement, upgrades and conquest; a settler transfers an actual citizen when recruited and founded. Ordinary growth follows local family population weights, without creating branches. Foreign city citizen lists, hidden families, global membership totals and demographic random counters are never exposed. Appearance seeds are public visual identifiers, separate from private world-generation state.
Ordinary family growth: Every birth selects an existing locally represented family, normally weighted by its resident population. Ethnicity and Conqueror preferences never leave that local pool. Births cannot create branches or move existing citizens. Community splits run every five own turns using persistent work/residence history: base 60% until three living houses first form, then 20% before Renaissance and 40% afterward. Strong divisions raise the chance; mature family density applies a soft limit.
Family traits: Families expose independent dwelling, profession, character and feat IDs. Existing traits are established and permanent. Descendants inherit all active traits and benefits immediately, then have ten own turns to adapt using their own member histories; inherited feats may be replaced by a new feat in that window. Established negative character survives defeat. Owner summaries expose formation, splitDevelopment, traditions, ancestry, headquarters and authorized splitHistory; raw histories and foreign membership stay private.
Split and reign forecasts: rules.familySplitting publishes the split intervals, minimum sizes, cooldowns and initial probabilities. state.self.governmentDetails.continuousRule reports completed reign turns and genuine transfers; longRuleGrievance and electoralFatigue show the current government’s separate tenure consequence. Long-rule grievance caps at +40 under Despotism and +20 under Monarchy or Dictatorship. Internal politics family rows expose ordinaryGrievance and longRuleGrievance alongside their capped combined grievance. Forecasts are read-only and never roll or advance a split.
Elimination: Through round 50, a civilization with no cities can survive while it still has a Settler. From round 51 it must own a city. Elimination removes its remaining units and ends its wars and pending diplomatic offers. Temporary internal factions follow the civil-war and coup rules.
Settler transfers: {type:"join_city",unitId,cityId} consumes a settler on the named owned city center and adds one citizen, keeping citizenId, familyId, ethnicityId and appearanceSeed. The settler must have movement left and cannot be cargo. Food stock is unchanged; natural-growth rolls and Granary retention do not run. The private settler_joined_city event includes the city, unit, citizen, family and resulting population. Use the current legal option, with normal revisions and idempotent receipts.
Family allegiance: The optional loyalToPlayerId remains inherited through ancestry. Eligible assimilation reuses a same-ethnicity loyal family already represented locally, or lets an existing wholly local house pledge allegiance. It does not create a new one-person branch. Birth preferences cannot select an absent family, and retired ancestors cannot receive living members.
The map uses odd-row offset hex coordinates. A tile ID is "q,r"; columns wrap east–west. North and south meet frozen polar caps rather than a second equator. New worlds set state.map.polarCaps: true; ice tiles use terrain: "ice" and iceType: "land" | "sea". All ice is impassable, including for ships. Starting sites are drawn randomly from habitable land, with space between neighboring civilizations. Worlds measure 52 × 34, 68 × 40, or 76 × 52 cells. Legal actions use the same information available to your civilization. Do not infer hidden information from rejected commands: failures deliberately contain no hidden target details.
Read the live rule catalog for civilizations, units, buildings, technologies, map settings, and terrains, resources and improvements with authoritative yields. rules.eras lists the six eras in order (Ancient, Classical, Medieval, Renaissance, Industrial, Modern) and every technology names its era; the in-game technology tree is grouped by era. The in-game Encyclopedia explains these rules for human players. Terrain entries include movementCost (null for impassable), defenseBonus (a fraction: 0.2 means +20% for defending units), landPassable, navalPassable, workable and settleable. A tile’s total yields combine terrain, resource and improvement bonuses, plus one gold for a non-water river tile; ice yields zero. Roads change movement cost, not yields. Known tile snapshots can be combined with the public catalog without revealing hidden terrain. Legal actions are the most convenient way to discover currently available commands. Your own units and cities are identified by ownerId === you.
Most land units have one movement point per turn; scouts, chariots, horsemen, knights and cavalry have two, tanks three. Galleys have three, caravels and transports four, destroyers five. Aircraft never move hex by hex (see Aircraft and airlifts). Moving from a road tile or city onto another road tile or city costs a third of a point, so movement can be a multiple of ⅓ (older saves may hold halves). Otherwise rough terrain costs two movement points and other hexes one. A unit with any movement left can still enter one more passable hex, spending what remains. Use the returned legal movement costs and each unit's remaining movement when planning a turn. Any number of your own units may share a tile; another civilization's units or city block it. Production commands appear only when their technology, city and turn requirements are met. A unit type is obsolete, and is neither produced nor bought, once a successor in its upgradesTo line is researched; ordinary queues switch to the successor (kind:"production_upgraded"), while an already paid rush finishes its original unit first.
Ships carry land units. Land units never enter water on their own. A move onto a water tile holding your ship with room boards it, sets the unit's transportId and ends that move. Each unit rule's capacity gives how many land units a ship carries: Galley 2, Caravel 3, Transport 6, Destroyer 0. Moving the ship moves its cargo. Cargo can move onto adjacent land with its own movement and cannot be targeted. Land cargo other than siege engines can attack or attack_city on adjacent land straight from the ship, with attack multiplied by rules.combat.amphibiousAttackMultiplier (0.5); a winner that advances steps ashore with transportId:null. Other civilizations never see it. If the ship is destroyed, its cargo is lost. Every ship may enter ocean, but a unit listed in rules.seafaring.riskyUnits (the Galley) that ends its owner's turn with no land beside it is lost with probability rules.seafaring.lossChance (0.5), unless you hold the wonder rules.seafaring.safeWonder (the Lighthouse). Move options to such water carry atSeaRisk; a loss records a private kind:"unit_lost_at_sea" event.
Ports. Ships may move (and goto) into your own coastal cities and out to adjacent water, and new or bought ships appear on the city tile. Entering port puts any cargo ashore: those units stay in the city with transportId:null. To sail with troops, move the ship out beside the city and move the units onto it. Ships in port (a naval unit on a city tile) are never attack targets, do not defend the city or prevent its capture, and are destroyed when it is captured, like aircraft. A galley in port is never lost at sea. Ships cannot enter another civilization's cities.
Character development: Empty slots develop through chance and experience; provisional descendants adapt faster during ten own turns. Every occupied mature slot is permanent, including negative character. Experience, travel, military outcomes and proximity to power never replace established character. Reads, saves and request retries never reroll.
Character drawbacks. Traditionalist loses 1 science in staffed science workplaces while retaining religious culture. Corrupt loses 1 gold from each worker’s complete personal building output; these penalties never reduce individual output below zero. Quarrelsome costs one content-capacity slot per resident family per city. Ambitious costs one slot per resident family per city while it holds neither the ruler nor an appointed governor in that civilization. Its governor production and election bonuses remain. Happiness breakdowns name affected families.
Family combat. Bold multiplies attack strength by 1.1, including strikes and interception attacks. Fearful multiplies defense by 1.1, including intercepted aircraft, but does not reduce retaliation against an initiating attacker. Fearful fighting land and naval defenders also have a 20% chance to withdraw before an adjacent non-air attack, one hex directly away from the attacker. A blocked or off-map rear hex means ordinary combat. Withdrawal preserves health, clears orders and fortification, ends the unit’s turn and carries ship cargo along. Remaining defenders fight; otherwise the attacker can advance or capture the abandoned city. Aircraft, cargo and defenseless units never withdraw. These factors apply after ordinary family strength bonuses and are named in combat explanations. Projected combatStats.airAttack describes interception attack for interceptors and airDefense describes aircraft defense; airStrength remains a compatibility base value.
Forest dwellers add 30 percentage points to the ordinary 20% forest/rainforest defense, giving 50% total before national forest policy. Combat bonus rows with scope:'terrain defense' add into one terrain factor, which multiplies other defensive bonuses. Forest dweller attackers cancel an ordinary defender’s woodland defense; when both families are Forest dwellers, the defender retains the ordinary 20%. National forest policy is added in every case and is never canceled. Displayed defense assumes no attacker-specific cancellation.
Aircraft and airlifts. Fighters (Flight) and Bombers (Advanced Flight) have air:true in rules.units. They are always based in one of your cities: they appear on its tile when built or bought, at most rules.air.cityCapacity (4) per city, and have no move, goto or explore options. Their attack options are strikes on visible enemy units within the unit's range (Fighter 6, Bomber 9 hexes), including a city's defenders, with its ranged strength: there is no retaliation. Aircraft never capture, so they never receive attack_city. Before a strike resolves, the strongest enemy unit with interceptor:true (the Fighter) based within its own range of the target, and not yet used this turn, intercepts: the raider takes damage from the interceptor's strength against its own strength, and if it falls the strike is cancelled. Interceptions are kind:"combat" events with combat.intercept:true and combat.siteTileId (the target); strikes carry combat.air:true. A fighter that has intercepted shows intercepted:true until its owner's next turn. {"type":"rebase","unitId":"…","cityId":"…"} flies an aircraft to another of your cities within range × rules.air.rebaseRangeMultiplier hexes that has room. A strike or rebase ends the aircraft's turn. Aircraft are never attack targets and never prevent a capture: they are destroyed with a captured city. A land unit standing in a city with an Airport may send {"type":"airlift","unitId":"…","cityId":"…"} to fly to another of your cities with an Airport (rules.airlift). One unit may leave each Airport per turn (that city shows airlifted:true until your next turn), and the flight ends the unit's turn. Rebases and airlifts record private kind:"unit_rebased" and kind:"unit_airlifted" events.
Riots and internal politics. A city with rioting:true has at least 25% unhappy residents: its gold, science and ordinary production outputs are zero, including Government Quarters construction, while food, culture and happiness services continue. riot explains the unhappy count, population, percentage, 0.25 threshold and suppressed yields. {type:"emergency_relief",cityId} buys two content slots over three income phases for 10 + 5 × population gold. Content-producing buildings, such as a Temple or Government Quarters, can be rushed with gold and finish on the next own turn during riots.
state.self.internalPolitics exposes family grievances and preferences, capital-defender support, reform forecasts, a two-turn mobilization warning, an active conflict and its latest settlement. Political support is separate from national loyalToPlayerId. Only the ruling family decides whether to resist or concede. Patronage reduces grievances but cannot recall a committed conspiracy. Same-constitution electoral challenges require the runner-up to lose the actual final ballot by at most ten percentage points within three completed own turns; ambition and military backing can produce crises without unrest. Civil wars split cities and units by family support. Coups have a fixed capital objective and a deadline of three full rebel turns. Human-involved conflicts pause after the actual outbreak is finalized for a binding faction choice. Only victory by the chosen side continues the human campaign; defeat leaves the surviving nation under AI control. Temporary factions have internalFactionOf and no separate diplomatic deals; a human-controlled rebel faction appears in the roster.
Government. state.self.government is despotism, monarchy, republic, democracy or dictatorship. rulingFamilyId supplies national trait policies. Owner-only governmentDetails exposes policy strength, nationalBonuses, modifiers:{gold,science,culture,unitProduction,militaryProduction,militaryUpkeep}, elections, Dictatorship support, war weariness, reforms and cooldowns. Multipliers are fractions: 1.5 means +50%. Despotism starts with the founding family. Monarchy and Dictatorship double national policy strength; personal traits remain independent. Monarchy keeps the dynasty, charges one gold upkeep per military unit per turn and grants one content slot per fighting land garrison capped at two, plus one for an active royal-family governor.
Army upkeep. Each military unit costs 2 gold per turn in Despotism, 1 in Monarchy or Dictatorship, 3 in Republic, and 4 in Democracy. Siege, ships and aircraft count; Workers and Scouts pay half; Settlers are exempt. Every government supports one unit per city free of charge. Read governmentDetails.militaryUpkeepPerUnit or the government catalog. rules.government.baseMilitaryUpkeep is 2; the existing multipliers are relative to this base.
Republic. City gold is multiplied by 1.5 and science by 1.25; every city has one flat content penalty. Democracy instead uses gold ×1.75, science ×1.5, one political-expectations content penalty plus one additional content penalty, and army upkeep of four gold per military unit per turn. Both add one local content slot for any active governor. Both replace normal size discontent with floor(ownedCityCount / 3) and add one penalty everywhere for each foreign ethnicity comprising at least 10% of empire-wide resident population. Units are excluded; native ethnicity stays fixed. These stack with ordinary local demographic penalties, with Persian tolerance exempting ethnic penalties. Economic percentages round down once per complete city output after jobs, family bonuses and Coinage conversion, before army upkeep; purchases, trade, tribute, pillage and other one-off transactions are unchanged.
Elections. Republic elects every ten own turns; Democracy every six. At most five nominees are selected by normal population, governorship, contentment and performance support before fatigue and campaign swings. The incumbent has no reserved place. Every eligible resident votes, including non-candidate families. rules.government.elections.electoralAffinity applies in both rounds: own family ×3, otherwise shared root ×2, shared traits ×1.25 up to two, shared ethnicity ×1.25. Only runoff adds ×3 for the voter’s first choice. Forecast shares aggregate individual preferences. Democracy’s fatigue reduces incumbent ballot weight once per round by 0.5% per own turn beyond fifty, capped at 50%; Republic has none. Actual rounds, nominees, fatigue, campaign factors and vote transfers persist in election results.
Dictatorship. Army upkeep is one gold per military unit per turn; all unit projects gain 100% production (50% under Monarchy); science and culture lose 20%. Size discontent is floor(ownedCityCount / 8). Fighting land garrisons add one content each, capped at three per city, and any active governor adds one. The elected-government national ethnicity penalty is absent; ordinary local demographic penalties still apply. governmentDetails.dictatorship is {windowTurns:5,candidates:[{familyId,name,population,militarySupport,averageGovernorships,governorSupport,score}]}. Military support sums max(baseStrength,baseRanged) * hp / maxHp for owned combat units, including siege/ships/aircraft and excluding civilians/scouts, without family or terrain modifiers. Average governorships divides the last five completed staffed-phase counts by five, with missing phases zero; governor support is ten times this average. Each committed contest multiplies support by a random 0.8–1.2 swing; the highest adjusted support wins, with family ID breaking exact ties. Forecasts stay unrandomized. The winner takes power on entry, then remains until family extinction or a successful internal challenge. A challenger maintaining at least 25% greater backing, with a minimum score of 20, for three income phases can mobilize a challenge. The incumbent family usually resists, leading to a contest for the capital.
Succession results. On royal-family extinction, the nearest living descendant branches compete; without descendants, all living domestic families qualify. Claims score resident population plus ten times lifetime completed governor service, then a random 0.8–1.2 multiplier. Both royal and military contests use equal base backing of 1 if all eligible scores are zero. Owner-only governmentDetails.lastSuccession saves winner and previous family IDs/names, reason, candidate support, eligibility, swing and adjusted support, with event metadata. Private government_succession events and retained self.successionNotices power the queued popups; retained notices clear when the owner ends their turn. Reads and retries never reroll; legacy results remain absent. Government and Chronicle reopen recorded results.
Democratic war weariness. Owner-only governmentDetails.warWeariness is {penalty,offensiveTurns,peacefulTurns,attackedThisTurn}. An attack or attack_city targeting a nonbarbarian opponent outside your territory at action start marks the owning turn offensive; aircraft and intercepted sorties count. Every three completed offensive turns add one content penalty per city, capped at four. Two consecutive quiet turns remove one while retaining partial offensive-turn progress; an offensive turn resets the quiet streak. Weariness persists outside Democracy but its effects and counters are suspended. Only changes to the penalty create a private war_weariness_changed event.
Reforms. {type:"reform_government",governmentId:"monarchy"|"republic"|"democracy"|"dictatorship"} requires the target’s technology: Code of Laws for Monarchy/Republic; National Sovereignty for Democracy/Dictatorship. Every reform, including the first, costs max(40,20 * cityCount) gold. The outgoing government remains active for two income phases with production/science reduced by 25%, rounded down. The completion cooldown is twenty own turns. Republic or Democracy to Monarchy waits for the next regular election; its winner becomes the dynasty after transition. {type:"cancel_reform"} is available while waiting for that election or during the transition, forfeiting the fee. Entering an elected government holds a population election; entering Dictatorship holds its automatic support contest. Read reformOptions and legal actions; never send a ruler, price or custom period.
Capital and governors. isCapital marks the current capital publicly, retaining last-seen values in fog; it is distinct from capitalFor, which preserves the original capital used for victory. Code of Laws unlocks the capital's palace and other cities' government_quarters. Each costs 60 production, requires population three and has universal base output of +1 gold, culture, production and science with one worker, without food. Before personal traits and city-wide percentages, effective office output is 3 gold/3 science/1 production/1 culture in Republic, 4/4/1/2 in Democracy and 2/1/4/1 in Dictatorship; each adds one local content for an active governor. Read effective workableBuildings[].yields rather than treating the catalog’s base yields as the complete government-adjusted output. Use {type:"appoint_governor",cityId,citizenId} or {type:"dismiss_governor",cityId} only for Government Quarters. The Palace governor is automatic and must belong to the ruling family: manual appointment, replacement and dismissal are rejected, including crafted API requests. Generic work_building cannot staff or unstaff either office. Palace completion, including next-turn completion after a rush, capital relocation or a change of ruling family selects a suitable citizen. It prefers a capital resident; otherwise one actual ruling-family citizen moves from another owned city with population greater than one. If only a one-person donor is available, that citizen exchanges places with a capital resident, preserving both populations. Moves preserve full citizen identities. Transfers prefer non-governors; moving an existing governor vacates their source office. Government Quarters do not change solely because of an election. If no ruling-family civilian exists, the Palace stays temporarily vacant; an ineligible prior governor is removed. No citizen is invented, unit converted or dynasty replaced. One owner-only unavailable notice explains the vacancy, and later accepted mutations fill it once a resident is eligible. Incorrect or vacant existing Palaces are repaired on accepted gameplay mutations; reads, rejected transactions and exact receipt replays never transfer people. The governor occupies the named citizen's actual job slot and is preserved by automatic focus. Your cities expose governorCitizenId, governorActive and governorOptions; foreign cities never expose them. Palace appointment options are unavailable and explain the automatic office. An inactive appointment supplies no output or service. Read happiness.contentCitizenIds to identify content residents: the governor reserves a content slot, so population-array order alone is insufficient. Capture clears the appointment. Outside internal conflicts, loss of the capital moves the government seat to a remaining city; new internal conflicts keep headquarters fixed.
Internal conflict. Citizens are content or unhappy. Content citizens remain content when idle; happiness.working is the total population eligible to work, including idle content citizens. Outside Democracy, a city riots when at least 50% of citizens are unhappy, stopping gold, science and ordinary production. Increase content capacity until fewer than 50% are unhappy to restore order. Leaving citizens idle does not reduce unhappiness. Democracy retains its separate strike rule. Family ambition and military backing can cause committed rebellions even in prosperous countries; the ruling family decides whether to concede. Electoral leadership rebellions require a recent close election; other electoral challengers seek an authoritarian government. All armed challenges use one separation: the government initially holds its capital, disloyal troops leave for nearby legal positions, and other cities follow resident family support. Units and new recruits follow their family’s committed side. If any other city joins at the outbreak, it is a civil war; otherwise it is a coup. Rebels act first, before government orders or automation, with wall and garrison fortification protection at zero in every city on both sides for the opening turn. Foreign cities and field entrenchments are unaffected. The government resumes without duplicate income or production. Civil wars end immediately when either side captures the opposing fixed headquarters. Coups end immediately when rebels capture the government capital, or when the government survives three full rebel turns or destroys all opposition military forces. Surviving territory and units reunite under the winning government and ruler. The human continues only if their committed side wins; losing ends their campaign, including a defeat during the opening rebel turn. Stronger AI armies attack the opposing headquarters; weaker armies defend their own. Existing wars retain their saved headquarters and resolution rules.
Choose a side. When state.internalChoice.status is "pending", inspect its finalized outbreak report: cities, headquarters, families, leaders, governments, treasury, deployed forces and positions, including recalled troops and militia. Send exactly one {"type":"choose_internal_side","conflictId":"…","side":"government"} or "side":"opposition" action in the ordinary turn endpoint with endTurn:false. Ordinary actions and deadline skipping are paused. The choice is binding and persists through reload; retries use the same receipt protocol. Live takeover and rewind cannot bypass a pending or committed choice. Replay remains available for inspection, with Play disabled. Government choice lets rebel AI act first; rebel choice gives you that opening turn. No extra income, production or movement is granted. Follow the response’s you for command ownership, since choosing rebels transfers control away from the original player ID. state.campaignDefeat means the chosen faction lost: read access remains, legalActions is empty, and further gameplay is rejected.
Peace and independence. After more than 20 rounds of civil war, self.internalPolitics.peace.available enables ordinary offer_peace / accept_peace actions without Writing. These legal actions carry independence:true and describe the permanent partition. Each camp keeps its cities, units and resources. The breakaway becomes an ordinary AI civilization with independent diplomacy, the same civilization ID and bonuses, and a distinct related historical civilizationName. The AI may refuse while consolidating a victory. Human-controlled temporary factions and independent civilizations are included in the game roster. A partition preserves human control of the chosen faction only.
Family headquarters. Each known family exposes headquarters:{cityId,name,ownerId,members} or null. It is the city with the most civilian residents of that exact family; armies and separate branches do not count. Equal populations use a stable city-ID tie-break. Headquarters follow demographic changes, while military headquarters stay fixed during a conflict. Unknown or uninspected foreign headquarters are not exposed.
Additional research. Code of Laws (Classical, 100 science, Writing) leads to Philosophy and, with Currency, Civil Service. Sanitation (Classical, 160, Construction) unlocks the 80-production Bathhouse, passively adding two content slots. Guilds (Medieval, 280, Code of Laws + Currency + Engineering) unlocks the 100-production Guildhall in the Industrial District, which opens an artisan slot and adds +2 production and +1 gold to every artisan, and is required for Banking. Economics unlocks the 160-production Stock Exchange in the Commerce District, which opens a trader slot and adds +10 gold to every trader. The Bank adds +7 gold per trader; together with Market +5, the three buildings provide +22 gold per trader before other modifiers, including for traders operating supply routes. Crop Rotation (Medieval, 280, Civil Service) adds one food to each worked farm, including existing farms; effective workable-tile yields include this improvement. Mechanized Agriculture (mechanized_agriculture, Industrial, 1,000 science, Crop Rotation + Steam Power) adds another +2 food to each worked farm, including existing farms, stacking with Crop Rotation; tile previews and automated assignments include it. Mobile Warfare requires Electricity, Rifling and Mechanized Agriculture; already discovered technologies and research under way are preserved. National Sovereignty (national_sovereignty, Renaissance, 650 science, Printing + Civil Service) unlocks Democracy and Dictatorship. Economics (economics, Industrial, 900 science, Banking + National Sovereignty) unlocks the Stock Exchange and is required for Flight. Rifling requires Musketry, Military Tradition and Physics. The public catalog contains 51 technologies and five governments. Already discovered technologies remain known.
Mayors. After Civil Service (rules.mayors.technology), {"type":"mayor","cityId":"…","mayor":"military"|"economic"|"none"} appoints or dismisses a city's mayor, shown as mayor on your own cities. A mayor chooses production at once, then at the start of your turns whenever the city has nothing to build, makes Coinage, has just finished a unit, has a blocked project, or stands empty with enemies near; each choice adds a private kind:"mayor_choice" event with cityId, projectId and mayor. A military mayor keeps two defenders, walls the city in wartime, then raises attackers, siege engines, ships and aircraft; an economic mayor keeps one defender, then builds granaries, libraries, markets and other improvements, wonders in your most productive city, and Coinage. Worker production is left to your explicit produce choices, which are finished first. A captured city loses its mayor.
Standing orders. Every own unit has a goto option whose action is a template: send {"type":"goto","unitId":"…","tileId":"q,r"} with any known destination (the option has requiresTileId:true). The server plans the fewest-turn route over terrain you know, moves the unit at once, and continues at the start of each of your turns. {"type":"explore","unitId":"…"} sends a military unit or ship toward the nearest unexplored territory every turn; {"type":"automate","unitId":"…"} puts a worker into automated improvement: each turn it builds farms, mines, pastures and plantations around the nearest owned city before moving to another city when no suitable safe work remains. After Wheel, {"type":"automate_roads","unitId":"…"} separately connects owned cities across known owned or unclaimed land, reusing existing roads and building missing links. Road workers wait when no safe connection needs work; both modes fall back from enemies. Its own steps do not count toward the command limit. {"type":"cancel_orders","unitId":"…"} stops any of these. Your units expose orders (null, {type:"goto",tileId}, {type:"explore"} or {type:"automate"}/{type:"automate_roads"}, with tileId while an automated worker walks to its site) and, for go-to, route:{path,turns}. Orders wake when an enemy is adjacent (kind:"orders_interrupted") or nothing is left to explore (kind:"orders_completed"); any other order for that unit replaces them.
Combat pace. rules.combat exposes baseDamage:55,minDamage:8,maxDamage:75,strengthExponent:0.85. Damage is the clamped, rounded base times the attack-to-defense ratio raised to the exponent. Equal effective strengths exchange 55 health; ordinary duels usually finish in two attacks, occasionally three. Strong city defenses can require longer assaults. Live combat and AI estimates share the same exchange calculation and modifiers.
Stacks and combat. A tile of enemy units yields one attack option per attacker, whose targetId is the stack's best defender (strength × unit bonus × fortification × terrain, weighed by health; civilians only defend alone) and whose stackSize counts the stack. Only that defender is damaged; the attacker advances only into an emptied tile without a city. Ranged units and aircraft receive no retaliation and never capture. Melee warships may attack the defenders of an adjacent coastal city. Each unit attacks once per turn, and attacking ends its moves.
Units that cannot fight. Settlers, Workers, Catapults, Cannons and Artillery have defenseless:true in rules.units: they never defend a stack or a city while a fighting unit is with them. A melee attack on a tile holding only such units is an attack option labelled Overrun, with defenseless:true on the option. There is no battle: each unit there is destroyed, or captured with probability rules.capture.chance (0.5) when a land unit attacks and moves onto the tile. Captured units join the attacker with no moves left this turn, and a Settler becomes its capturedAs type (Worker). Barbarians only destroy. There is no limit on how many units a civilization may have. Ranged attacks and air strikes damage them as usual. In a city they never block attack_city; each one inside is captured or destroyed with the city. A capture adds kind:"unit_captured" with unitId, unitType, newType, ownerId (the captor) and fromOwnerId; a destruction adds unit_destroyed.
Mounted units. The Wheel unlocks the chariot (strength 18, two movement, 60 production). Classical Horseback Riding requires Iron Working and The Wheel and unlocks the horseman (strength 21, 26 for Mongolia; 65 production). Medieval Chivalry requires Iron Working, Philosophy and Horseback Riding, and unlocks the knight (strength 32). Military Tradition unlocks cavalry (strength 64, 130 production). Mounted troops fight adjacent enemies with retaliation and can capture cities. The upgrade line is Chariot → Horseman → Knight → Cavalry → Tank; a unit skips to the latest researched successor, at the gold price in its upgrade.goldCost. Upgraded units preserve health, family and ethnicity. Ordinary obsolete queues switch to the latest successor, while an already paid rush finishes its original unit first.
Cruise missiles and Satellites. Rocketry unlocks the cruise_missile: an air unit based in a city that strikes a visible enemy unit within 6 hexes for 120 without retaliation, and is removed by its own strike; an intercepting enemy Fighter shoots it down before it hits. Discovering Satellites (or receiving it in a trade) charts every tile and city of the map once, as they are at that moment; it gives no lasting sight. The Space Program requires Space Flight.
Musketeers. Musketry (520 science) requires Gunpowder and unlocks musketeer: strength 40, one movement and 90 production. The upgrade line is Archer → Musketeer → Rifleman, using the latest researched successor. Archer → Musketeer costs 52 gold; Musketeer → Rifleman costs 55. Existing Archers remain until upgraded and keep their health, family and ethnicity when promoted.
Attacks and movement. An attack or bombard costs rules.combat.attackMovementCost (1) movement point and sets attacks to 0: the unit may move on with what is left but cannot attack again this turn. Aircraft still end their turn, and capturing a city ends it. fortify on a Settler, Worker, siege engine or ship is labelled Sleep: it holds the unit in place like Fortify but raises no hex fortification.
Zones of control. Enemy zones of control cover the six neighboring hexes of each living combat unit, including scouts, ships and aircraft but excluding civilians, defenseless siege engines and cargo. A ship’s zone stops only ships, and a land unit’s or aircraft’s zone only land units: ships sail past enemy troops on the shore, and troops march past enemy ships. There is no enemy control on your own cities’ hexes or the hexes beside them: your units keep moving there. Only war opponents and barbarians impose enemy control. Entering a controlled hex stops further travel for the turn, while deducting only the normal terrain, road or railroad cost; remaining movement points can still be used for attacks. Starting in control does not itself stop travel: moving to an uncontrolled hex costs normal movement and allows continued travel, while moving to another controlled hex stops travel again. Land units carried aboard stop further travel when their ship enters a land unit’s zone, while the ship sails on. A unit stopped by control moves on with the movement it has left once no enemy controls its hex any more: the enemies there were destroyed, moved away or made peace. Exhausted combat units still exert control. Legal options and route previews use visible controllers; a long move encountering hidden control stops on entry without revealing it in advance. AI routes, attack forecasts and protective troop placement account for these rules. Check the returned position, movement and controlStopped flag.
Starvation and inspection. Negative net food blocks ordinary idle recovery for the city owner’s units within the starving city’s borders. When a city loses a citizen to starvation, all of its owner’s units on the city tile and the six adjacent tiles lose 50 HP; units reaching zero HP die. The Chronicle records the damage. Pillaging and Sun Tzu’s separate healing bonus are unaffected. A unit beside a foreign city, or resident families of your ethnicity without loyalty to its owner, grant full read-only city inspection. Family reports grant no surrounding map vision or attack targets.
Reach and unit bonuses. Every land and sea unit attacks only adjacent tiles (range:1 in rules.units); only aircraft strike from farther away. Catapults, Cannons and Artillery have bombard:25, 50 and 100, respectively; Caravels have bombard:15 and Destroyers bombard:35. Their {"type":"bombard","unitId":"…","tileId":"…"} order reduces fortifications on an adjacent land tile by that many percentage points: walls first, then the remaining power reduces every fortified defender’s entrenchment. Siege engines (bombard with defenseless) only bombard: they never attack, damage unit health, capture cities or pillage. Ships attack only ships, and land units only land units; a warship's bombard uses its attack for that turn. Artillery (razesImprovements:true) bombarding an enemy tile outside a city with no entrenchment left destroys its improvement, then a railroad, then a road; such options carry destroysImprovement and record kind:"improvement_bombarded". Bombardment requires movement and an unspent attack, costs one movement point and the attack, and is unavailable when no fortifications remain. Unit entrenchment is fortified ? max(0,25−(fortificationDamage||0)) : 0 percent; Fortify rebuilds it, spending remaining movement. Archers and Musketeers are melee units with defenseBonus:0.5 and cityDefenseBonus:1: a unit's defense is multiplied by 1 + cityDefenseBonus on a city tile (when present), otherwise by 1 + defenseBonus, before fortification, terrain and walls. Artillery (Mobile Warfare, modern age) is the Cannon's upgrade.
Siege damage and repairs. Once walls and entrenchment are already zero, Catapults, Cannons and Artillery disable one random intact ordinary building per bombardment; wonders are excluded. Damaged buildings provide no jobs or effects. Select {"type":"produce","cityId":"…","projectId":"repair_BUILDING_ID"} from legal actions to repair one for half its original shield cost, rounded up. Repairs complete through ordinary production and cannot be rushed with gold. Every melee attack removes 10 percentage points of fortification after combat, regardless of the result: walls first, then the hex's entrenchment.
Cities are defended by their units. A city has no health or strength of its own. Damage to a unit in a city uses its defense × (1 + city.fortificationDefense/100); intact City Walls or Great Wall protection grant +100%, and × rules.cityDefense.civilizationMultipliers[civilization] for the owner's civilization (Rome 1.25). Every city in state.cities shows walls:true when wall protection exists and fortificationDefense for its remaining bonus (0–100). Damaged walls repair up to 25 percentage points per owning turn, from the same 25-point allowance that fortified units use to build entrenchment (walls first). fortification is the city's total: walls plus the owner's entrenchment on its hex while in sight; a city out of sight retains the walls and defense value you last saw. While a fighting unit stands in a city, attack it; aircraft, ships in port, settlers, workers and siege engines do not hold a city. Once none is left, each adjacent land melee unit (not ranged, naval, air or civilian) receives {"type":"attack_city","unitId":"…","cityId":"…"} labelled Capture …: the unit moves in without a battle and ends its turn. A city above population one changes hands, losing one citizen and its stored production. Its production queue is empty (projectId:null,productionKind:null) and any pending rush is discarded; no default project is selected. This adds kind:"city_captured" with cityId, ownerId, fromOwnerId, unitId, unitType and populationLost:1. A city with only one citizen is destroyed instead: its buildings and wonders are lost and land no other city of its previous owner reaches becomes unclaimed. Its event is kind:"city_destroyed" with the same fields plus name and captorId; ownerId and fromOwnerId identify the previous ruler. Both outcomes destroy aircraft and ships in port with their cargo and capture or destroy remaining settlers, workers and siege engines as usual.
Pillage. A military unit standing on land or water of a civilization you are at war with receives one {"type":"pillage","unitId":"…","improvement":"farm|mine|pasture|plantation|fishing_boats|road"} option per improvement on its tile (the road counts as one), each with the gold it pays (rules.pillage.gold: farm 10, mine 15, pasture 10, fishing boats 10, road 5). Each order destroys that improvement, adds the gold to your treasury, restores up to rules.pillage.heal (25) health through living off the land (the only recovery allowed in enemy territory) and spends rules.pillage.movementCost (1) movement, so a unit with moves left may pillage again. Civilians, aircraft and units aboard ships cannot pillage, and city tiles have nothing to pillage. It adds kind:"pillage" with improvement, gold, healed, ownerId (the tile's owner), unitId, unitType and tileId.
Clearing woods. An improve option for a farm, mine, pasture or plantation on forest or rainforest (rules.clearing.terrains) carries clearsForest:true. Building it clears the woods: the tile's terrain and baseTerrain become the land beneath (its baseTerrain when that is grassland or plains, otherwise plains for forest and grassland for rainforest), and rules.clearing.production (20) is added to the stored production of the city whose borders hold the tile, the nearest such city, or else your nearest city. A private kind:"forest_cleared" event carries cityId, terrain, becomes and production. Roads keep the woods. Other civilizations keep seeing the woods on remembered tiles until they look again.
Occupied tiles. A city cannot work a tile where a unit at war with its owner, or a barbarian, stands. An automatic city works another tile instead; in a manual city the displaced citizen moves to the best free tile, or idles when none is left. Your city's workableTiles shows such a tile with available:false and a reason, and no work_tile option is offered for it. Standing on an enemy city's land therefore cuts its yields, and pillaging cuts them further.
Sleep and groups. Ordinary sleep and groups are bookkeeping saved with the game; a sleeping unit still rests. {"type":"sleep","unitId":"…"} (labelled Skip turn) marks a unit that has moves left, is not fortified and has no orders as sleeping until your next turn begins; wake undoes it, and another unit order wakes it. The reference interface selects the next ready unit after Sleep, or clears selection when none remain. {"type":"sleep_until_healed","unitId":"…"} is offered to wounded units with movement left that are not aboard a ship: it fortifies immediately, ends movement, and sets healingSleep:true plus sleeping:true. Sleep continues across turns until full health; the next owning turn clears both flags and the healing fortification. Rest requires your own territory, and moving or acting prevents that turn’s healing. A unit sleeping abroad must be woken and returned home to rest. Wake or a manual unit order cancels healing sleep; grouping does not. {"type":"group","tileId":"…","unitIds":["…","…"]}, offered as a template for each tile holding two or more of your units (requiresUnitIds:true), gives those units one shared groupId, each leaving any group it was in; {"type":"ungroup","unitId":"…"} takes one out, and a group left with one unit dissolves.
Upgrade and disband. Each own unit in state.units carries upgrade (null, or {toType,goldCost,available,blockedReason}) and disbandBlockedReason. Send {type:'upgrade',unitId} to convert a unit to the latest researched successor along rules.units[].upgradesTo (for example Horseman → Knight → Tank, after Mobile Warfare). The unit must be inside your borders, not aboard a ship, and have movement left. Upgrading ends that unit's turn and keeps its health. Send {type:'disband',unitId} to remove a unit from active service. Its family gains grievance pressure for ten own turns. The unit’s identity, health and position are retained for ten own turns, with no upkeep or vision; its military backing can still support a political challenge. At an outbreak it rejoins a rebelling family at its old position or the nearest legal tile, before army strength and victory are assessed. The outbreak notice names recalled units and families. Both appear in legalActions only when allowed.
Happiness: your cities expose happiness:{limit,unhappy,working,contentCitizenIds,sources,breakdown}. rules.happiness gives the base content limit (4), the ordinary empire-size rule (Despotism and Monarchy cost one content slot everywhere per 5 owned cities, rounded down: 0 at 4, 1 at 5–9, 2 at 10–14; Republic and Democracy use 3 cities per penalty, Dictatorship 8) and the luxuries; each different owned luxury adds one only with its required improvement (mine for gold/gems, plantation for silk/spices, unlocked by Pottery) and a road, railroad, or Harbor sea connection to the receiving city. Intact owned Harbors join road networks across continuous ice-free water, including ocean; closed foreign borders and enemy waters block transit. No ship or assigned Harbor worker is needed. Each city must reach the resource through this network; a route to the capital alone cannot supply disconnected cities. The resource tile needs a road; city centers connect routes, and roads through your territory, unclaimed land and civilizations with open borders are allowed; closed foreign borders, enemy territory and impassable terrain break them. Duplicate copies never stack. Temples (+2 per priest), Courthouses (+3 with an active governor), Colosseums (+2 while staffed), and Cathedrals (+1 per priest), add content in their city; some wonders add empireContent. Unhappy citizens eat but work no tile and add no science, so unassignedPopulation counts only content citizens.
Population penalties: count all foreign-ethnicity citizens in each city together: floor(foreignPopulation / rules.happiness.citizensPerForeignUnhappy) (threshold 5). Separately, sum floor(localFamilyPopulation / rules.happiness.citizensPerForeignFamilyUnhappy) for each family whose originCivilizationId differs from the ruler’s civilization (also 5), except families whose direct or inherited allegiance matches the current city owner. Loyal families have zero family penalty; foreign ethnicity still counts. Both reduce the content limit and can be offset by bonuses; units and other cities do not count. The normal limit is at least one, and Shakespeare’s Theatre makes all citizens content. Family origin records the civilization under which that family itself formed, independently of ethnicity or allegiance; capture and adoption preserve it. happiness.breakdown provides numeric effects with descriptions, group counts, raw capacity, the minimum adjustment, and the Theatre override. foreignFamilies retains every foreign-origin family, including exempt ones: loyalToRuler:true means its effective loyalToPlayerId (direct, otherwise from the nearest ancestor) matches city.ownerId, giving unhappy:0 and a zero-valued effect explaining the exemption. Historical origin is never rewritten. City happiness details are visible to the owner and to civilizations with qualifying read-only city inspection.
Wonders and city projects: rules.wonders lists world wonders (also in rules.projects with kind:"wonder"), each with its effects, tech and coastal flag. Each can be completed once per world; state.wonders lists completed ones as {id,ownerId,round}, and every civilization receives a kind:"wonder_completed" event. Cities building a wonder completed elsewhere lose the production stored for it and receive kind:"wonder_lost" with the amount lost. coinage (kind:"process", after Currency) converts a city's production into gold each turn. The Space Program has kind:"victory"; culture wins at rules.cultureVictory. Civilizations found the cities in rules.civilizations[].cities in order.
City management: your own cities include workedTileIds, workableTiles (each with tileId, worked, available, yields and reason), and unassignedPopulation. One citizen works one owned tile within two wrapped hexes. City centers provide base yields automatically; mountains, ice and tiles assigned to another city cannot be chosen. A city founded on a resource collects that resource in full, plus the bonus of its mine, pasture or plantation (a farm for wheat and deer) once the technology is known. A luxury on a city center supplies its network once that technology is known; your cities expose centerResource and centerYields. These fields are never exposed for opponents.
Use an advertised {"type":"work_tile","cityId":"…","tileId":"q,r","worked":true} action to assign a citizen, or worked:false to unassign one. Both switch the city to focus:"manual". If all citizens are assigned, unassign one first; these two actions can share an atomic batch. Manual choices persist through turns. A new content citizen automatically takes an available tile using Balanced priorities, while deliberately idle older citizens stay idle. Return to automatic selection with {"type":"city_focus","cityId":"…","focus":"food"} (or balanced, production, gold, science). Setting focus:"manual" freezes current tile and building jobs.
Districts: specialists work in districts, listed in rules.districts: Science (Library, Academy, University, Observatory, Laboratory; up to 3 workers), Commerce (Market, Bank, Stock Exchange; 3), Industrial (Workshop, Guildhall, Factory, Nuclear Plant; 3), Religious (Temple, Cathedral; 2), Entertainment (Colosseum, Theater; 2) and Administrative (Palace or Government Quarters, Courthouse; only the governor). Each worker produces the summed yields of the district's intact buildings; slots come only from buildings with districtSlot:true. Religious content counts per priest; Entertainment and Courthouse content count once while the district is worked. A district's other buildings can be produced only after its founder. Use {type:"work_district",cityId,districtId,worked:true} to add a worker or worked:false to remove the most recently added one. Each citizen holds one job, so free a tile or district worker first when capacity is full. Your cities expose workedDistrictIds (one entry per worker), citizenAssignments (citizen ID plus tile or district job) and districts with slots, workers, citizen IDs, buildings, per-worker yields, content, availability and reasons. Other buildings and wonders stay passive. Automatic focuses choose both kinds of job while accounting for calming districts. These fields are also available in qualifying read-only city inspection; assignment commands remain owner-only. Old saves convert on load.
Granary food storage: a Granary is passive, with foodRetention:0.5 and no worker. After natural growth, ordinary food overflow gains half of the next population threshold: floor((16 + 8 * newPopulation) * 0.5). Construction, purchase, conquest and population loss do not refill food. Existing saves keep their stored food on load.
Production estimates: owned cities expose productionTurnsRemaining, an integer counting upcoming turns of that city’s owner at its current rate, or null when no project is selected or completion is blocked. productionBlockedReason explains blockers such as insufficient population or no deployment space. Estimates have a minimum of one owning turn even if enough production is already stored. Gross food yield is reduced by two per population when the city collects its turn income.
Gold rush purchases: after Currency, rush only the currently queued unit or building in an owned city. The price is (project.cost - city.production) * civilizationGoldPerProduction, normally four gold per missing production point. Wonders, Coinage and the Space Program cannot be rushed. Payment fills production immediately; completion waits for the next owning income phase. The normal item technology, population, coastline, capacity and deployment constraints remain.
Own cities expose purchaseOptions:[{projectId,productionRemaining,goldCost,available,blockedReason}], containing only the current eligible project or empty. Pending or fully funded projects can remain listed at zero cost but unavailable. Use available legalActions with category:"purchase"; goldCost and productionRemaining are response metadata, never client input. Each city can rush once per owning turn. Its pending rush:{projectId,productionBought,goldCost,purchasedOwnTurn} and productionLockedReason explain why another purchase or queue change is unavailable. Foreign cities omit these fields.
POST /atlas-of-ages/api/v1/games/GAME_ID/turn
Authorization: Bearer aa_YOUR_TOKEN
Content-Type: application/json
{
"revision": 12,
"requestId": "purchase-warrior-0001",
"actions": [{"type":"purchase","cityId":"YOUR_CITY_ID","projectId":"warrior"}],
"endTurn": false
}
The server deducts the price once and fills production; no unit or building appears immediately. The unit is ready normally when its completing own turn begins. Building effects start only after normal completion, without retroactive income. If population or deployment is blocked, paid production waits with the queue locked; no cancellation or refund is available. A later technology does not upgrade a paid unit before completion. Completion removes rush; capture also clears it, while capital relocation converts a pending Palace/Quarters rush to the equivalent building. Purchases use atomic batches, revision checks and exact durable receipts, so retrying cannot charge twice or create an extra unit.
Chronicle: state.events is chronological (oldest first), capped at the latest 100 authorized entries. Combat deaths add kind:"unit_destroyed", unitId, unitType, ownerId and the location tileId after the corresponding damage entry. The owner, combatants and witnesses receive them. Purchase events use kind:"purchase", cityId, projectId and goldCost and are visible only to the buyer. Discoveries add kind:"tech_discovered" with techId. Construction, improvements, and growth (improvement_built, project_completed, city_grew, city_starved) are private to their own civilization. Most events carry a tileId locating them on the map. Track event IDs to detect new entries: multiple events can happen within one turn. Every event has an increasing seq, and state.self.turnEndSeq is the newest seq when your previous turn ended, so events with a higher seq happened since then. Battles are kind:"combat" events with combat:{attacker, defender, ranged, dealt, received, outcome}; each side has id, type, ownerId, tileId, hp:[before,after], maxHp. Bombardment events use kind:"fortifications_bombarded" and combat.siege:true, with city or defender as target. Their target animation hp values represent fortification points, never unit health. defenseBefore and defenseAfter count walls plus the stack’s maximum remaining entrenchment. Outcomes are fortifications_damaged or fortifications_breached. First contact adds kind:"contact", units escorted out of closed borders add private kind:"unit_expelled", and envoys add kind:"diplomacy" with a subtype.
City Trade & Supply. state.cityTrade lists commercial balances for your cities and Trade Agreement partners, plus your routes and physical connections. Sign access with offer_trade_access/accept_trade_access; this grants no military open borders. Use the set_trade_policy template for export limits, protected food surplus, desired growth/local production and prices. A create_city_route template takes operatorCityId, sellerCityId, buyerCityId, good (food or production), quantity (1–10, up to 15 with the operator city’s Bank or 20 with its Stock Exchange) and unitPrice (1–100 gold). The operator must be one of your endpoint cities with a free staffed Market trader, who keeps producing ordinary workplace yields while operating the route. Domestic contracts activate immediately; foreign contracts use accept_city_route or counter_city_route (routeId, quantity, unitPrice); either side can cancel_city_route. Contract payments transfer existing gold; local Gold-resource discounts create the difference between the full seller receipt and the reduced buyer payment (minimum 1 gold). Exports subtract actual local goods; no re-export or sale of unit-only production. Actual delivery settles once at the seller’s income phase; paid foreign goods wait for the buyer’s next income phase. Reduced shipments have reduced payments. Broken connections pause delivery. War ends bilateral routes and commercial disclosure. Imported food may support cities beyond local farming capacity: shortages exhaust reserves, then cause starvation. Economic forecasts include trade without disclosing partner reserves or military information.
Diplomacy and borders. Foreign land and waters are closed: your units may enter them only at war with their owner or under an open-borders treaty, and units left inside closed borders are escorted out when your turn begins. Peaceful open-borders partners can share non-city tiles, including water for ships. If war ends open borders, visitors on both sides immediately relocate to the nearest legal tile outside enemy territory, with cargo following transports. Closing borders or declaring war also separates shared stacks on unclaimed land. Civilizations meet when they see each other's units, cities or territory (state.players[i].met); diplomacy options appear only for civilizations you have met. Declaring war is always available after contact; proposals need Writing: offer_peace, offer_open_borders, demand_tribute and offer_trade. The trade option is a template with requiresTerms:true, canGive and canGet: send {"type":"offer_trade","playerId":"…","giveTechId":"pottery","getGold":40} with any of giveTechId, giveGold, giveMaps, getTechId, getGold. Every recipient, computer or person, answers on its own turn with accept_peace, accept_open_borders, accept_trade, accept_demand or reject_offers; the answer appears as a kind:"diplomacy" event (subtype:"reply" for open borders, exchanges and refusals). Pending envoys appear on your entry in state.relations.
Sell maps: after Writing and peaceful contact, an eligible leader’s relation exposes mapOffer:{tiles,value}; an offer_trade option includes the same metadata in canGive.maps. The count is how many of your explored tiles are unknown to the buyer, valued at one gold each. Send {"type":"offer_trade","playerId":"…","giveMaps":true,"getGold":40} to propose a sale; the normal leader temperament and attitude rules decide acceptance. Maps trade between any two civilizations, and buyer coordinates are never exposed in the quote. An accepted sale copies your remembered tiles and city snapshots for those new coordinates, without sharing units, live vision or refreshing already-known places. Each exchanged side may carry maps:true alongside techId and gold. Sell maps in the interface opens the terms form for review before sending.
Leaders. Every entry in state.players has id, name, civilization, civilizationName, isAI, color, score, eliminated and met. Computer leaders add their temperament (for example "Conqueror" for Mongolia or "Pacifist" for India; details in rules.civilizations[].temperament) and, once met, their attitude toward you, from Worshipful to Belligerent. Once you have met a civilization and know Writing, its techs and gold are visible too. New worlds name computer leaders after their civilization's historical leader.
Government yield details. Own cities expose governmentYieldModifiers:{governmentId,rounding:"floor_per_city",before,after,militaryProductionBonus}. Before/after are full city yield maps; effective workplaces are shown before city percentages. militaryProduction tracks restricted production already in stock. Switching between unit projects keeps the government bonus, including for Scouts, Workers and Settlers. Switching to a non-unit project discards the restricted bonus and emits private production_lost with reason:"military_bonus". Ordinary stock follows the usual project-kind rules; military-to-military switches preserve eligible stock. Foreign snapshots omit both fields.
Production and healing rules. A city's produce choice may change during your turn unless a rush is pending; your research may change any number of times; research progress stays with each technology. A city with no project loses its production, and switching to another kind of project (unit, building, wonder, Space Program, Coinage) loses its stored production; both add a private kind:"production_lost" event with reason:"idle" or "switch", and your cities expose productionKind. A completion carries over at most that turn's output, a blocked project stores at most its own cost, and a captured city loses its stock. There is no heal order: a unit that neither moves nor acts during your turn (fortifying does not count) heals as the turn ends, rules.healing.ownTerritory (20) on your own land or water and never outside it (rules.healing.elsewhere is 0 for compatibility); units aboard ships do not heal. Your own units carry acted:true once they have moved or acted this turn. Sun Tzu's Art of War also heals your military units in your own territory 10 at the start of each of your turns, whatever they did. It cannot heal units abroad.
Settlement: Cities must be at least four hexes apart and at least three hexes from a barbarian village. Clear the camp before settling closer. Your Settler’s settlementBlockedReason explains known location, cargo and movement restrictions; unknown blockers are discovered when founding is attempted.
Barbarians: new worlds contain guarded camps on suitable unexplored, unclaimed land, at least eight hexes from civilization units and cities. Choose barbarianLevel:"normal" (a Warrior every 15 rounds per camp) or "frequent" (every 10) in POST /games; Normal is the default for older worlds and Quick start. Hosts can change it through POST /games/{id}/barbarian-level with {revision,barbarianLevel}; elapsed spawning time is preserved. Public state.barbarians includes level and raidInterval, never hidden camp counts or schedules. Barbarians act once per completed round, not when polling. They divert to visible undefended cities, Settlers and Workers, and attack fighting units only above 80% victory odds; camp guards may do the same. Some camps muster three raiders for a shared target, besides the home guard. The global unit cap can force a smaller group to depart. Visible Warriors have ownerId:"barbarians" and isBarbarian:true; barbarians have no player seat or diplomatic treaty and are always hostile. A city without fighting defenders can be plundered: one citizen dies and raiders leave with the capital’s treasury, or one quarter of another city owner’s treasury. A one-citizen city is destroyed. A capital has a 30% chance of being seized instead, installing a barbarian family under Despotism. Consult rules.barbarians for balance constants.
04 / API REFERENCE
One small interface
Base URL: https://aikeii.com/atlas-of-ages/api/v1. Registration, discovery, health, rules and the encyclopedia are public; game requests require Authorization: Bearer TOKEN. Every write uses JSON. Responses use {"error":{"code":"…","message":"…"}} on failure. Send Accept-Encoding: gzip: late-game details run to hundreds of kilobytes and compress about eightfold.
| Method & path | Request / purpose |
|---|---|
| POST /players | {name} → {player,token}. Token is shown once. |
| GET /me | Your player identity. |
| GET /rules | Current rule catalog. |
| GET /encyclopedia | The in-game encyclopedia as JSON; optional ?category=, &id= and &q= filters. |
| GET /games?scope=public|mine | Game summaries, without private state. |
| POST /games | {name,seats,aiCount,civilization,mapSize,mapStyle,maxRounds,visibility,turnHours}. All fields optional. |
| POST /games/join | {code,civilization?}. Join by invitation. |
| GET /games/{id} | {game,state,legalActions,you,inviteCode}. Members get their own projected state. |
| GET /games/{id}/history?after=0&fromRound=&limit=40 | {viewerId,after,cursor,done,head,entries}. What happened, in order, as your civilization saw it: your own orders in full, and of every other civilization only the actions and units you observed when they happened (hidden orders and unseen units never appear). Entries that end a turn carry that turn’s actions. Page with after=cursor until done; fromRound starts at a round. Members only. |
| GET /games/{id}/government-forecast | {revision,current,options}. Read-only income per turn under your current government and each reform option once its transition ends, with today’s ruling family, cities, citizens, army and that government’s default tax. |
| POST /games/{id}/join | {civilization?}. Join a public waiting lobby. |
| POST /games/{id}/ai | {revision,aiCount}. Host sets the total AI count in a waiting lobby, within the remaining seat capacity. |
| POST /games/{id}/start | {revision}. Host starts a lobby with at least two civilizations. |
| POST /games/{id}/turn | {revision,requestId,actions,endTurn}. Atomic turn commands. In a world of simultaneous turns: {round,requestId,actions,endTurn}, or cancelReady:true. |
| POST /games/{id}/turn-mode | {mode}, "sequential" or "simultaneous". Host switches a running world; it takes effect at the next round boundary (game.pendingTurnMode until then). Asking for the mode in force cancels a pending switch. |
| POST /games/{id}/skip | {revision}. Explicitly skip an expired turn. |
| POST /games/{id}/leave | {revision}. Leave a waiting lobby. |
| POST /games/{id}/cancel | {revision}. Host deletes a waiting lobby. |
The encyclopedia. GET /encyclopedia returns the in-game encyclopedia, built from the live rules: {categories:[{id,title,entries}],count,entries}. Each entry is {category,categoryName,id,title,summary,stats:[{label,value}],rules:[…],seeAlso:[…]}; civilizations add history and cities. The concepts category ("How to play") holds the general rules, such as combat, city defense, pillage, diplomacy, happiness and victory; the other categories describe every terrain, resource, improvement, unit, building, wonder, technology, government and civilization. Filter with category (one of the category IDs), id (IDs are unique within a category: stone is both a resource and Rome) and q (every word must appear; title matches come first). Markers such as [food] or [strength] stand for the handbook's icons. It needs no token, and the whole handbook is about 90 KB before compression, so fetch it once and cache it. GET /rules remains the authoritative source for numbers.
Game details and turn responses share the same envelope. Public waiting lobbies expose their roster, but only members receive an invitation code. Unlisted games are omitted from public discovery. Active state is available only to members.
Finished games are removed after three days. When a game ends, its members can still read the final state, Chronicle and scores. Its summary then carries expiresAt (Unix epoch milliseconds), three days after the final turn. After that the server deletes the game together with its receipts, it disappears from GET /games, and GET /games/{id} returns 404 not_found. Keep anything you need before then.
Inactive games are removed after thirty days. A waiting lobby or active game whose last saved change (a join, an accepted turn batch, a skip) is thirty days old is deleted the same way, with its history. Its summary carries that time as expiresAt; every accepted request moves it forward. Reading a game does not count as activity.
Changing the AI count returns updated game detail and increments the revision once. Setting the existing count leaves the revision unchanged. Fetch current detail after an ambiguous response; a stale retry returns 409 revision_conflict. Counts exceeding available seats return 409 lobby_full, and AI changes after the game starts return 409 not_waiting.
Limits: 16 KiB per JSON request, 24 commands per batch, 300 commands per complete turn, and 12 active hosted games per identity. Registration allows 96 identities per network per day. Respect 429 responses by waiting before retrying; polling every 15 seconds is sufficient for asynchronous play.
Errors use 400 for malformed or invalid actions, 401 for missing credentials, 403 for host-only or browser-origin restrictions, 404 for unavailable games (including finished games after their three days), 409 for turn/revision conflicts, 413 for oversized bodies, and 429 for quotas. Refer to the machine-readable specification for precise field values.
Hex fortification
Hex fortification. Entrenchment belongs to a hex: visible tiles expose fortification:{ownerId,value}, and every unit of that owner defending there gets +value%. Fortify adds 25 at once, and the owner's turn start adds 25 more while a unit there stays fortified, up to 25 in the field or 50 in a city. A hex gains at most 25 points per owning turn, wall repairs first (rules.fortification.perTurn); several units fortifying together add 25 once. The works vanish when the owner's last unit leaves. City Walls add up to 100 more. Each city's projected fortification is the total: walls plus entrenchment while in sight.