API

The Rust SDK

Everything your bot can call, phase by phase, with the bytecode each call costs. The snippets come from one small bot that compiles and plays; the whole file is at the end.

On this page

The Bytecode column shows what each call costs on top of its instructions.

01How your bot runs

A bot is a Rust library crate built as a cdylib for wasm32-unknown-unknown. It depends on clashcode-sdk (in the starter bot), implements the Bot trait and names its type once with entry!, which exports the functions the engine calls.

rust · the trait and the macro
// clashcode_sdk (lib.rs)
pub trait Bot: Default {
    fn build(&mut self) {}
    fn draft(&mut self) {}
    fn turn(&mut self, robot: u32, kind: u32);
}

#[macro_export]
macro_rules! entry { ($bot:ty) => { /* exports cc_abi_version, cc_build, cc_draft, cc_turn */ } }
Entry points
Bot methodExportCalledBytecode budget
build(&mut self)cc_buildonce per match, to place your base200,000
draft(&mut self)cc_draftonce per match, to buy troops and spells20,000
turn(&mut self, robot, kind)cc_turnyour commander, every round of your raid10,000
turn(&mut self, robot, kind)cc_turneach of your troops, and each of your defenses while your base is raided, every round2,500

One instance per robot. The engine loads a fresh copy of your module for each robot: one planner that runs build and then draft (so the draft can see what the build left in self), one commander, one per troop and one per defense building. Fields and statics are never shared between them; teammates talk through the shared array. Your Default runs inside the first call of each instance and is charged to it.

Who is acting. robot is the robot's id (the same as get_id()). kind is 0 for the commander, the RobotType index for a troop, and 32 plus the BuildingType index for a defense. Decode it with Robot::from_kind, which hands you the right controller:

rust · clashcode_sdk::game
// clashcode_sdk::game
pub enum Robot {
    Commander(CommanderRc),
    Troop(TroopRc),
    Defense(DefenseRc),
}

impl Robot {
    pub fn from_kind(kind: u32) -> Option<Robot>;
}

The controllers BuildRc, DraftRc and CommanderRc are unit structs, so you can also write BuildRc.get_map_width() anywhere in the right phase. A call that does not belong to the current phase ends the turn.

02A skeleton

The shape every bot shares: two phase methods and one turn that splits by robot. The functions it calls are the examples in the sections below.

rust · bots/mybot/src/lib.rs
use clashcode_sdk::game::*;
use clashcode_sdk::{Bot, entry};

#[derive(Default)]
struct MyBot {
    /// Turns this robot has played. Every robot has its own instance, so its own count.
    turns: u32,
}

impl Bot for MyBot {
    fn build(&mut self) {
        place_base(&BuildRc);
    }
    fn draft(&mut self) {
        buy_army(&DraftRc);
    }
    fn turn(&mut self, _robot: u32, kind: u32) {
        self.turns += 1;
        match Robot::from_kind(kind) {
            Some(Robot::Commander(rc)) => command(&rc, self.turns),
            Some(Robot::Troop(rc)) => troop(&rc),
            Some(Robot::Defense(rc)) => defend(&rc),
            None => {}
        }
    }
}

entry!(MyBot);

Its Cargo.toml, inside the starter workspace (which sets the release profile and the linker flag the sandbox needs):

toml · bots/mybot/Cargo.toml
[package]
name = "mybot"
version.workspace = true
edition.workspace = true

[lib]
crate-type = ["cdylib"]

[dependencies]
clashcode-sdk.workspace = true

03Results and errors

Every action returns a GameResult. Err(GameActionError) means the game refused it; the error carries no detail, so call the matching can_* check first. A refused action still pays its bytecode cost.

rust
// clashcode_sdk::game
pub struct GameActionError;
pub type GameResult<T> = Result<T, GameActionError>;
rust · using ? in a helper
/// Two walls side by side, or neither call after the first refusal.
fn wall_pair(rc: &BuildRc, at: MapLocation) -> GameResult<()> {
    rc.place(BuildingType::Wall, at)?; // a refused place still costs its bytecode
    rc.place(BuildingType::Wall, at.translate(1, 0))?;
    Ok(())
}

A panic, a wasm trap or running out of bytecode ends that one call. Actions already taken stand, the robot plays again next round, and the instance keeps its memory, even if it was halfway through changing it.

04Build: BuildRc

