Reference

class code_battles.CodeBattles[source]

Bases: Generic[GameStateType, APIImplementationType, APIType, PlayerRequestsType]

The base class for a Code Battles game.

You should subclass this class and override the following methods:

Then, bind your class to the React application by calling run_game() with an instance of your subclass.

player_names: List[str]

The name of the players. This is populated before any of the overridable methods run.

map: str

The name of the map. This is populated before any of the overridable methods run.

map_image: js.Image

The map image. This is populated before any of the overridable methods run.

canvas: GameCanvas

The game’s canvas. Useful for the render() method. This is populated before any of the overridable methods run, but it isn’t populated for background simulations, so you should only use it in render().

state: GameStateType

The current state of the game. You should modify this in apply_decisions().

player_requests: List[PlayerRequestsType]

The current requests set by the players. Should be read in make_decisions() (and probably serialized), and set by the API implementation.

random: Random

A pseudorandom generator that should be used for all randomness purposes (except make_decisions())

player_randoms: List[Random]

A pseudorandom generator that should be used for all randomness purposes in a player’s bot. Given to the bots as a global via configure_bot_globals().

make_decisions_random: Random

A pseudorandom generator that should be used for all randomness purposes in make_decisions().

background: bool

Whether the current simulation is occuring in the background (without UI).

console_visible: bool

Whether the console is visible, i.e. the current simulation is not in showcase mode.

verbose: bool

Whether the current simulation is verbose, i.e. should show alerts and play sounds.

step: int

The current step of the simulation. Automatically increments after each apply_decisions().

active_players: List[int]

A list of the currently active player indices.

render() None[source]

You must override this method.

Use the canvas attribute to render the current state attribute.

make_decisions() bytes[source]

You must override this method.

Use the current state and bots to make decisions in order to reach the next state. You may use run_bot_method() to run a specific player’s method (for instance, run).

If you need any randomness, use make_decisions_random.

This function may take a lot of time to execute.

Warning

Do not call any other method other than run_bot_method() in here. This method will run in a web worker.

apply_decisions(decisions: bytes) None[source]

You must override this method.

Use the current state and the specified decisions to update the current state to be the next state.

This function should not take a lot of time.

Do NOT update step.

get_api() APIType[source]

You must override this method.

Returns the api module.

create_initial_state() GameStateType[source]

You must override this method.

Create the initial state for each simulation, to store in the state attribute.

create_initial_player_requests(player_index: int) PlayerRequestsType[source]

You must override this method.

Create the initial player requests for each simulation, to store in the player_requests attribute.

Should probably be empty.

create_api_implementation(player_index: int) APIImplementationType[source]

You must override this method.

Returns an implementation for the API’s Context class, which provides users with access to their corresponding element in player_requests.

You should also provide the API implementation with the state, but think about it as read-only.

Should perform checking.

async setup()[source]

Optional setup for the simulation.

For example, loading images using download_images() or fonts using load_font().

configure_extra_width() int[source]

Optionally add extra height to the right of the boards. 0 by default.

configure_extra_height() int[source]

Optionally add extra height below the boards. 0 by default.

configure_steps_per_second() int[source]

The number of wanted steps per second when running the simulation with UI. 20 by default.

configure_board_count() int[source]

The number of wanted boards for the game. 1 by default.

configure_map_image_url(map: str) str[source]

The URL containing the map image for the given map. By default, this takes the lowercase, replaces spaces with _ and loads from /images/maps which is stored in public/images/maps in a project.

configure_sound_url(name: str) str[source]

The URL containing the sound for the given name. By default, this takes the lowercase, replaces spaces with _ and loads from /sounds which is stored in public/sounds in a project.

configure_bot_base_class_name() str[source]

A bot’s base class name. CodeBattlesBot by default.

configure_render_rate(playback_speed: float) int[source]

The amount of frames to simulate before each render.

For games with an intensive render method, this is useful for higher playback speeds.

configure_bot_globals(player_index: int) Dict[str, Any][source]

Configure additional available global items, such as libraries from the Python standard library, bots can use.

By default, this is math, time and random, where random is the corresponding player_randoms.

Warning

Bots will also have api, context, player_api, and the bot base class name (CodeBattlesBot by default) available as part of the globals, alongside everything in api.

Any additional imports will be stripped (not as a security mechanism).

configure_version() str[source]

Configure the version of the game, which is stored in the simulation files.

download_image(url: str) Future[js.Image][source]
download_images(sources: List[Tuple[str, str]]) Future[Dict[str, js.Image]][source]
Parameters:

sources – A list of (image_name, image_url) to download.

Returns:

A future which can be await’d containing a dictionary mapping each image_name to its loaded image.

load_font(name: str, url: str) None[source]

Loads the font from the specified url as the specified name.

run_bot_method(player_index: int, method_name: str)[source]

Runs the specifid method of the given player.

Upon exception, shows an alert (does not terminate the bot).

eliminate_player(player_index: int, reason='')[source]

Eliminate the specified player for the specified reason from the simulation.

log(text: str, player_index: int | None = None, color='white')[source]

Logs the given entry with the given color.

For game-global log entries (not coming from a specific player), don’t specify a player_index.

alert(title: str, alert: str, color: str, icon: str, limit_time: int = 5000, is_code=True)[source]

Displays the given alert in the game UI.

play_sound(sound: str, force=False)[source]

Plays the given sound, from the URL given by configure_sound_url().

If force is set, will play the sound even if the simulation is not verbose.

pause()[source]

Pauses the current simulation. Useful for letting bots insert breakpoints wherever they wish.

Important: call this method only from the make_decisions() method.

property time: str

The current step of the simulation, as a string with justification to fill 5 characters.

property over: bool

Whether there is only one remaining player.

class code_battles.GameCanvas(canvas: js.Element, player_count: int, map_image: js.Image, max_width: int, max_height: int, extra_width: int, extra_height: int)[source]

Bases: object

A nice wrapper around HTML Canvas for drawing map-based multiplayer games.

draw_element(image: js.Image, x: int, y: int, width: int, board_index=0, direction: float | None = None, alignment=Alignment.CENTER)[source]

Draws the given image on the specified board.

Scaled to fit width in map pixels, be on position (x, y) in map pixels and face direction where 0 is no rotation and the direction is clockwise positive.

draw_text(text: str, x: int, y: int, color='black', board_index=0, text_size=15, font='')[source]

Draws the given text in the given coordinates (in map pixels).

draw_line(start_x: int, start_y: int, end_x: int, end_y: int, stroke='black', stroke_width=10, board_index=0)[source]

Draws a line between the given (start_x, start_y) and (end_x, end_y) coordinates (in map pixels) with the given stroke.

draw_rectangle(start_x: int, start_y: int, width: int, height: int, fill='black', stroke='transparent', stroke_width=2, board_index=0)[source]

Draws the given rectangle with the top-left corner at (start_x, start_y) (in map pixels) and with the specified width and height (in map pixels) with the given stroke and fill.

draw_circle(x: int, y: int, radius: float, fill='black', stroke='transparent', stroke_width=2, board_index=0)[source]

Draws the given circle (with the given stroke and fill) in the given coordinates and with the given radius (in map pixels).

clear()[source]

Clears the canvas and re-draws the players’ maps.

property total_width: float

The total width of the canvas (in map pixels).

class code_battles.Alignment(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

CENTER = 0
TOP_LEFT = 1
code_battles.run_game(battles: CodeBattles)[source]

Binds the given code battles instance to the React code to enable all simulations.