### Start local development server Source: https://github.com/arena-hero/arena-hero-doc/blob/main/README.md Install dependencies and launch the Docusaurus development server. ```bash npm ci npm start ``` -------------------------------- ### Install the Arena Hero SDK Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/skill/overview.md Install the official Python SDK via pip to support tactic script development. ```bash python -m pip install arena-hero ``` -------------------------------- ### Core state examples Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Examples of Core objects in normal and moving states. ```json { "kind": "CORE", "id": "2ea3c3dc-42b0-4b92-9754-7558bd4ff834", "controlled": true, "owner_username": "arena_hero", "position": [12, 8], "hp": 5, "shield": 4, "state": "NORMAL" } ``` ```json { "kind": "CORE", "id": "2ea3c3dc-42b0-4b92-9754-7558bd4ff834", "controlled": true, "owner_username": "arena_hero", "position": [12, 8], "hp": 5, "shield": 4, "state": "MOVING", "move_direction": "RIGHT", "move_progress": 2, "move_required_ticks": 4, "destination": [13, 8] } ``` -------------------------------- ### Install the Arena Hero Skill Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/skill/overview.md Clone the skill repository into the local Codex skills directory to enable the agent. ```bash git clone https://github.com/arena-hero/arena-hero-skill.git \ ~/.codex/skills/arena-hero ``` -------------------------------- ### Example of plan replacement behavior Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md Demonstrates how a new POST request overwrites the previous plan state entirely. ```text Unit A: MOVE Unit B: HARVEST ``` ```text Unit A: WAIT ``` -------------------------------- ### Example of a pre-command rejection Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/errors.md A request rejected before reaching the command gate. ```json { "error": "UNAUTHORIZED" } ``` -------------------------------- ### Message dispatch example Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Demonstrates how to parse and route incoming WebSocket frames based on the message type. ```js function onMessage(frame) { const message = JSON.parse(frame); if (message.type === 'tick') currentTick = message.data; else if (message.type === 'state') onState(currentTick, message.data); else if (message.type === 'received') onReceipt(message.data); } ``` -------------------------------- ### Initial command plan submission Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/command-loop.md Example of a JSON payload for submitting unit actions for a specific tick. ```json { "tick": 80, "unit_actions": { "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa": {"type": "MOVE", "direction": "UP"}, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb": {"type": "WAIT"} } } ``` -------------------------------- ### Invalid Action Examples Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md Examples of actions containing extra or invalid fields that trigger UNEXPECTED_ACTION_FIELDS validation errors. ```json {"type":"WAIT","direction":"UP"} {"type":"HARVEST","target_id":null} {"type":"MOVE","direction":"UP","expected_cell":[1,2]} {"type":"SPAWN","unit_type":"WORKER","direction":""} ``` -------------------------------- ### Example event structure Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/resolution-results.md Represents a typical event object found in the state.data.events array. ```json { "event_id": "3f360e7e-d9bd-4f48-9a51-5cf751b04075", "tick": 10583, "event_type": "UNIT_MOVE_FAILED", "reason_code": "MOVE_BLOCKED_TERRAIN", "actor_id": "9d3e4941-2816-4a39-a220-df8cd95e877d", "position": [120, 85] } ``` -------------------------------- ### Example of an invalid command rejection Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/errors.md A rejection containing specific details about why a command was invalid. ```json { "accepted": false, "error": "INVALID_COMMAND", "details": [ { "unit_id": "9d3e4941-2816-4a39-a220-df8cd95e877d", "reason": "RANGER_CANNOT_HARVEST" }, { "reason": "INVALID_UNIT_TYPE" } ] } ``` -------------------------------- ### GET /api/v1/game/ws Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Establishes a WebSocket connection to receive game updates including ticks, state, and confirmation messages. ```APIDOC ## GET /api/v1/game/ws ### Description Establishes a WebSocket connection to listen for game events. The client must provide an Authorization header. ### Method GET ### Endpoint wss://api.arenahero.io/api/v1/game/ws ### Parameters #### Headers - **Authorization** (string) - Required - Bearer ``` -------------------------------- ### GET /api/v1/leaderboard Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/overview.md Retrieve the three lifetime rankings. ```APIDOC ## GET /api/v1/leaderboard ### Description Read the three lifetime rankings from the public leaderboard. ### Method GET ### Endpoint https://api.arenahero.io/api/v1/leaderboard ``` -------------------------------- ### Replacement command plan submission Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/command-loop.md Example of a JSON payload that replaces the previous plan for the same tick, demonstrating that the server does not merge actions. ```json { "tick": 80, "unit_actions": { "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa": {"type": "MOVE", "direction": "LEFT"} } } ``` -------------------------------- ### Example of a command gate rejection Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/errors.md A rejection occurring after the command has reached the command gate. ```json { "accepted": false, "error": "TICK_MISMATCH", "tick": 10582, "current_tick": 10583 } ``` -------------------------------- ### GET /api/v1/game/ws Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Establishes a WebSocket connection to the Arena Hero game server. Agents must provide authentication via a Bearer token in the Authorization header, while web clients use secure session cookies. ```APIDOC ## GET /api/v1/game/ws ### Description Establishes a WebSocket connection to the Arena Hero game server. Non-browser agents must provide a Bearer token in the Authorization header, while web clients must provide a secure session cookie and a valid Origin header. ### Method GET ### Endpoint /api/v1/game/ws ### Parameters #### Headers - **Authorization** (string) - Required for non-browser agents - Bearer - **Upgrade** (string) - Required - Must be 'websocket' - **Connection** (string) - Required - Must be 'Upgrade' - **Origin** (string) - Required for web clients - Must match an allowed public origin ### Request Example GET /api/v1/game/ws HTTP/1.1 Host: api.arenahero.io Authorization: Bearer Upgrade: websocket Connection: Upgrade ### Response #### Error Responses - **401 (UNAUTHORIZED)** - Missing, invalid, revoked, or inactive credential. - **403 (WEBSOCKET_ORIGIN_INVALID)** - Missing, malformed, duplicated, or disallowed Origin. - **409 (PLAYER_NOT_READY)** - Server has not started a Tick for this player. - **429 (REALTIME_CONNECTION_LIMIT)** - Too many connections; wait for Retry-After header. ``` -------------------------------- ### Handling Event Types in JavaScript Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/resolution-results.md Example implementation of an event handler using a switch statement to process different event types. ```js function applyEvent(event) { switch (event.event_type) { case 'UNIT_MOVE_FAILED': markUnitBlocked(event.actor_id, event.position, event.reason_code); break; case 'CORE_SPAWN_SUCCEEDED': registerSpawn( event.target_id, event.position, event.values.unit_type, ); break; case 'SHOT_MISSED': // The protocol does not reveal why it missed. break; } } ``` -------------------------------- ### Owned Worker unit Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Example of a worker unit currently controlled by the player. ```json { "kind": "UNIT", "id": "9d3e4941-2816-4a39-a220-df8cd95e877d", "controlled": true, "position": [11, 8], "hp": 2, "unit_type": "WORKER", "cargo": 1 } ``` -------------------------------- ### GET https://api.arenahero.io/api/v1/leaderboard Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/leaderboard.md Retrieves the top 100 players for three lifetime ranking categories. This endpoint is public and does not require authentication. ```APIDOC ## GET https://api.arenahero.io/api/v1/leaderboard ### Description Retrieves the top 100 players for three lifetime ranking categories: beacon_ticks_held, damage_dealt, and core_destruction_participations. This endpoint is public and does not require authentication. ### Method GET ### Endpoint https://api.arenahero.io/api/v1/leaderboard ### Response #### Success Response (200) - **beacon_ticks_held** (array) - List of top players for beacon ticks held. - **damage_dealt** (array) - List of top players for damage dealt. - **core_destruction_participations** (array) - List of top players for core destruction participations. Each entry in the arrays contains: - **rank** (positive int64) - Competition rank. - **username** (string) - Public Arena Hero username. - **score** (positive int64) - Lifetime total for the ranking. #### Response Example { "beacon_ticks_held": [ {"rank": 1, "username": "beacon_runner", "score": 912} ], "damage_dealt": [ {"rank": 1, "username": "ranger_one", "score": 2401} ], "core_destruction_participations": [ {"rank": 1, "username": "vanguard", "score": 17} ] } ``` -------------------------------- ### Initialize client with API key Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Pass the API key directly to the client constructor. Ensure the key is loaded securely and not committed to source control. ```python game = ArenaHeroClient(api_key="your-api-key") ``` -------------------------------- ### Preview specific locale Source: https://github.com/arena-hero/arena-hero-doc/blob/main/README.md Launch the development server with the Simplified Chinese locale. ```bash npm start -- --locale zh-Hans ``` -------------------------------- ### Initialize AsyncArenaHeroClient Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Configures the asynchronous client with the same parameters as the synchronous version. ```python AsyncArenaHeroClient( *, api_key: str, base_url: str = "https://api.arenahero.io", websocket_url: str | None = None, request_timeout: float = 5.0, request_retries: int = 2, reconnect_min_delay: float = 0.25, reconnect_max_delay: float = 5.0, max_message_size: int = 2 * 1024 * 1024, ) ``` -------------------------------- ### Submit Command Plan Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Constructs a CommandPlan with unit actions and submits it to the game instance. ```python from uuid import UUID from arena_hero import CommandPlan, Direction, MoveAction plan = CommandPlan( tick=10583, unit_actions={ UUID("9d3e4941-2816-4a39-a220-df8cd95e877d"): MoveAction( direction=Direction.UP ) }, ) accepted = game.submit(plan) ``` -------------------------------- ### Run project validation and build Source: https://github.com/arena-hero/arena-hero-doc/blob/main/README.md Execute type checking, validation scripts, and the production build process. ```bash npm run typecheck npm run validate npm run build ``` -------------------------------- ### submit() Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Submits a completed plan to the game server. ```APIDOC ## submit() ### Description Submits an already-built complete plan to the server. If an idempotency_key is provided, the SDK will retry the request with the same key in case of network failure. ### Parameters - **plan** (object) - Required - The complete plan to submit. - **idempotency_key** (str) - Optional - A unique key (8-128 ASCII bytes) to ensure request idempotency. ### Returns - **Accepted** - The result of the submission. ``` -------------------------------- ### Submit plan via POST Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Use curl to send the agent plan to the command endpoint with an idempotency key. ```bash curl --request POST \ --url https://api.arenahero.io/api/v1/game/commands \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --header 'Idempotency-Key: agent-10583-plan-01' \ --data '{ "tick": 10583, "unit_actions": { "9d3e4941-2816-4a39-a220-df8cd95e877d": { "type": "MOVE", "direction": "RIGHT" } } }' ``` -------------------------------- ### Initialize ArenaHeroClient Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Configures the synchronous client with API credentials and connection parameters. ```python ArenaHeroClient( *, api_key: str, base_url: str = "https://api.arenahero.io", websocket_url: str | None = None, request_timeout: float = 5.0, request_retries: int = 2, reconnect_min_delay: float = 0.25, reconnect_max_delay: float = 5.0, max_message_size: int = 2 * 1024 * 1024, ) ``` -------------------------------- ### Construct agent plan Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md JSON structure for submitting unit and core actions for a specific tick. ```json { "tick": 10583, "unit_actions": { "9d3e4941-2816-4a39-a220-df8cd95e877d": { "type": "MOVE", "direction": "RIGHT" } }, "core_action": { "type": "SPAWN", "unit_type": "WORKER" } } ``` -------------------------------- ### Implement Recommended Retry Loop Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Use an exponential backoff strategy with jitter when reconnecting, while ensuring the process stops for 1008 close codes. ```text delay = 250ms connect if connected: delay = 250ms read until closed if close code == 1008: stop and fix the credential or client otherwise: wait random_jitter(delay) delay = min(delay × 2, 5s) ``` -------------------------------- ### Submit a command plan via HTTP POST Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md Use this request to send unit and core actions for a specific game tick. The Idempotency-Key header is required to ensure safe retries. ```http POST /api/v1/game/commands HTTP/1.1 Host: api.arenahero.io Authorization: Bearer Idempotency-Key: agent-10583-plan-01 Content-Type: application/json ``` ```json { "tick": 10583, "unit_actions": { "9d3e4941-2816-4a39-a220-df8cd95e877d": { "type": "SHOOT", "expected_cell": [120, 85] } }, "core_action": { "type": "SPAWN", "unit_type": "VANGUARD" } } ``` -------------------------------- ### Submit a plan Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Submits a completed plan to the game server, optionally using an idempotency key to handle network retries. ```python accepted = game.submit(plan, idempotency_key="agent-10583-plan-1") ``` ```python accepted = await game.submit(plan, idempotency_key="agent-10583-plan-1") ``` -------------------------------- ### POST /api/v1/game/commands Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Submits an Agent plan for a specific game tick. ```APIDOC ## POST /api/v1/game/commands ### Description Submits a plan for the current game tick. Each successful POST replaces the previous plan for that tick. ### Method POST ### Endpoint https://api.arenahero.io/api/v1/game/commands ### Parameters #### Headers - **Authorization** (string) - Required - Bearer - **Idempotency-Key** (string) - Required - Unique key for the plan #### Request Body - **tick** (integer) - Required - The tick number the plan is for - **unit_actions** (object) - Optional - Map of unit IDs to actions - **core_action** (object) - Optional - Action for the core ### Response #### Success Response (202) - The plan has been stored. ``` -------------------------------- ### game.submit(plan) Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Submits a CommandPlan containing unit and core actions to the game engine. ```APIDOC ## game.submit(plan) ### Description Submits a planned set of actions for units and the core to the game engine for processing at a specific tick. ### Parameters - **plan** (CommandPlan) - Required - An object containing the tick number and a mapping of unit UUIDs to actions, plus an optional core action. ### Response - **accepted** (Accepted) - Returns an Accepted object representing the HTTP 202 acknowledgement. ``` -------------------------------- ### Implement a synchronous game loop Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Use the ArenaHeroClient context manager to handle connections and iterate through game turns. ```python from getpass import getpass from arena_hero import ArenaHeroClient, Direction api_key = getpass("Arena Hero API key: ") with ArenaHeroClient(api_key=api_key) as game: for turn in game.turns(): for worker in turn.workers: if worker.position in turn.resource_cells: worker.harvest() else: worker.move(Direction.RIGHT) turn.submit() ``` -------------------------------- ### Open WebSocket connection Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Establish a WebSocket connection with the required Authorization header. ```http GET /api/v1/game/ws HTTP/1.1 Host: api.arenahero.io Upgrade: websocket Connection: Upgrade Authorization: Bearer ``` -------------------------------- ### Unit Action Commands Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md JSON structures for performing unit actions. Each command requires a type field and specific parameters based on the action. ```json {"type":"WAIT"} ``` ```json {"type":"MOVE","direction":"RIGHT"} ``` ```json {"type":"HARVEST"} ``` ```json {"type":"DEPOSIT"} ``` ```json {"type":"SWEEP","direction":"UP"} ``` ```json {"type":"SHOOT","expected_cell":[120,85]} ``` ```json {"type":"PICKUP_BEACON"} ``` ```json {"type":"DROP_BEACON"} ``` ```json {"type":"HEAL"} ``` ```json {"type":"SELF_DESTRUCT"} ``` -------------------------------- ### Turn and AsyncTurn Methods Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Methods available on Turn and AsyncTurn objects to interact with the game state and submit plans. ```APIDOC ## unit(unit_id) ### Description Find one controlled Unit by UUID or UUID string. ## clear() ### Description Remove every queued Unit and Core action. ## submit(idempotency_key=None) ### Description Submit the complete queued plan. For AsyncTurn, this method must be awaited. ``` -------------------------------- ### Import Rule Helpers Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Imports constants and helper functions for calculating resource capacity and unit costs. ```python from arena_hero import ( CORE_RESOURCE_CAPACITY_PER_UNIT, CORE_RESOURCE_MINIMUM_CAPACITY, UNIT_BASE_COSTS, UnitType, core_resource_capacity, unit_cost, ) ``` -------------------------------- ### Core Controller Methods Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Methods available on the Core controller to perform actions such as spawning units, moving, and managing resources. ```APIDOC ## Core Controller Methods ### spawn(unit_type) Spawns a unit of the specified type (WORKER, VANGUARD, or RANGER). ### heal() Recover Core HP after combat. ### repair_shield() Spend resources to repair shield. ### start_move(direction) Start moving the Core in the specified direction. ### cancel_move() Cancel current Core movement. ### pickup_beacon() Pick up the Beacon on the current cell. ### drop_beacon() Drop a carried Beacon. ### self_destruct() Destroy the Core, its inventory, and all owned Units after combat, then enter the normal respawn flow. ### wait() Queue an explicit WAIT action. ### clear_action() Remove the queued Core action. ``` -------------------------------- ### Core Action Commands Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md A list of available actions that can be sent to the Core, defined by their type and required parameters. ```APIDOC ## Core Actions ### Description Core actions define the behavior of a player's Core during a game tick. Actions are submitted as JSON objects. ### Available Actions - **WAIT**: `{"type":"WAIT"}` - No new action; continues existing migration. - **SPAWN**: `{"type":"SPAWN","unit_type":"TYPE"}` - Creates a unit. `unit_type` must be `WORKER`, `VANGUARD`, or `RANGER`. - **HEAL**: `{"type":"HEAL"}` - Spends resources to restore Core HP after combat. - **REPAIR_SHIELD**: `{"type":"REPAIR_SHIELD"}` - Spends 1 resource to restore 1 shield. - **START_MOVE**: `{"type":"START_MOVE","direction":"DIR"}` - Initiates migration. `direction` can be `LEFT`, `RIGHT`, `UP`, or `DOWN`. - **CANCEL_MOVE**: `{"type":"CANCEL_MOVE"}` - Stops current migration. - **PICKUP_BEACON**: `{"type":"PICKUP_BEACON"}` - Attempts to pick up a beacon on the current cell. - **DROP_BEACON**: `{"type":"DROP_BEACON"}` - Attempts to drop a carried beacon. - **SELF_DESTRUCT**: `{"type":"SELF_DESTRUCT"}` - Destroys the Core and its assets after combat. ``` -------------------------------- ### Configure local backend Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Override default production endpoints by providing explicit base_url and websocket_url parameters to the ArenaHeroClient constructor. ```python game = ArenaHeroClient( api_key=api_key, base_url="http://localhost:8080", websocket_url="ws://localhost:8080/api/v1/game/ws", ) ``` -------------------------------- ### Unit Action Commands Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md A list of available unit actions that can be sent to the game engine to control units. ```APIDOC ## Unit Action Commands ### WAIT - **Type**: `WAIT` - **Description**: The unit performs no action. - **JSON**: `{"type":"WAIT"}` ### MOVE - **Type**: `MOVE` - **Description**: Moves the unit one cardinal cell. - **Parameters**: `direction` (String: UP, DOWN, LEFT, RIGHT) - **JSON**: `{"type":"MOVE","direction":"RIGHT"}` ### HARVEST - **Type**: `HARVEST` - **Description**: Consumes a resource point and loads cargo (1 or 2 if holding Beacon). - **JSON**: `{"type":"HARVEST"}` ### DEPOSIT - **Type**: `DEPOSIT` - **Description**: Deposits cargo into the player's Core on the same cell. - **JSON**: `{"type":"DEPOSIT"}` ### SWEEP - **Type**: `SWEEP` - **Description**: Deals 1 damage to enemy entities in the adjacent cell. - **Parameters**: `direction` (String: UP, DOWN, LEFT, RIGHT) - **JSON**: `{"type":"SWEEP","direction":"UP"}` ### SHOOT - **Type**: `SHOOT` - **Description**: Fires at a target cell or specific unit. - **Parameters**: - `expected_cell` (Array: [x, y]) - Required - `target_id` (UUID) - Optional - **JSON**: `{"type":"SHOOT","expected_cell":[120,85]}` ### PICKUP_BEACON - **Type**: `PICKUP_BEACON` - **Description**: Attempts to pick up a Beacon on the unit's current cell. - **JSON**: `{"type":"PICKUP_BEACON"}` ### DROP_BEACON - **Type**: `DROP_BEACON` - **Description**: Drops the Beacon if the unit is the current carrier. - **JSON**: `{"type":"DROP_BEACON"}` ### HEAL - **Type**: `HEAL` - **Description**: Restores HP at the owned stationary Core. - **JSON**: `{"type":"HEAL"}` ### SELF_DESTRUCT - **Type**: `SELF_DESTRUCT` - **Description**: Removes the unit from the game. - **JSON**: `{"type":"SELF_DESTRUCT"}` ``` -------------------------------- ### WebSocket Connection Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/overview.md Connect to the game server to receive tick, state, and received updates. ```APIDOC ## WebSocket wss://api.arenahero.io/api/v1/game/ws ### Description Establish a WebSocket connection to receive game updates including tick numbers, state, and plan receipt confirmations. ### Endpoint wss://api.arenahero.io/api/v1/game/ws ``` -------------------------------- ### Agent state tracking variables Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/command-loop.md List of essential state variables that must be tracked to maintain synchronization with the server. ```text announced_tick latest_state latest_received.AGENT latest_received.MANUAL connection_phase reconnect_attempt obstacle_memory resource_observation_memory ``` -------------------------------- ### Control game objects and submit turns Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Iterate through unit collections to issue commands and finalize actions with turn.submit(). Ensure turn.core is checked before performing core-specific actions. ```python from arena_hero import Direction, UnitType for worker in turn.workers: worker.move(Direction.UP) # The later call replaces MOVE for this Worker. worker.harvest() for ranger in turn.rangers: if turn.visible_enemies: ranger.shoot(turn.visible_enemies[0]) else: x, y = ranger.position ranger.shoot_cell((x + 1, y)) if turn.core is not None: turn.core.heal() turn.core.spawn(UnitType.WORKER) turn.submit() ``` -------------------------------- ### Core Action JSON Definitions Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md A reference table of JSON structures for all available Core actions. ```json {"type":"WAIT"} ``` ```json {"type":"SPAWN","unit_type":"WORKER"} ``` ```json {"type":"HEAL"} ``` ```json {"type":"REPAIR_SHIELD"} ``` ```json {"type":"START_MOVE","direction":"LEFT"} ``` ```json {"type":"CANCEL_MOVE"} ``` ```json {"type":"PICKUP_BEACON"} ``` ```json {"type":"DROP_BEACON"} ``` ```json {"type":"SELF_DESTRUCT"} ``` -------------------------------- ### Calculate unit production costs Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Use the unit_cost helper to determine production prices based on current population. ```python from arena_hero import UnitType, unit_cost worker_price = unit_cost(UnitType.WORKER, turn.state.population) ``` -------------------------------- ### Minimal agent loop logic Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Pseudocode outlining the message handling loop and reconnection strategy. ```text connect with Authorization header for each message: if type == "tick": remember data, but do not act if type == "state": replace the previous world view compute a plan for the announced Tick POST it with a new idempotency key if type == "received": replace the stored plan for data.source on disconnect: stop on close code 1008 and fix the credential or client otherwise reconnect with jittered exponential backoff ``` -------------------------------- ### Process turn events Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Iterate through turn events to handle resource drops, captures, and recovery results. ```python from arena_hero import HarvestSource for event in turn.events: if event.event_type == "WORKER_CARGO_DROPPED": print("dropped", event.resource_amount, "at", event.position) elif event.event_type == "CORE_RESOURCE_OVERFLOW_DESTROYED": print("destroyed", event.resource_amount, "excess Core resources") elif event.core_resource_capture is not None: capture = event.core_resource_capture print("captured", capture.amount, "destroyed", capture.destroyed) elif event.harvest_source is HarvestSource.DROPPED_CARGO: print("recovered", event.resource_amount, "at", event.position) ``` -------------------------------- ### Unit Controls Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Base methods available to all Unit objects for movement, interaction, and state management. ```APIDOC ## Unit Methods ### move(direction) Queue a one-cell move. ### pickup_beacon() Pick up the Beacon on the current cell. ### drop_beacon() Drop a carried Beacon. ### heal() Recover HP after combat while sharing a cell with the owned stationary Core. ### self_destruct() Remove this Unit before movement. ### wait() Queue an explicit WAIT. ### clear_action() Remove this Unit from the queued plan. ``` -------------------------------- ### Process full event stream Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Use game.events() to access Tick notices and canonical plans from other clients. Do not use events() and turns() simultaneously on the same client instance. ```python from arena_hero import ArenaHeroClient, Received, Tick, Turn with ArenaHeroClient(api_key=api_key) as game: for event in game.events(): if isinstance(event, Tick): current_tick = event.tick elif isinstance(event, Turn): event.submit() elif isinstance(event, Received): print(event.source, event.plan) ``` -------------------------------- ### Minimal state message JSON Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Represents a complete snapshot of the current player state including status, resources, and active world objects. ```json { "type": "state", "data": { "status": "ACTIVE", "resources": 5, "population": 1, "champion_beacon": {"position": [0, 0]}, "objects": [ { "kind": "CORE", "id": "2ea3c3dc-42b0-4b92-9754-7558bd4ff834", "controlled": true, "owner_username": "arena_hero", "position": [12, 8], "hp": 5, "shield": 5, "state": "NORMAL" }, { "kind": "UNIT", "id": "9d3e4941-2816-4a39-a220-df8cd95e877d", "controlled": true, "position": [11, 8], "hp": 2, "unit_type": "WORKER", "cargo": 0 } ], "events": [] } } ``` -------------------------------- ### WebSocket Connection URL Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md The endpoint for establishing a WebSocket connection to the game server. ```text wss://api.arenahero.io/api/v1/game/ws ``` -------------------------------- ### Submit Core Self-Destruct Action Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/core-and-economy.md Submit a self-destruct command for a living Core. This action has no resource or cooldown restrictions. ```json {"type":"SELF_DESTRUCT"} ``` -------------------------------- ### Dispatch by kind Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Iterate through state objects and route them to specific handlers based on their kind. ```js for (const object of state.objects) { if (object.kind === 'CORE') handleCore(object); else if (object.kind === 'UNIT') handleUnit(object); else handleTerrain(object); } ``` -------------------------------- ### Champion Beacon Visibility States Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md JSON representations of the Champion Beacon object based on whether it is outside vision, on the ground, or being carried. ```json { "position": [120, 85] } ``` ```json { "position": [120, 85], "status": "GROUND" } ``` ```json { "position": [120, 85], "status": "CARRIED", "carrier_id": "9d3e4941-2816-4a39-a220-df8cd95e877d" } ``` -------------------------------- ### Define API endpoints Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Base URLs for HTTP and WebSocket communication. ```text HTTP base: https://api.arenahero.io WebSocket: wss://api.arenahero.io/api/v1/game/ws ``` -------------------------------- ### Invoke the Skill in Codex Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/skill/overview.md Use this prompt within a Codex session to initiate tactic generation. ```text Use $arena-hero to create a balanced tactic for Arena Hero. ``` -------------------------------- ### ArenaHeroClient / AsyncArenaHeroClient Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Initializes the synchronous or asynchronous client for interacting with the ArenaHero API. ```APIDOC ## ArenaHeroClient / AsyncArenaHeroClient ### Description Initializes the client used to communicate with the ArenaHero API. Both synchronous and asynchronous versions accept the same configuration parameters. ### Parameters - **api_key** (str) - Required - Credential sent as Authorization: Bearer. - **base_url** (str) - Optional - HTTP API base URL (default: https://api.arenahero.io). - **websocket_url** (str) - Optional - WebSocket endpoint URL. - **request_timeout** (float) - Optional - Timeout in seconds for HTTP attempts (default: 5.0). - **request_retries** (int) - Optional - Number of retries for HTTP attempts (default: 2). - **reconnect_min_delay** (float) - Optional - Initial WebSocket reconnect delay (default: 0.25). - **reconnect_max_delay** (float) - Optional - Maximum WebSocket reconnect delay (default: 5.0). - **max_message_size** (int) - Optional - Maximum WebSocket message size in bytes (default: 2MB). ``` -------------------------------- ### Calculate unit pricing and capacity Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/reference/numbers.md Determines resource capacity and dynamic unit pricing based on current population. ```text population = Worker + Vanguard + Ranger resource_capacity = max(10, population × 5) k = max(0, floor((population - 20) / 5) + 1) unit_price = round_half_up(base_price × (13 / 10)^k) ``` -------------------------------- ### turns() Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Retrieves an iterator for actionable game turns. ```APIDOC ## turns() ### Description Yields each actionable Tick once. Receipts are processed internally and stored in latest_receipts. ### Returns - **Iterator[Turn] / AsyncIterator[AsyncTurn]** - An iterator yielding game turns. ``` -------------------------------- ### Champion Beacon Position Data Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/map-and-vision.md Basic coordinate structure for the beacon. ```json {"position": [0, 0]} ``` -------------------------------- ### Accepted Response Format Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/commands.md The HTTP response and JSON body returned when a plan is successfully stored. ```http HTTP/1.1 202 Accepted Content-Type: application/json; charset=utf-8 ``` ```json { "accepted": true, "tick": 10583, "source": "AGENT", "received_at": "2026-07-27T05:40:06.241Z" } ``` -------------------------------- ### Authentication header Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/overview.md The required format for sending the Agent token in HTTP or WebSocket upgrade headers. ```http Authorization: Bearer ``` -------------------------------- ### Received message structure Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Confirms that a plan has been stored by the server. ```json { "type": "received", "data": { "tick": 10583, "source": "AGENT", "received_at": "2026-07-27T05:40:06.241Z", "plan": { "tick": 10583, "unit_actions": { "9d3e4941-2816-4a39-a220-df8cd95e877d": { "type": "MOVE", "direction": "RIGHT" } }, "core_action": {"type": "WAIT"} } } } ``` -------------------------------- ### Asynchronous game loop Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Use the AsyncArenaHeroClient to manage game turns within an asyncio event loop. ```python import asyncio from getpass import getpass from arena_hero import AsyncArenaHeroClient, Direction async def play(api_key: str) -> None: async with AsyncArenaHeroClient(api_key=api_key) as game: async for turn in game.turns(): for vanguard in turn.vanguards: vanguard.sweep(Direction.LEFT) await turn.submit() asyncio.run(play(getpass("Arena Hero API key: "))) ``` -------------------------------- ### Receive tick and state messages Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Initial messages received from the server to synchronize the agent's world view. ```json {"type": "tick", "data": 10583} ``` ```json { "type": "state", "data": { "status": "ACTIVE", "resources": 5, "population": 1, "champion_beacon": {"position": [0, 0]}, "objects": [ { "kind": "CORE", "id": "2ea3c3dc-42b0-4b92-9754-7558bd4ff834", "controlled": true, "owner_username": "arena_hero", "position": [12, 8], "hp": 5, "shield": 5, "state": "NORMAL" }, { "kind": "UNIT", "id": "9d3e4941-2816-4a39-a220-df8cd95e877d", "controlled": true, "position": [11, 8], "hp": 2, "unit_type": "WORKER", "cargo": 0 } ], "events": [] } } ``` -------------------------------- ### Calculate Core resource capacity Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/core-and-economy.md Determines the maximum resource storage based on the current population, with a minimum capacity of 10. ```text resource_capacity = max(10, population × 5) ``` -------------------------------- ### Champion Beacon Ground Status Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/map-and-vision.md Data structure when the beacon is visible on the ground. ```json {"position": [0, 0], "status": "GROUND"} ``` -------------------------------- ### Confirm plan receipt Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/agent/quickstart.md Server response confirming the stored plan for the current tick. ```json { "type": "received", "data": { "tick": 10583, "source": "AGENT", "received_at": "2026-07-27T05:40:06.241Z", "plan": { "tick": 10583, "unit_actions": { "9d3e4941-2816-4a39-a220-df8cd95e877d": { "type": "MOVE", "direction": "RIGHT" } } } } } ``` -------------------------------- ### Connect via WebSocket Upgrade Request Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Non-browser agents must provide a Bearer token in the Authorization header during the initial HTTP upgrade request. ```http GET /api/v1/game/ws HTTP/1.1 Host: api.arenahero.io Authorization: Bearer Upgrade: websocket Connection: Upgrade ``` -------------------------------- ### Calculate resource quota Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/reference/numbers.md Determines the resource quota per chunk based on the chunk coordinates. ```text axis(c) = c if c >= 0 else -c - 1 ring = axis(cx) + axis(cy) resource_quota = max(2, floor(16 * 8 / (8 + ring))) ``` -------------------------------- ### Fetch Leaderboard Data Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/leaderboard.md Public endpoint to retrieve lifetime rankings. No authentication headers are required. ```http GET https://api.arenahero.io/api/v1/leaderboard ``` -------------------------------- ### Leaderboard Response Format Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/leaderboard.md The JSON structure returned by the leaderboard endpoint containing rankings for three categories. ```json { "beacon_ticks_held": [ {"rank": 1, "username": "beacon_runner", "score": 912} ], "damage_dealt": [ {"rank": 1, "username": "ranger_one", "score": 2401} ], "core_destruction_participations": [ {"rank": 1, "username": "vanguard", "score": 17} ] } ``` -------------------------------- ### Rebuild entity map from state Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Iterate through the nextState objects to populate a Map keyed by object ID. Only includes CORE and UNIT types. ```js const entities = new Map(); for (const object of nextState.objects) { if (object.kind === 'CORE' || object.kind === 'UNIT') { entities.set(object.id, object); } } ``` -------------------------------- ### Calculate dynamic unit pricing Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/core-and-economy.md Formula for determining unit costs based on the number of living units N, where prices increase by 30% for every five-unit band after the first 20 units. ```text N = living Units when Core actions resolve k = max(0, floor((N - 20) / 5) + 1) price = round_half_up(base_price × (13 / 10)^k) ``` -------------------------------- ### Worker harvest action Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Standard harvest command for worker units. ```json {"type": "HARVEST"} ``` -------------------------------- ### events() Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Retrieves an iterator for the application-level WebSocket stream. ```APIDOC ## events() ### Description Yields the complete application-level WebSocket stream, including Ticks, Turns, and Received events. ### Returns - **Iterator[Tick | Turn | Received] / AsyncIterator[Tick | AsyncTurn | Received]** - An iterator yielding stream events. ``` -------------------------------- ### Healing unit action Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Restores HP if the unit is alive and shares a cell with its stationary Core. Consumes one Core resource per HP restored. ```json {"type": "HEAL"} ``` -------------------------------- ### Vanguard sweep action Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Executes a sweep in a specified direction. ```json {"type": "SWEEP", "direction": "RIGHT"} ``` -------------------------------- ### Access turn state properties Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/quickstart.md Retrieve authoritative state snapshots from the current turn object. ```python turn.tick turn.resources turn.resource_capacity turn.resource_space turn.core turn.units turn.workers turn.vanguards turn.rangers turn.visible_enemies turn.resource_cells turn.obstacle_cells turn.beacon turn.events ``` -------------------------------- ### Cache Control Header Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/leaderboard.md The response includes a Cache-Control header indicating a public cache duration of 15 seconds. ```http Cache-Control: public, max-age=15 ``` -------------------------------- ### Access latest_receipts Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Retrieves the latest current-Tick Received values for specific command sources. ```python from arena_hero import CommandSource agent_receipt = game.latest_receipts.get(CommandSource.AGENT) manual_receipt = game.latest_receipts.get(CommandSource.MANUAL) ``` -------------------------------- ### WebSocket Message Protocol Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Overview of the message types received from the server via WebSocket. ```APIDOC ## WebSocket Messages ### Description The server sends UTF-8 JSON frames. Clients should parse the `type` field to determine the message structure. ### Message Types - **tick**: Indicates a new tick is being prepared. Contains a positive int64 representing the tick number. - **state**: Provides the current game state. Contains a `PlayerState` object. - **received**: Confirms that a plan has been stored. Contains receipt details including tick, source, and the stored plan. ### Example Dispatch ```js function onMessage(frame) { const message = JSON.parse(frame); if (message.type === 'tick') currentTick = message.data; else if (message.type === 'state') onState(currentTick, message.data); else if (message.type === 'received') onReceipt(message.data); } ``` ``` -------------------------------- ### Tick message structure Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md Represents a new tick being prepared by the server. ```json { "type": "tick", "data": 10583 } ``` -------------------------------- ### SELF_DESTRUCT Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/core-and-economy.md Submits a request for the Core to self-destruct. This action occurs after combat if the Core survives. ```APIDOC ## POST /core/self-destruct ### Description Submits a request for the Core to self-destruct. If the Core survives combat, it is destroyed along with its inventory and owned units. ### Request Body - **type** (string) - Required - Must be "SELF_DESTRUCT" ``` -------------------------------- ### Ranger Shooting Actions Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Methods for executing ranged attacks using coordinates or target objects. ```python ranger.shoot_cell((120, 85)) ranger.shoot(target) ranger.shoot(target_id, expected_cell=(120, 85)) ``` -------------------------------- ### Self-destruct unit action Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Removes the unit before movement. Cargo and beacons are dropped at the unit's current cell. ```json {"type": "SELF_DESTRUCT"} ``` -------------------------------- ### Game loop sequence Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/overview.md The sequence of events from receiving a tick to processing action results. ```text WebSocket tick -> save the Tick number and wait WebSocket state -> replace the old state and choose actions HTTP POST /api/v1/game/commands -> 202 means the plan was stored WebSocket received -> shows the plan stored for that source next WebSocket state -> state.events contains the action results ``` -------------------------------- ### Vanguard Controls Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Specialized methods for Vanguard units to perform combat sweeps. ```APIDOC ## Vanguard Methods ### sweep(direction) Attack the adjacent cell in one direction. ``` -------------------------------- ### SHOOT Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Performs a ranged shot at a specific target cell. ```APIDOC ## SHOOT ### Description Performs a ranged shot at a specific target cell. ### Request Body - **type** (string) - Required - Must be "SHOOT" - **expected_cell** (array) - Required - The [x, y] coordinates of the target cell ``` -------------------------------- ### Worker Controls Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/sdk/reference.md Specialized methods for Worker units to manage resource harvesting and depositing. ```APIDOC ## Worker Methods ### harvest() Try to consume the resource point on the current cell. ### deposit() Deposit what fits while sharing a cell with the Core. ``` -------------------------------- ### Game Loop Message Sequence Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/websocket.md The expected order of messages received during the game loop. ```text tick(N) → state → zero or more received messages → quiet while N resolves → tick(N + 1) → state containing results for N ``` -------------------------------- ### RESPAWNING state representation Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/destruction-and-respawn.md The state object returned when a player is in the RESPAWNING status due to a failed spawn placement. ```json { "status": "RESPAWNING", "respawn_at_tick": 10604, "resources": 0, "population": 0, "champion_beacon": {"position": [0, 0]}, "objects": [], "events": [] } ``` -------------------------------- ### Terrain object structure Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/api/state-model.md Represents visible map features like obstacles or resources as a batch of positions. ```json { "kind": "OBSTACLE", "positions": [[4, 7], [4, 8], [5, 8]] } ``` -------------------------------- ### HARVEST Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/units.md Performs a harvest action for worker units. ```APIDOC ## HARVEST ### Description Standard harvest action for worker units. ### Request Body - **type** (string) - Required - Must be "HARVEST" ``` -------------------------------- ### CORE_RESOURCES_CAPTURED event structure Source: https://github.com/arena-hero/arena-hero-doc/blob/main/docs/rules/destruction-and-respawn.md The JSON structure sent to a winning player when they successfully capture resources from a destroyed Core. ```json {"amount":3,"available":8,"destroyed":5,"capacity":10} ```