Place the fixed inventory on your copy of the map. You never see the enemy base. Locations are the bottom-left tile of the building. Anything you do not place is lost, except the keep: if it is missing the engine puts it at the free spot nearest the centre. See the build rules.

BuildRc calls
CallWhat it doesBytecode
get_map_width(&self) -> i32
get_map_height(&self) -> i32
Map size in tiles. (0, 0) is the bottom-left corner.
get_inventory(&self) -> [i32; BuildingType::COUNT]Buildings and traps still to place, indexed by kind as usize.
sense_rock(&self, loc: MapLocation) -> boolTrue on a rock tile.
is_buildable(&self, loc: MapLocation) -> boolTrue if one tile could take a building now: on the map, outside the deploy zone, no rock, nothing placed there.
can_place(&self, kind: BuildingType, loc: MapLocation) -> boolTrue if kind is left in the inventory and its whole footprint is buildable.
place(&self, kind: BuildingType, loc: MapLocation) -> GameResult<()>Places one building or trap.5
rust · keep in the middle, the rest around it
/// Keep in the middle, then every other building on the free tiles closest to it.
fn place_base(rc: &BuildRc) {
    let (w, h) = (rc.get_map_width(), rc.get_map_height());
    let centre = MapLocation::new(w / 2 - 1, h / 2 - 1);
    if rc.can_place(BuildingType::Keep, centre) {
        let _ = rc.place(BuildingType::Keep, centre);
    }
    // free tiles in a 21x21 square round the keep, nearest first
    let (cx, cy) = (centre.x, centre.y);
    let mut tiles: Vec<MapLocation> = (cx - 10..=cx + 10)
        .flat_map(|x| (cy - 10..=cy + 10).map(move |y| MapLocation::new(x, y)))
        .filter(|&p| rc.is_buildable(p))
        .collect();
    tiles.sort_by_cached_key(|p| p.distance_squared_to(centre));
    let left = rc.get_inventory(); // buildings still to place, by BuildingType index
    for kind in BuildingType::ALL {
        let mut n = left[kind as usize];
        for &p in &tiles {
            if n == 0 {
                break;
            }
            if rc.can_place(kind, p) && rc.place(kind, p).is_ok() {
                n -= 1;
            }
        }
    }
}

Scanning every tile of a 64 by 64 map and sorting them costs more than the build budget, which is why the example only looks at a 21 by 21 window round the keep.

05Draft: DraftRc

Spend 1,200 gold on troops and spells, still blind. Unspent gold is lost. can_buy and buy take a RobotType or a SpellType (both convert into Kind) and a count.

DraftRc calls
CallWhat it doesBytecode
get_gold(&self) -> i32Gold left.
get_army(&self) -> [i32; RobotType::COUNT]Troops bought so far, by RobotType index.
get_spells(&self) -> [i32; SpellType::COUNT]Spells bought so far.
can_buy(&self, kind: impl Into<Kind>, n: i32) -> boolTrue if n is at least 1 and you can afford n of kind.
buy(&self, kind: impl Into<Kind>, n: i32) -> GameResult<()>Buys n at once; the cost is per call, not per unit.2
rust · a mixed army
/// A tank, a front line, some range, two scorches, and gliders with whatever gold is left.
fn buy_army(rc: &DraftRc) {
    let _ = rc.buy(RobotType::Colossus, 1);
    let _ = rc.buy(RobotType::Brute, 4);
    let _ = rc.buy(RobotType::Ranger, 4);
    let _ = rc.buy(SpellType::Scorch, 2);
    let _ = rc.buy(SpellType::Mend, 1);
    while rc.can_buy(RobotType::Glider, 1) {
        let _ = rc.buy(RobotType::Glider, 1);
    }
    print(&format!("gold left: {}", rc.get_gold()));
}

06Every raid robot: RaidRc

CommanderRc, TroopRc and DefenseRc all implement the RaidRc trait, which use clashcode_sdk::game::* brings into scope.

