bot_api.internal package¶
Submodules¶
bot_api.internal.base_bot_internals module¶
- class BaseBotInternals(base_bot: BaseBotABC, bot_info: BotInfo | None, server_url: str | None, server_secret: str | None)[source]¶
Bases:
object- property my_id: int¶
- property teammate_ids: Set[int]¶
- property initial_position: InitialPosition | None¶
- property tick_start_nano_time: int¶
- property event_handling_disabled_turn: int¶
- execute(captured_turn_number: int) None[source]¶
Execute bot intent and wait for next turn.
- Parameters:
captured_turn_number – The turn number captured by go() at the time events were dispatched, or -1 if no tick was available.
- set_fire(firepower: float) bool[source]¶
Set fire with given firepower. Matches Java’s setFire() semantics exactly.
- property turn_rate: float¶
- property gun_turn_rate: float¶
- property radar_turn_rate: float¶
- property target_speed: float | None¶
- get_graphics() GraphicsABC[source]¶
- get_bullet_states() Sequence[BulletState | None][source]¶
- property server_handshake: ServerHandshake¶
- property variant: str¶
- property version: str¶
bot_api.internal.bot_event_handlers module¶
Class used for bot event handlers on the public API.
These handlers may or may not be triggered by the bot event queue, and might not be handled immediately by the bot logic.
- class BotEventHandlers(base_bot: BaseBotABC)[source]¶
Bases:
objectClass used for bot event handlers on the public API.
These handlers may or may not be triggered by the bot event queue, and might not be handled immediately by the bot logic.
- __init__(base_bot: BaseBotABC)[source]¶
Initialize a new BotEventHandlers instance.
- Parameters:
base_bot – The base bot that will handle the events.
bot_api.internal.bot_handshake_factory module¶
bot_api.internal.bot_internals module¶
- class BotInternals(bot: Bot, base_bot_internals: BaseBotInternals)[source]¶
Bases:
StopResumeListenerABC- on_hit_bot(e: HitBotEvent) None[source]¶
- property turn_rate: float¶
- property gun_turn_rate: float¶
- property radar_turn_rate: float¶
- property target_speed: float | None¶
bot_api.internal.env_vars module¶
- class EnvVars[source]¶
Bases:
objectUtility class for reading environment variables.
- ServerUrl = 'SERVER_URL'¶
Name of environment variable for server URL.
- ServerSecret = 'SERVER_SECRET'¶
Name of environment variable for server secret.
- BotName = 'BOT_NAME'¶
Name of environment variable for bot name.
- BotVersion = 'BOT_VERSION'¶
Name of environment variable for bot version.
- BotAuthors = 'BOT_AUTHORS'¶
Name of environment variable for bot author(s).
- BotDescription = 'BOT_DESCRIPTION'¶
Name of environment variable for bot description.
- BotHomepage = 'BOT_HOMEPAGE'¶
Name of environment variable for bot homepage URL.
- BotCountryCodes = 'BOT_COUNTRY_CODES'¶
Name of environment variable for bot country code(s).
- BotGameTypes = 'BOT_GAME_TYPES'¶
Name of environment variable for bot game type(s).
- BotPlatform = 'BOT_PLATFORM'¶
Name of environment variable for bot platform.
- BotProgrammingLang = 'BOT_PROG_LANG'¶
Name of environment variable for bot programming language.
- BotInitialPosition = 'BOT_INITIAL_POS'¶
Name of environment variable for bot initial position.
- TeamId = 'TEAM_ID'¶
Name of environment variable for bot team id.
- TeamName = 'TEAM_NAME'¶
Name of environment variable for bot team name.
- TeamVersion = 'TEAM_VERSION'¶
Name of environment variable for bot team version.
- BotBooted = 'BOT_BOOTED'¶
Name of environment variable that set if the bot is being booted.
- MissingEnvValue = 'Missing environment variable: '¶
- static get_bot_info() BotInfo[source]¶
Gets the bot info from environment variables.
- Returns:
An object containing the bot’s information.
- Return type:
- static get_server_url() str | None[source]¶
Gets the server URL from environment variables.
- Returns:
The server URL, or None if not set.
- Return type:
Optional[str]
- static get_server_secret() str | None[source]¶
Gets the server secret from environment variables.
- Returns:
The server secret, or None if not set.
- Return type:
Optional[str]
- static get_bot_name() str | None[source]¶
Gets the bot name from environment variables.
- Returns:
The bot name, or None if not set.
- Return type:
Optional[str]
- static get_bot_version() str | None[source]¶
Gets the bot version from environment variables.
- Returns:
The bot version, or None if not set.
- Return type:
Optional[str]
- static get_bot_authors() List[str][source]¶
Gets the bot author(s) from environment variables.
- Returns:
A list of author names, or an empty list if not set.
- Return type:
List[str]
- static get_bot_description() str | None[source]¶
Gets the bot description from environment variables.
- Returns:
The bot description, or None if not set.
- Return type:
Optional[str]
- static get_bot_homepage() str | None[source]¶
Gets the bot homepage URL from environment variables.
- Returns:
The bot homepage URL, or None if not set.
- Return type:
Optional[str]
- static get_bot_country_codes() List[str][source]¶
Gets the bot country code(s) from environment variables.
- Returns:
A list of country codes, or an empty list if not set.
- Return type:
List[str]
- static get_bot_game_types() Set[str][source]¶
Gets the list of game type(s) supported by the bot from environment variables.
- Returns:
A set of game types, or an empty set if not set.
- Return type:
Set[str]
- static get_bot_platform() str | None[source]¶
Gets the platform used for running the game from environment variables.
- Returns:
The platform, or None if not set.
- Return type:
Optional[str]
- static get_bot_programming_lang() str | None[source]¶
Gets the programming language used for running the game from environment variables.
- Returns:
The programming language, or None if not set.
- Return type:
Optional[str]
- static get_bot_initial_position() InitialPosition | None[source]¶
Gets the initial starting position for the bot used for debugging from environment variables.
- Returns:
The initial position of the bot.
- Return type:
- static get_team_id() int | None[source]¶
Gets the bot team ID if provided from environment variables.
- Returns:
The team ID, or None if not set.
- Return type:
Optional[int]
- static get_team_name() str | None[source]¶
Gets the bot team name if provided from environment variables.
- Returns:
The team name, or None if not set.
- Return type:
Optional[str]
bot_api.internal.event_handler module¶
- class EventHandler[source]¶
Bases:
Generic[T]Generic event handler for handling and dispatching events of type T.
Events can be published to all subscribed listeners, which will be invoked in order of their priority. Subscribers with higher priority are invoked before lower priority ones. This handler provides thread-safety through synchronization and exception handling during event publication.
- Type Parameters:
T: The type of event that this handler processes. Must implement the EventABC interface.
- subscribe(subscriber: Callable[[T], None], priority: int = 1) None[source]¶
Subscribe a new event handler with a given priority.
- Parameters:
subscriber – The subscriber callback that will handle the events
priority – The priority of the subscriber; higher values indicate higher priority (0-100)
- Raises:
ValueError – If priority is outside valid range or subscriber is already registered
TypeError – If subscriber is None
- unsubscribe(subscriber: Callable[[T], None]) bool[source]¶
Unsubscribe a subscriber from this event handler.
- Parameters:
subscriber – The subscriber to be removed from subscriptions
- Returns:
True if the subscriber was found and removed, False otherwise
- Return type:
bool
- publish(event_data: T) None[source]¶
Publishes an event, invoking all subscribed listeners in order of their priority.
- Parameters:
event_data – The event data to be published to the subscribers
- Raises:
TypeError – If event_data does not implement the EventABC interface
- get_subscriber_count() int[source]¶
Returns the number of subscribers currently registered.
- Returns:
The count of subscribers
- Return type:
int
bot_api.internal.event_interruption module¶
- class EventInterruption[source]¶
Bases:
objectManages event interruption settings for bot events.
This class is responsible for tracking which bot event types are marked as interruptible. Events marked as interruptible can interrupt the normal execution flow of bot events.
- __init__()[source]¶
Initializes the EventInterruption class.
This is a private constructor to prevent instantiation of this class.
bot_api.internal.event_priorities module¶
- class EventPriorities[source]¶
Bases:
objectManages priorities for bot events in the game.
This class maintains a registry of event priorities that determine the order in which events are processed by the bot API.
- static initialize_event_priorities() dict[Type[BotEvent], int][source]¶
Initializes the default event priorities map.
- Returns:
A map containing default priority values for all supported event types.
- Return type:
dict
- EVENT_PRIORITIES = {<class 'bot_api.events.bot_death_event.BotDeathEvent'>: 100, <class 'bot_api.events.bullet_fired_event.BulletFiredEvent'>: 60, <class 'bot_api.events.bullet_hit_bot_event.BulletHitBotEvent'>: 70, <class 'bot_api.events.bullet_hit_bullet_event.BulletHitBulletEvent'>: 80, <class 'bot_api.events.bullet_hit_wall_event.BulletHitWallEvent'>: 90, <class 'bot_api.events.custom_event.CustomEvent'>: 120, <class 'bot_api.events.death_event.DeathEvent'>: 10, <class 'bot_api.events.hit_bot_event.HitBotEvent'>: 30, <class 'bot_api.events.hit_by_bullet_event.HitByBulletEvent'>: 50, <class 'bot_api.events.hit_wall_event.HitWallEvent'>: 40, <class 'bot_api.events.scanned_bot_event.ScannedBotEvent'>: 20, <class 'bot_api.events.skipped_turn_event.SkippedTurnEvent'>: 140, <class 'bot_api.events.team_message_event.TeamMessageEvent'>: 110, <class 'bot_api.events.tick_event.TickEvent'>: 130, <class 'bot_api.events.won_round_event.WonRoundEvent'>: 150}¶
- static set_priority(event_class: Type[BotEvent] | None, priority: int) None[source]¶
Sets the priority for a specific event class.
- Parameters:
event_class (type) – The event class to set priority for.
priority (int) – The priority value to assign.
- Raises:
ValueError – If event_class is None.
- static get_priority(event_class: Type[BotEvent] | None) int[source]¶
Gets the priority for a specific event class.
- Parameters:
event_class (type) – The event class to get priority for.
- Returns:
The priority value for the specified event class.
- Return type:
int
- Raises:
ValueError – If event_class is None.
Exception – If no priority is defined for the event class.
bot_api.internal.event_queue module¶
- class EventQueue(base_bot_internals: BaseBotInternals, bot_event_handlers: BotEventHandlers)[source]¶
Bases:
objectQueue containing bot events that are being prioritized and dispatched to event handlers.
The event queue makes sure that the events are being processed in the right order based on event priority and age of the events. Old events that are no longer relevant will be removed from the queue.
- MAX_QUEUE_SIZE = 256¶
- MAX_EVENT_AGE = 2¶
- get_events(turn_number: int) list[BotEvent][source]¶
Returns a list containing all events in the queue.
- Parameters:
turn_number – Current turn number used for removing old events.
- Returns:
List of all events in the queue.
- set_current_event_interruptible(interruptible: bool) None[source]¶
Sets if the current event can be interrupted by new events with higher priority.
- Parameters:
interruptible – True if the current event can be interrupted; false otherwise.
- is_current_event_interruptible() bool[source]¶
Checks if the current event can be interrupted by new events with higher priority.
- Returns:
True if the current event can be interrupted; false otherwise.
- add_events_from_tick(event: TickEvent) None[source]¶
Adds standard events from a tick event, and custom events from conditions.
- Parameters:
event – The tick event containing the standard events to add.
bot_api.internal.graphics_state module¶
bot_api.internal.intent_validator module¶
bot_api.internal.internal_event_handlers module¶
Internal event handler support.
- class InternalEventHandlers[source]¶
Bases:
objectClass used for instant event handling only used for updating the state of the API internals.
- fire_event(event: EventABC) None[source]¶
Fire an event to its registered handler.
- Parameters:
event – The event to fire.
Note
If there is no registered event handler for the event type, the event is ignored.
bot_api.internal.json_util module¶
- class MessageEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶
Bases:
JSONEncoder- default(o: Any) Any[source]¶
Implement this method in a subclass such that it returns a serializable object for
o, or calls the base implementation (to raise aTypeError).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return super().default(o)
- __init__(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)¶
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float, bool or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an RecursionError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is
Noneand (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a
TypeError.
- encode(o)¶
Return a JSON string representation of a Python data structure.
>>> from json.encoder import JSONEncoder >>> JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'
- item_separator = ', '¶
- iterencode(o, _one_shot=False)¶
Encode the given object and yield each string representation as available.
For example:
for chunk in JSONEncoder().iterencode(bigobject): mysocket.write(chunk)
- key_separator = ': '¶
bot_api.internal.recording_text_writer module¶
RecordingTextWriter - Captures stdout/stderr output for sending to server. This matches the functionality of RecordingPrintStream (Java) and RecordingTextWriter (C#/.NET).
- class RecordingTextWriter(text_writer: TextIO)[source]¶
Bases:
objectA text writer wrapper that records all written text and forwards it to an underlying writer. Thread-safe for concurrent writes (e.g., from print statements in event handlers).
- __init__(text_writer: TextIO)[source]¶
Initialize the recording text writer.
- Parameters:
text_writer – The underlying text writer to forward output to (e.g., sys.stdout)
- write(text: str) int[source]¶
Write text to both the underlying writer and the recording buffer. Thread-safe.
- Parameters:
text – The text to write
- Returns:
The number of characters written
- read_next() str[source]¶
Read and clear the recorded output since the last read. Thread-safe.
- Returns:
The recorded output as a string
- property encoding: str¶
Return the encoding of the underlying writer.
- property errors¶
Return the error handling mode of the underlying writer.
bot_api.internal.stop_resume_listener_abs module¶
bot_api.internal.thread_interrupted_exception module¶
- exception ThreadInterruptedException[source]¶
Bases:
BaseExceptionException used for interrupting event handlers.
This exception is thrown to signal that the current event handler has been interrupted deliberately and processing should stop so another event can take place.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
bot_api.internal.websocket_handler module¶
- class WebSocketHandler(base_bot_internals: BaseBotInternals, server_url: str, server_secret: str | None, base_bot: BaseBotABC, bot_info: BotInfo, bot_event_handlers: BotEventHandlers, internal_event_handlers: InternalEventHandlers, closed_event: Event, event_queue: EventQueue)[source]¶
Bases:
objectWebsocket handler for Robocode Tank Royale Bot API that handles websocket connections and messages from the server.
- __init__(base_bot_internals: BaseBotInternals, server_url: str, server_secret: str | None, base_bot: BaseBotABC, bot_info: BotInfo, bot_event_handlers: BotEventHandlers, internal_event_handlers: InternalEventHandlers, closed_event: Event, event_queue: EventQueue)[source]¶
Initialize the websocket handler.
- async on_close(websocket: ClientConnection, code: int, reason: str) None[source]¶
Handle WebSocket close event.
- async handle_round_started(json_msg: Dict[Any, Any]) None[source]¶
Handle a round started event from the server.
- async handle_round_ended(json_msg: Dict[Any, Any])[source]¶
Handle a round ended event from the server.
- async handle_game_started(json_msg: Dict[Any, Any]) None[source]¶
Handle a game started event from the server.
- async handle_game_ended(json_msg: Dict[Any, Any]) None[source]¶
Handle a game ended event from the server.