src/robocode_tankroyale_botapi

Source   Edit  

Main entry-point module for Robocode Tank Royale Nim bot API.

This module is the primary interface for writing Robocode Tank Royale bots in Nim. It re-exports all public symbols from the submodules, so you only need to import this one module in your bot code.

Quick Start

  1. Create a bot type that inherits from Bot:

    import robocode_tankroyale_botapi
    
    type MyBot = ref object of Bot
    method run(bot: MyBot) =
      # Your bot logic here
      forward(100)
      turnLeft(90)
      fire(2.0)

  2. Create an instance and start it with your bot's JSON configuration file:

    var bot = MyBot()
    start(bot, "MyBot.json")

The JSON file contains your bot's identity (name, version, authors, etc.) and optional settings like initial position and game types. See BotInfo for details.

Architecture Overview

The API uses a three-thread architecture:

  • Main thread: Runs the WebSocket receive loop, processes incoming server messages, updates shared state, and wakes the bot thread each tick.
  • Bot thread: Runs your run() method and event handlers. It blocks on go() waiting for the next tick.
  • Sender thread: Owns all WebSocket writes, sending your bot's intents to the server.

Communication between threads happens through channels, avoiding shared mutable state where possible.

Exported Modules

This module re-exports the following submodules:

  • constants -- Game physics constants and event priorities
  • color -- Color type with 141 named colors and hex parsing
  • schemas -- Protocol message types (events, game setup, etc.)
  • utils -- Math and geometry helpers (bearing, distance, angles)
  • bot_info -- Bot identity loading from JSON or environment
  • ws_client -- Low-level WebSocket client (internal)
  • json_parse -- Safe JSON-to-type parsing (internal)
  • event_queue -- Priority-based event dispatch (internal)
  • bot -- Core bot implementation, movement, and event handlers
  • graphics -- SVG debug graphics for visualization

See Also

  • Bot -- Base class for your bot implementation
  • start -- Connect to server and begin the game loop
  • BotInfo -- Bot identity configuration

Procs

proc runReceiveLoop(ws: SyncWebSocket; info: BotInfo; secret: string;
                    serverUrl: string) {....raises: [IOError, IOError, IOError],
    tags: [ReadIOEffect, TimeEffect, WriteIOEffect, RootEffect], forbids: [].}

Main WebSocket receive loop.

This procedure runs on the main thread and handles all incoming messages from the Tank Royale server. It:

  • Receives WebSocket frames
  • Parses JSON messages
  • Dispatches messages to appropriate handlers (handshake, game start, ticks, round end, game end, etc.)
  • Updates shared game state
  • Signals the bot thread when a new tick arrives

The loop runs until the connection is closed or a fatal error occurs. Timeouts are ignored; the bot waits indefinitely for server messages.

Note: This is an internal procedure. You typically don't call it directly; use start() instead.

Parameters:

  • ws: The connected WebSocket
  • info: Your bot's identity information
  • secret: Optional server secret for authentication
  • serverUrl: The server URL (used for error reporting)
Source   Edit  
proc start(bot: Bot; jsonFile: string = "") {....raises: [IOError, OSError,
    JsonParsingError, ValueError, KeyError, IOError, ResourceExhaustedError], tags: [
    ReadDirEffect, ReadIOEffect, WriteIOEffect, ReadEnvEffect, RootEffect,
    TimeEffect], forbids: [].}

Connect to the Tank Royale server and start the bot's game loop.