RaidRc calls
CallWhat it doesBytecode
get_id(&self) -> u32This robot's id.
get_round_num(&self) -> i32The current round of this raid, counting from 0.
get_team(&self) -> TeamTeam::A or Team::B.
get_map_width(&self) -> i32
get_map_height(&self) -> i32
Map size in tiles.
on_the_map(&self, loc: MapLocation) -> boolTrue inside the map.
sense_rock(&self, loc: MapLocation) -> boolTrue on a rock tile.
read_shared_array(&self, i: i32) -> GameResult<i32>Slot i of your side's shared array (64 slots). Err outside it.1
write_shared_array(&self, i: i32, v: i32) -> GameResult<()>Writes 0 to 65,535; anything else is refused. Attackers and defenders have separate arrays.1
set_indicator_string(&self, s: &str)A label shown on this robot in the replay; it stays until you set another. The first 400 bytes are kept.
set_indicator_dot(&self, loc: MapLocation, r: i32, g: i32, b: i32)A dot on a tile, for this round only. Colour values are clamped to 0 to 255.
set_indicator_line(&self, a: MapLocation, b: MapLocation, r: i32, g: i32, bl: i32)A line between two tiles, for this round only.

07Commander: CommanderRc

Your commander stays off the map and runs first every round of your raid. It lands up to 3 troops per round on deploy-zone tiles and casts up to 1 spell per round anywhere. It sees enemy buildings only on explored tiles (fog of war).

CommanderRc calls
CallWhat it doesBytecode
get_type(&self) -> RobotTypeAlways RobotType::Commander.
get_reserve(&self) -> [i32; RobotType::COUNT]Troops not yet deployed.
get_deploys_left(&self) -> i32Deploys left this round.
get_destruction_pm(&self) -> i32Destruction so far, 0 to 1000 (per mille).
get_destruction(&self) -> f64The same as a percent with one decimal.
is_deploy_zone(&self, loc: MapLocation) -> boolTrue on a deploy-zone tile.
can_deploy(&self, kind: RobotType, loc: MapLocation) -> boolTrue if kind is in reserve, a deploy is left this round and loc is a deploy-zone tile (not a rock, unless the troop flies).
deploy(&self, kind: RobotType, loc: MapLocation) -> GameResult<u32>Lands one troop and returns its id. It takes its first turn this same round, after the commander.10
get_spells(&self) -> [i32; SpellType::COUNT]Spells left to cast.
get_spells_left(&self) -> i32Casts left this round.
can_cast(&self, spell: SpellType, loc: MapLocation) -> boolTrue if you hold spell, a cast is left this round and loc is on the map.
cast(&self, spell: SpellType, loc: MapLocation) -> GameResult<()>Casts centred on loc. Spells also explore the tiles they cover.10
sense_nearby_buildings(&self) -> Vec<BuildingInfo>Living enemy buildings with at least one explored tile. Hidden traps never appear.10
is_explored(&self, loc: MapLocation) -> boolTrue if the tile is explored.2
sense_nearby_robots(&self) -> Vec<RobotInfo>Your troops on the map.10
rust · deploy, report the keep, scorch a tower
/// Shared array slot 0: the enemy keep as x * 256 + y + 1 (0 = not found yet).
const KEEP_SLOT: i32 = 0;

fn command(rc: &CommanderRc, turns: u32) {
    // deploy along the bottom edge until this round's deploys are used up
    let reserve = rc.get_reserve();
    for x in 0..rc.get_map_width() {
        let at = MapLocation::new(x, 0);
        for kind in RobotType::ALL {
            if reserve[kind as usize] > 0 && rc.can_deploy(kind, at) {
                let _ = rc.deploy(kind, at);
            }
        }
        if rc.get_deploys_left() == 0 {
            break;
        }
    }
    // the scouting report: enemy buildings on explored tiles
    let seen = rc.sense_nearby_buildings();
    if let Some(k) = seen.iter().find(|b| b.kind == BuildingType::Keep) {
        let _ = rc.write_shared_array(KEEP_SLOT, k.location.x * 256 + k.location.y + 1);
    }
    // one spell a round: scorch the first defense in sight
    if let Some(d) = seen.iter().find(|b| b.kind.is_defense())
        && rc.can_cast(SpellType::Scorch, d.location)
    {
        let _ = rc.cast(SpellType::Scorch, d.location);
    }
    rc.set_indicator_string(&format!("turn {turns}: {:.1}%", rc.get_destruction()));
}

The commander runs before the troops in the same round, so the keep location it writes is there for them to read.

08Troops: TroopRc

Each deployed troop runs in id order after the commander. A troop sees buildings within its vision (r² 20). Ranges are squared distances, measured to the tile you aim at, so aim at the building tile nearest to you. move is a Rust keyword: call it as rc.r#move(d).

TroopRc calls
CallWhat it doesBytecode
get_type(&self) -> RobotTypeThis troop's type.
get_location(&self) -> MapLocationIts tile.
get_health(&self) -> i32Health left.
is_movement_ready(&self) -> bool
is_action_ready(&self) -> bool
True when that cooldown is 0.
get_movement_cooldown_turns(&self) -> i32
get_action_cooldown_turns(&self) -> i32
Rounds until it can move or act again.
is_furious(&self) -> boolTrue while a fury spell is on it.
get_vision_radius_squared(&self) -> i32Its vision r².
can_sense_location(&self, loc: MapLocation) -> boolTrue if loc is within vision.
sense_nearby_buildings(&self, radius_sq: i32) -> Vec<BuildingInfo>Visible enemy buildings within radius_sq; -1 means full vision. No hidden traps.10
sense_building_at(&self, loc: MapLocation) -> Option<BuildingInfo>The building covering loc, if loc is in vision. Never a hidden trap.2
sense_nearby_robots(&self, radius_sq: i32) -> Vec<RobotInfo>Your other troops within radius_sq; -1 means full vision.10
sense_passable(&self, loc: MapLocation) -> boolTrue if loc is in vision and a ground troop could stand there: on the map, no rock, no living building.
can_move(&self, d: Direction) -> boolTrue if the movement cooldown is 0 and the next tile is open: on the map for flyers, passable for ground troops (a diagonal step also needs one of the two tiles beside it passable). Center is always false.
r#move(&self, d: Direction) -> GameResult<()>Steps one tile and starts the movement cooldown.5
can_attack(&self, loc: MapLocation) -> boolTrue if the action is ready, a living building covers loc and loc is within the troop's action r². Always false for sappers and menders.
attack(&self, loc: MapLocation) -> GameResult<()>Hits the building covering loc (any of its tiles). A mage also splashes every building near loc.5
can_mend(&self) -> bool
mend(&self) -> GameResult<()>
Menders only: restores health to every friendly troop within its radius, itself included.5
can_explode(&self) -> bool
explode(&self) -> GameResult<()>
Sappers only: damages every building within its radius, then the sapper dies.5
rust · attack the nearest building, else walk to the keep
/// The tile of `b` closest to `p`: range is measured to the tile you aim at.
fn nearest_tile(b: &BuildingInfo, p: MapLocation) -> MapLocation {
    MapLocation::new(
        p.x.clamp(b.location.x, b.location.x + b.size - 1),
        p.y.clamp(b.location.y, b.location.y + b.size - 1),
    )
}

fn troop(rc: &TroopRc) {
    let me = rc.get_location();
    let kind = rc.get_type();
    if kind == RobotType::Mender {
        if rc.can_mend() {
            let _ = rc.mend();
        }
        return;
    }
    // the nearest building in sight that is not a wall
    let target = rc
        .sense_nearby_buildings(-1)
        .into_iter()
        .filter(|b| b.kind != BuildingType::Wall)
        .min_by_key(|b| me.distance_squared_to(nearest_tile(b, me)));
    let goal = match target {
        Some(b) => {
            let aim = nearest_tile(&b, me);
            if kind == RobotType::Sapper {
                if me.distance_squared_to(aim) <= kind.action_radius_sq() && rc.can_explode() {
                    let _ = rc.explode();
                    return;
                }
            } else if rc.can_attack(aim) {
                let _ = rc.attack(aim);
                return;
            }
            aim
        }
        // nothing in sight: head for the keep the commander reported, or the middle
        None => match rc.read_shared_array(KEEP_SLOT) {
            Ok(v) if v > 0 => MapLocation::new((v - 1) / 256, (v - 1) % 256),
            _ => MapLocation::new(rc.get_map_width() / 2, rc.get_map_height() / 2),
        },
    };
    if rc.is_movement_ready() {
        let d = me.direction_to(goal);
        for d in [d, d.rotate_left(), d.rotate_right()] {
            if rc.can_move(d) {
                let _ = rc.r#move(d);
                return;
            }
        }
        // blocked: hit whatever stands in the way (usually a wall)
        let ahead = me.add(d);
        if rc.can_attack(ahead) {
            let _ = rc.attack(ahead);
        }
    }
}

09Defenses: DefenseRc

While your base is raided, each of your living defense buildings (bombard, longbow post, lobber, spire, arc pylon, ballista, flame tower) runs your code after the attacking troops, in id order, in every round that has living attackers on the map. A defense your code never fires does nothing. Traps need no code.