This is the main entry point for running your bot. It:

  1. Loads your bot's identity from jsonFile (or environment variables)
  2. Connects to the WebSocket server (default: ws://localhost:7654)
  3. Performs the handshake with the server
  4. Starts the three-thread architecture (receive, bot, sender)
  5. Blocks until the game ends or connection is lost

The procedure never returns normally -- it runs until the game ends, the server disconnects, or a fatal error occurs.

Configuration

You can configure the connection via environment variables:

  • SERVER_URL -- WebSocket server URL (default: ws://localhost:7654)
  • SERVER_SECRET -- Optional secret for authenticated servers

Parameters

  • bot: An instance of your bot type (must inherit from Bot)
  • jsonFile: Path to your bot's JSON configuration file. If empty or not found, falls back to environment variables (BOT_NAME, BOT_VERSION, BOT_AUTHORS, etc.). See loadBotInfo for details.

Example

import robocode_tankroyale_botapi

type MyBot = ref object of Bot
method run(bot: MyBot) =
  while true:
    forward(100)
    turnLeft(90)

var bot = MyBot()
start(bot, "MyBot.json")

Source   Edit  

Exports

BOT_RADIUS, PRIORITY_HIT_BY_BULLET, MAX_TURN_RATE, MAX_RADAR_TURN_RATE, PRIORITY_TEAM_MESSAGE, MAX_QUEUE_SIZE, PRIORITY_BULLET_FIRED, MAX_FIRE_POWER, MAX_GUN_TURN_RATE, PRIORITY_HIT_WALL, MAX_NUMBER_OF_TEAM_MESSAGES_PER_TURN, NEGATIVE_INFINITY, RAM_DAMAGE, PRIORITY_BULLET_HIT_WALL, MAX_SPEED, RADAR_RADIUS, PRIORITY_BULLET_HIT_BULLET, PRIORITY_DEATH, PRIORITY_CUSTOM, PRIORITY_BULLET_HIT_BOT, ONE_VS_ONE, PRIORITY_SKIPPED_TURN, POSITIVE_INFINITY, ACCELERATION, MIN_VALUE, MAX_EVENTS_AGE, STARTING_GUN_HEAT, INACTIVITY_ZAP, PRIORITY_SCANNED_BOT, CLASSIC, PRIORITY_TICK, PRIORITY_BOT_DEATH, MELEE, DECELERATION, ABS_DECELERATION, TEAM_MESSAGE_MAX_SIZE, PRIORITY_WON_ROUND, MIN_FIRE_POWER, PRIORITY_HIT_BOT, FOREST_GREEN, GREEN, PEACH_PUFF, LIME_GREEN, INDIGO, TAN, BLANCHED_ALMOND, WHEAT, g, DARK_RED, toHex, CYAN, PERU, ==, LIGHT_SEA_GREEN, MEDIUM_PURPLE, GAINSBORO, STEEL_BLUE, GRAY, BEIGE, $, AZURE, ROYAL_BLUE, DARK_KHAKI, DEEP_SKY_BLUE, SILVER, HOT_PINK, DARK_VIOLET, DARK_CYAN, DARK_TURQUOISE, MEDIUM_SLATE_BLUE, FLORAL_WHITE, LEMON_CHIFFON, toColor, ROSY_BROWN, DARK_MAGENTA, DARK_OLIVE_GREEN, AQUA, SNOW, SPRING_GREEN, TRANSPARENT, a, LIGHT_GRAY, DEEP_PINK, TURQUOISE, TEAL, RED, WHITE, SANDY_BROWN, DARK_BLUE, GHOST_WHITE, DARK_ORCHID, LIGHT_SALMON, BLACK, BURLY_WOOD, MEDIUM_BLUE, ORANGE_RED, CHARTREUSE, PINK, LIGHT_YELLOW, PLUM, SADDLE_BROWN, LIGHT_GOLDENROD_YELLOW, Color, LIGHT_STEEL_BLUE, DARK_GOLDENROD, DARK_ORANGE, BLUE_VIOLET, THISTLE, DARK_GRAY, ANTIQUE_WHITE, MEDIUM_SPRING_GREEN, MEDIUM_VIOLET_RED, MAGENTA, PALE_GOLDENROD, SLATE_GRAY, YELLOW, FUCHSIA, LAVENDER_BLUSH, fromRgba, NAVY, VIOLET, MINT_CREAM, GOLDENROD, DARK_SALMON, SEA_SHELL, CRIMSON, fromHex, OLD_LACE, CORAL, b, KHAKI, MEDIUM_ORCHID, SLATE_BLUE, LIGHT_BLUE, POWDER_BLUE, MOCCASIN, DIM_GRAY, TOMATO, SEA_GREEN, MISTY_ROSE, DARK_SLATE_BLUE, SALMON, ORANGE, CORNSILK, HONEYDEW, PALE_VIOLET_RED, CADET_BLUE, YELLOW_GREEN, NAVAJO_WHITE, WHITE_SMOKE, MEDIUM_TURQUOISE, AQUAMARINE, IVORY, OLIVE_DRAB, ORCHID, GREEN_YELLOW, DODGER_BLUE, DARK_GREEN, BROWN, PALE_TURQUOISE, PAPAYA_WHIP, LIGHT_SLATE_GRAY, LIGHT_SKY_BLUE, INDIAN_RED, MEDIUM_SEA_GREEN, LAVENDER, SKY_BLUE, LINEN, LIGHT_CYAN, MEDIUM_AQUAMARINE, r, CHOCOLATE, LIGHT_GREEN, FIREBRICK, PALE_GREEN, DARK_SLATE_GRAY, PURPLE, GOLD, BLUE, SIENNA, MIDNIGHT_BLUE, ALICE_BLUE, BISQUE, DARK_SEA_GREEN, LIGHT_CORAL, LIGHT_PINK, CORNFLOWER_BLUE, LAWN_GREEN, OLIVE, MAROON, LIME, fromRgb, GameSetup, BulletHitBulletEvent, TeamMessage, BulletFiredEvent, GameStartedEventForBot, GameEndedEventForBot, ResultsForBot, WonRoundEvent, SkippedTurnEvent, HitByBulletEvent, ConnectedEvent, RoundStartedEvent, BotState, BotIntent, BulletHitBotEvent, GameAbortedEvent, InitialPosition, BotHandshake, BotReady, ScannedBotEvent, TeamMessageEvent, TickEventForBot, BotHitBotEvent, DisconnectedEvent, BotDeathEvent, ConnectionErrorEvent, RawEvent, ServerHandshake, BulletHitWallEvent, BotHitWallEvent, BulletState, RoundEndedEventForBot, directionTo, getDistanceTraveledUntilStop, calcBulletSpeed, distanceTo, getNewTargetSpeed, calcGunHeat, normalizeAbsoluteAngle, normalizeRelativeAngle, calcMaxTurnRate, bearingTo, calcDeltaAngle, isNearZero, newBotInfo, BotInfo, loadBotInfo, MAX_NAME_LEN, botInfoFromEnv, botInfoFromJson, parseBulletState, parseBotEvent, parseBotState, setPriority, initEventQueue, clear, getEvents, EventQueue, priorityOf, removeConditionByName, addCondition, popFirst, BotEvent, getPriority, setInterruptible, sortEvents, addEvent, isCritical, Condition, isInterruptible, EventKind, clearEvents, addCustomEvents, removeOldEvents, getTurn, getRadarTurnRate, setScanColor, getGunDirection, getGunTurnRemaining, getMyId, removeCustomEvent, getTargetSpeed, getRadarSweep, getTimeLeft, shutdownBotThread, getEnemyCount, onHitBot, radarBearingTo, waitForBotThreadWhileServicingWs, onScannedBot, resume, setGunTurnRate, getArenaHeight, getBotName, getGameType, onCustomEvent, getMaxSpeed, getX, onSkippedTurn, getGunTurnRate, isAdjustRadarForGunTurn, getScanColor, onWonRound, getTeammateIds, getRadarColor, back, go, rescan, onBotDeath, onBulletFired, signalStop, getTurnTimeout, getTurretColor, getMaxInactivityTurns, processTickOnMainThread, getArenaWidth, turnRadarRight, updateBotNames, waitForBotThread, setResume, getServerVersion, bearingTo, calcRadarBearing, onConnected, setInterruptible, getTurnRemaining, gBotInfo, stopSenderThread, getTurnRate, waitFor, isAdjustRadarForBodyTurn, getNumberOfRounds, onBulletHitWall, distanceTo, calcGunBearing, printToStdOut, onConnectionError, getEnergy, turnRadarLeft, getVariant, onBulletHitBullet, setTurnGunLeft, debugLog, recvIntent, setBack, setTurnRight, drainTickChan, calcBearing, setForward, onHitWall, onGameEnded, getBulletColor, setFireAssist, setAdjustRadarForBodyTurn, onDeath, getMaxRadarTurnRate, getRadarTurnRemaining, startRound, getGunHeat, getEventPriority, printToStdErr, startBotThread, setTurnGunRight, wakeBotThread, isStopped, processTurn, setGunColor, setServerInfo, gBot, initGlobals, getTracksColor, setAdjustRadarForGunTurn, setTurnLeft, clearEvents, dispatchPendingEvents, isDisabled, getY, setTracksColor, getSpeed, onRoundEnded, setTargetSpeed, startSenderThread, getEvents, getMaxGunTurnRate, setRescan, forward, BotState, drainEventChan, onTeamMessage, run, gunBearingTo, fire, signalTick, turnLeft, isRunning, isTeammate, onGameStarted, setMaxGunTurnRate, gPendingMsg, setTurretColor, Bot, isAdjustGunForBodyTurn, onBulletHit, gWs, setBulletColor, sendTeamMessage, setGameStarted, setRunning, onRoundStarted, setEventPriority, drainIntentChan, setMaxSpeed, getRadarDirection, setMaxTurnRate, clearRemaining, getMaxTurnRate, onHitByBullet, setFire, setMaxRadarTurnRate, turnGunRight, directionTo, getGunCoolingRate, setTurnRadarLeft, isDroid, getDirection, setStop, setTurnRadarRight, setBodyColor, setRadarTurnRate, getGunColor, setTurnRate, turnGunLeft, onTick, getBodyColor, onGameAborted, getDistanceRemaining, getRound, setAdjustGunForBodyTurn, getFirepower, onDisconnected, stop, addCustomEvent, buildIntentJson, getBulletStates, turnRight, setRadarColor, broadcastTeamMessage, clearGraphics, drawRectangle, drawLine, drawText, setStrokeWidth, gArenaWidth, drawCircle, fillCircle, setArenaDimensions, setStrokeColor, setFont, setFillColor, svgOutput, fillRectangle, gArenaHeight, fillPolygon, drawPolygon