DefenseRc calls
CallWhat it doesBytecode
get_type(&self) -> BuildingTypeWhich defense this is.
get_location(&self) -> MapLocationIts tile.
get_health(&self) -> i32Health left.
is_action_ready(&self) -> boolTrue when its cooldown is 0.
sense_nearby_robots(&self, radius_sq: i32) -> Vec<RobotInfo>Enemy troops within radius_sq; -1 means its action radius.10
can_attack(&self, loc: MapLocation) -> boolTrue if loc is in range (and outside any minimum range), holds a troop it can hit, and it is ready.
attack(&self, loc: MapLocation) -> GameResult<()>Fires at the tile. Without splash it hits the lowest-id valid troop there.5
rust · shoot the weakest troop in range
/// Towers run the defending team's code: shoot the weakest troop in range.
fn defend(rc: &DefenseRc) {
    if !rc.is_action_ready() {
        return;
    }
    let enemies = rc.sense_nearby_robots(-1);
    if let Some(t) = enemies.iter().min_by_key(|t| t.health)
        && rc.can_attack(t.location)
    {
        let _ = rc.attack(t.location);
    }
}

10Types

Enums

RobotType, BuildingType, SpellType, Team and Direction all have ALL (every variant in index order), COUNT, name() (the upper-case name, such as "LONGBOW_POST") and from_index(i) -> Option<Self>. kind as usize indexes the count arrays.

Enum variants
EnumVariants, in index order
RobotTypeCommander (0, never on the map), Brute, Ranger, Sapper, Drake, Runner, Colossus, Catapult, Mage, Mender, Glider
BuildingTypeKeep, Bombard, LongbowPost, Lobber, Spire, ArcPylon, Ballista, FlameTower, Vault, Storehouse, Shack, Wall, then the hidden traps SpikeTrap, BlastCharge, SkyMine, TarPit
SpellTypeScorch, Bolt, Stasis, Mend, Fury
TeamA, B
DirectionNorth, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest, Center (clockwise, Center last)

Stats

Type stats are methods that read the game data, so they follow balance changes. The numbers are in the codex.

Stat methods
TypeMethods (all take self)
RobotTypecost, health, damage, wall_damage, action_radius_sq, movement_cooldown, action_cooldown, splash_radius_sq, mend (all i32); is_air (bool)
BuildingTypesize, health, count, action_radius_sq, min_radius_sq, damage, cooldown, splash_radius_sq (i32); hits_air, hits_ground, is_hidden, is_defense (bool)
SpellTypecost, radius_sq, damage, stun, mend (i32); fury (bool)
KindKind::Troop(RobotType) or Kind::Spell(SpellType); cost() -> i32. Both enums convert with .into().

Locations and records

Location helpers
ItemWhat it is
MapLocation { pub x: i32, pub y: i32 }A tile. (0, 0) is bottom-left and North is +y. MapLocation::new(x, y) is a const fn.
add(self, d: Direction) -> MapLocation
translate(self, dx: i32, dy: i32) -> MapLocation
One step in a direction; any offset.
distance_squared_to(self, o: MapLocation) -> i32dx² + dy², the measure every radius uses.
is_adjacent_to(self, o: MapLocation) -> boolTrue for the 8 neighbours.
direction_to(self, o: MapLocation) -> DirectionThe step that heads towards o; Center if equal.
Direction: dx(), dy(), rotate_left(), rotate_right(), opposite(), Direction::all_directions() -> [Direction; 8]Turns are 45 degrees; all_directions leaves out Center.
BuildingInfo { id: u32, kind: BuildingType, location: MapLocation, size: i32, health: i32 }What sensing returns for a building. location is its bottom-left tile.
RobotInfo { id: u32, kind: RobotType, location: MapLocation, health: i32 }What sensing returns for a troop.

These helpers run inside your module, so they cost only their instructions.

rust · a tour of the types
fn types_tour(rc: &DraftRc) {
    let a = MapLocation::new(3, 4);
    let b = a.add(Direction::NorthEast).translate(2, 0); // (6, 5)
    let d2 = a.distance_squared_to(b); // 9 + 1 = 10
    let dir = a.direction_to(b); // NorthEast
    // type stats come from the game data, so they follow balance changes
    let tank = RobotType::ALL
        .into_iter()
        .max_by_key(|t| t.health())
        .unwrap();
    let anti_air = BuildingType::ALL.iter().filter(|b| b.hits_air()).count();
    // count arrays are indexed by the enum
    let gliders = rc.get_army()[RobotType::Glider as usize];
    print(&format!("{d2} {dir:?} {} {anti_air} {gliders}", tank.name()));
}

Run in a draft, this prints 10 NorthEast COLOSSUS 4 0.

11Budget and debugging

Clock and debugging calls
CallWhat it does
Clock::get_bytecodes_left() -> i64Budget left in this call, in wasm fuel.
Clock::get_budget_limit() -> i64This call's whole budget, in fuel.
Clock::get_bytecode_num() -> i64Fuel used so far.
rng_next() -> u64The next number of this call's random stream. Seeded by the match, so replays repeat exactly.
print(s: &str)One line in this robot's log in the replay. The first 8 lines of 160 characters per robot per round are kept; each kept byte costs 1 fuel.
clashcode_sdk::log(msg: &str)The raw log call under print, without the newline.

Budgets are metered in fuel, about one unit per wasm instruction. A game call costs 1 fuel plus its bytecode cost times 6, and the replay shows what each robot used converted back to bytecode. The full table is in the rules.

rust · stop early, draw in the replay
/// Look at the 8 tiles round this troop, but stop once half the budget is gone.
fn count_rocks(rc: &TroopRc) -> u32 {
    let half = Clock::get_budget_limit() / 2;
    let me = rc.get_location();
    let mut rocks = 0;
    for d in Direction::all_directions() {
        if Clock::get_bytecodes_left() < half {
            print("half the budget used, stopping");
            break;
        }
        let p = me.add(d);
        if rc.on_the_map(p) && rc.sense_rock(p) {
            rocks += 1;
            rc.set_indicator_dot(p, 255, 0, 0); // a red dot in the replay, this round only
        }
    }
    if rng_next().is_multiple_of(10) {
        rc.set_indicator_line(me, MapLocation::new(0, 0), 0, 255, 255);
    }
    rocks
}

12The full example

All of the snippets above as one file, about 170 lines. It builds clean under clippy and plays every map in the pool; on the test map pillars it beats the engine's built-in greedy bot. It is a starting point, not a strong bot: read the house bots for better ideas.

Show bots/mybot/src/lib.rs
rust · bots/mybot/src/lib.rs
use clashcode_sdk::game::*;
use clashcode_sdk::{Bot, entry};

#[derive(Default)]
struct MyBot {
    /// Turns this robot has played. Every robot has its own instance, so its own count.
    turns: u32,
}

impl Bot for MyBot {
    fn build(&mut self) {
        place_base(&BuildRc);
    }
    fn draft(&mut self) {
        buy_army(&DraftRc);
    }
    fn turn(&mut self, _robot: u32, kind: u32) {
        self.turns += 1;
        match Robot::from_kind(kind) {
            Some(Robot::Commander(rc)) => command(&rc, self.turns),
            Some(Robot::Troop(rc)) => troop(&rc),
            Some(Robot::Defense(rc)) => defend(&rc),
            None => {}
        }
    }
}

entry!(MyBot);

/// Keep in the middle, then every other building on the free tiles closest to it.
fn place_base(rc: &BuildRc) {
    let (w, h) = (rc.get_map_width(), rc.get_map_height());
    let centre = MapLocation::new(w / 2 - 1, h / 2 - 1);
    if rc.can_place(BuildingType::Keep, centre) {
        let _ = rc.place(BuildingType::Keep, centre);
    }
    // free tiles in a 21x21 square round the keep, nearest first
    let (cx, cy) = (centre.x, centre.y);
    let mut tiles: Vec<MapLocation> = (cx - 10..=cx + 10)
        .flat_map(|x| (cy - 10..=cy + 10).map(move |y| MapLocation::new(x, y)))
        .filter(|&p| rc.is_buildable(p))
        .collect();
    tiles.sort_by_cached_key(|p| p.distance_squared_to(centre));
    let left = rc.get_inventory(); // buildings still to place, by BuildingType index
    for kind in BuildingType::ALL {
        let mut n = left[kind as usize];
        for &p in &tiles {
            if n == 0 {
                break;
            }
            if rc.can_place(kind, p) && rc.place(kind, p).is_ok() {
                n -= 1;
            }
        }
    }
}

/// A tank, a front line, some range, two scorches, and gliders with whatever gold is left.
fn buy_army(rc: &DraftRc) {
    let _ = rc.buy(RobotType::Colossus, 1);
    let _ = rc.buy(RobotType::Brute, 4);
    let _ = rc.buy(RobotType::Ranger, 4);
    let _ = rc.buy(SpellType::Scorch, 2);
    let _ = rc.buy(SpellType::Mend, 1);
    while rc.can_buy(RobotType::Glider, 1) {
        let _ = rc.buy(RobotType::Glider, 1);
    }
    print(&format!("gold left: {}", rc.get_gold()));
}

/// Shared array slot 0: the enemy keep as x * 256 + y + 1 (0 = not found yet).
const KEEP_SLOT: i32 = 0;

fn command(rc: &CommanderRc, turns: u32) {
    // deploy along the bottom edge until this round's deploys are used up
    let reserve = rc.get_reserve();
    for x in 0..rc.get_map_width() {
        let at = MapLocation::new(x, 0);
        for kind in RobotType::ALL {
            if reserve[kind as usize] > 0 && rc.can_deploy(kind, at) {
                let _ = rc.deploy(kind, at);
            }
        }
        if rc.get_deploys_left() == 0 {
            break;
        }
    }
    // the scouting report: enemy buildings on explored tiles
    let seen = rc.sense_nearby_buildings();
    if let Some(k) = seen.iter().find(|b| b.kind == BuildingType::Keep) {
        let _ = rc.write_shared_array(KEEP_SLOT, k.location.x * 256 + k.location.y + 1);
    }
    // one spell a round: scorch the first defense in sight
    if let Some(d) = seen.iter().find(|b| b.kind.is_defense())
        && rc.can_cast(SpellType::Scorch, d.location)
    {
        let _ = rc.cast(SpellType::Scorch, d.location);
    }
    rc.set_indicator_string(&format!("turn {turns}: {:.1}%", rc.get_destruction()));
}

/// The tile of `b` closest to `p`: range is measured to the tile you aim at.
fn nearest_tile(b: &BuildingInfo, p: MapLocation) -> MapLocation {
    MapLocation::new(
        p.x.clamp(b.location.x, b.location.x + b.size - 1),
        p.y.clamp(b.location.y, b.location.y + b.size - 1),
    )
}

fn troop(rc: &TroopRc) {
    let me = rc.get_location();
    let kind = rc.get_type();
    if kind == RobotType::Mender {
        if rc.can_mend() {
            let _ = rc.mend();
        }
        return;
    }
    // the nearest building in sight that is not a wall
    let target = rc
        .sense_nearby_buildings(-1)
        .into_iter()
        .filter(|b| b.kind != BuildingType::Wall)
        .min_by_key(|b| me.distance_squared_to(nearest_tile(b, me)));
    let goal = match target {
        Some(b) => {
            let aim = nearest_tile(&b, me);
            if kind == RobotType::Sapper {
                if me.distance_squared_to(aim) <= kind.action_radius_sq() && rc.can_explode() {
                    let _ = rc.explode();
                    return;
                }
            } else if rc.can_attack(aim) {
                let _ = rc.attack(aim);
                return;
            }
            aim
        }
        // nothing in sight: head for the keep the commander reported, or the middle
        None => match rc.read_shared_array(KEEP_SLOT) {
            Ok(v) if v > 0 => MapLocation::new((v - 1) / 256, (v - 1) % 256),
            _ => MapLocation::new(rc.get_map_width() / 2, rc.get_map_height() / 2),
        },
    };
    if rc.is_movement_ready() {
        let d = me.direction_to(goal);
        for d in [d, d.rotate_left(), d.rotate_right()] {
            if rc.can_move(d) {
                let _ = rc.r#move(d);
                return;
            }
        }
        // blocked: hit whatever stands in the way (usually a wall)
        let ahead = me.add(d);
        if rc.can_attack(ahead) {
            let _ = rc.attack(ahead);
        }
    }
}

/// Towers run the defending team's code: shoot the weakest troop in range.
fn defend(rc: &DefenseRc) {
    if !rc.is_action_ready() {
        return;
    }
    let enemies = rc.sense_nearby_robots(-1);
    if let Some(t) = enemies.iter().min_by_key(|t| t.health)
        && rc.can_attack(t.location)
    {
        let _ = rc.attack(t.location);
    }
}