# Worked examples

Copy one full script at a time into **PHP source** and use the matching loadout in mount order. Each example is a starting point you can test in a few minutes and then adapt.

- **Rail Scout** trades sustained fire for heavier hits and leads moving targets.
- **Bastion Runner** uses an energy weapon so its ammo is available for repairs. A heavier chassis trades speed for durability and another mount.
- **Lane Partner** repositions when an ally blocks a shot. It depends on seeing the firing lane and responding to teammates' signals.

Start with [the first-bot walkthrough](getting-started.md) if you want a shorter script. Use the [decision trace walkthrough](testing.md) and the [PHP reference](php-reference.md) to understand unfamiliar calls.

## Rail Scout

**Loadout** Lightweight, **Tortoise · Armor** (`light-armor`), then Railgun (`railgun`) and Shield Generator (`shield`) in that order.

**Try it** Choose **Solo combat**, seed **77**, and **Basic Bot**. The Rail Scout closes until its shot has a useful hit probability, leads moving contacts, and keeps tracking during cooldown. The same code can fight a moving target in a regular battle with a larger arena. A useful test is to compare launch counts and damage in two runs at the same seed after changing the preferred range.

```php
<?php
declare(strict_types=1);

// Railgun is slot 0. Keep the Shield Generator in slot 1.
function railPoint(array $enemy, array $battle): array
{
    // Movement resolves before launching. Predict one tick before solving flight time.
    $vx = $enemy['velocity']['x'] ?? 0.0;
    $vz = $enemy['velocity']['z'] ?? 0.0;
    $dt = $battle['tickDuration'];
    $x = $enemy['x'] + $vx * $dt;
    $z = $enemy['z'] + $vz * $dt;
    $intercept = $pilot->estimateIntercept(0, $x, $z, $vx, $vz);
    $bounds = $battle['movementBounds'];
    return [
        'x' => max($bounds['minX'], min($bounds['maxX'], $intercept['x'] ?? $x)),
        'z' => max($bounds['minZ'], min($bounds['maxZ'], $intercept['z'] ?? $z)),
    ];
}

$self = $pilot->selfState();
if ($self['stunRemaining'] > 0) {
    return;
}
$enemy = $pilot->scan()['enemies'][0] ?? null;
$mount = $pilot->mountState(0);
$shield = $pilot->mountState(1);
$bank = $self['resources'];
$missing = $bank['shield']['max'] - $bank['shield']['current'];
$charge = $missing > ($shield['enabled'] ? 0.25 : 8.0)
    && $bank['energy']['current'] > $mount['energyCost'] + ($shield['enabled'] ? 4.0 : 12.0);
if ($shield['ready'] && $shield['enabled'] !== $charge) {
    $pilot->toggle(1, $charge);
}
if ($enemy === null) {
    if ($mount['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    $pilot->moveTo(0.0, 0.0);
    return;
}

$battle = $pilot->battleState();
$range = min(42.0, $mount['effectiveRange']);
$point = railPoint($enemy, $battle);
$shot = $pilot->estimateShot(0, $point['x'], $point['z']);
if ($enemy['distance'] > $range) {
    $pilot->moveTo($enemy['x'], $enemy['z']);
}
if (!($shot['inRange'] ?? false)) {
    if ($mount['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    return;
}
if ($enemy['distance'] <= $range && $mount['ready'] && $shot['aimSeconds'] <= $battle['tickDuration']) {
    $risk = $pilot->estimateFriendlyFire(0, $point['x'], $point['z']);
    if (!$battle['friendlyFire'] || ($risk['atRisk'] ?? null) === []) {
        $pilot->fire(0, $point['x'], $point['z']);
        return;
    }
}
$pilot->aim(0, $point['x'], $point['z']);
```

## Bastion Runner

**Loadout** Heavyweight, **Rampart · Armor** (`heavy-armor`), then Beam Laser (`beam-laser`), Shield Generator (`shield`), Nanobot Repair System (`repair`), and Energy Core Optimizer (`optimizer`).

**Try it** Choose **Solo combat**, seed **101**, and **Field Technician**. Watch the trace for shield or repair activation after damage, then inspect the energy and hull pickup routes. Compare the same matchup under **Practice battles** with pickups disabled to see how recovery affects the outcome.

```php
<?php
declare(strict_types=1);

function useRecovery(int $slot, bool $wanted, float $surplus): float
{
    $mount = $pilot->mountState($slot);
    if ($mount['ready'] && $mount['enabled'] !== $wanted
        && (!$wanted || $surplus >= $mount['energyCost'])) {
        if ($pilot->toggle($slot, $wanted) && $wanted) {
            return $surplus - $mount['energyCost'];
        }
    }
    return $surplus;
}

function reachablePickup(array $pickup, array $resources, array $battle, float $speed): bool
{
    $reserve = $resources[$pickup['kind']];
    $gain = min($pickup['amount'], $reserve['max'] - $reserve['current']);
    $move = $pilot->estimateMove($pickup['x'], $pickup['z']);
    if ($move === null || $speed <= 0.0 || $gain < 9.0) {
        return false;
    }
    $radius = $battle['pickupRules']['collectionRadius'];
    $eta = max(0.0, $move['totalSeconds'] - $radius / $speed);
    return $eta + 0.15 < $pickup['secondsRemaining'] && $eta <= 5.0;
}

$self = $pilot->selfState();
if ($self['stunRemaining'] > 0) {
    return;
}
$scan = $pilot->scan();
$battle = $pilot->battleState();
$bank = $self['resources'];
$laser = $pilot->mountState(0);
$shield = $pilot->mountState(1);
$repair = $pilot->mountState(2);
$enemy = $scan['enemies'][0] ?? null;
$surplus = max(0.0, $bank['energy']['current'] - $laser['energyCost'] - 4.0);

// Use separate start and stop thresholds for stable equipment decisions.
$shieldLoss = $bank['shield']['max'] - $bank['shield']['current'];
$wantShield = $shieldLoss > ($shield['enabled'] ? 0.25 : 9.0)
    && $surplus > ($shield['enabled'] ? 3.0 : 10.0);
$surplus = useRecovery(1, $wantShield, $surplus);
$hullLoss = $bank['hull']['max'] - $bank['hull']['current'];
$wantRepair = $battle['phase'] === 'normal'
    && $hullLoss > ($repair['enabled'] ? 0.25 : 12.0)
    && $bank['ammo']['current'] >= 4.0
    && $surplus > ($repair['enabled'] ? 8.0 : 14.0);
useRecovery(2, $wantRepair, $surplus);

$fired = false;
if ($enemy !== null && $enemy['distance'] <= $laser['range']) {
    $x = $enemy['x'] + ($enemy['velocity']['x'] ?? 0.0) * $battle['tickDuration'];
    $z = $enemy['z'] + ($enemy['velocity']['z'] ?? 0.0) * $battle['tickDuration'];
    $shot = $pilot->estimateShot(0, $x, $z);
    if ($shot['inRange'] ?? false) {
        $risk = $pilot->estimateFriendlyFire(0, $x, $z);
        $safe = !$battle['friendlyFire'] || ($risk['atRisk'] ?? null) === [];
        if ($safe && $laser['ready'] && $shot['aimSeconds'] <= $battle['tickDuration']) {
            $fired = $pilot->fire(0, $x, $z);
        } else {
            $pilot->aim(0, $x, $z);
        }
    }
}

if ($fired) {
    return;
}
$pickup = $scan['pickups'][0] ?? null;
if ($pickup !== null && reachablePickup($pickup, $bank, $battle, $self['driveSpeed'])) {
    $pilot->moveTo($pickup['x'], $pickup['z']);
} elseif ($enemy === null) {
    $pilot->moveTo(0.0, 0.0);
} elseif ($enemy['distance'] > $laser['effectiveRange'] - 4.0) {
    $pilot->moveTo($enemy['x'], $enemy['z']);
}
```

## Lane Partner

**Loadout** Mediumweight, **Relay · Energy** (`medium-energy`), then Pulse Laser (`pulse-laser`), Shield Generator (`shield`), and Heavy Armor (`armor`).

**Try it** Select **Team communication**, seed **77**, and the default Practice Partner. The partner sends a help request, and the bot acknowledges it once on its delivery tick. Then use **Allied fire risk** with the same seed and the default roster to watch the bot reposition when its ally is in the candidate shot. To see a claim attempt followed by a pickup, select **Contested pickups**, seed **101**, and set the first opponent to **Benchmark Mediumweight**. Keep the teammate and second opponent at their defaults.

```php
<?php
declare(strict_types=1);

function claimedPickup(array $pickup, array $self, array $battle, array $allies): bool
{
    $reserve = $self['resources'][$pickup['kind']];
    if ($reserve['max'] - $reserve['current'] < 8.0 || $self['driveSpeed'] <= 0.0) {
        return false;
    }
    $route = $pilot->estimateMove($pickup['x'], $pickup['z']);
    $radius = $battle['pickupRules']['collectionRadius'];
    $arrival = max(0.0, ($route['totalSeconds'] ?? 999.0) - $radius / $self['driveSpeed']);
    if ($arrival + 0.2 >= $pickup['secondsRemaining'] || $arrival > 4.0) {
        return false;
    }
    foreach ($pilot->teamClaims('pickup') as $claim) {
        if ($claim['objectiveId'] === $pickup['id']) {
            return $claim['claimantId'] === $self['id'];
        }
    }
    if ($allies === []) {
        return true;
    }
    foreach ($allies as $ally) {
        $allyDistance = hypot($ally['x'] - $pickup['x'], $ally['z'] - $pickup['z']);
        if ($allyDistance + 1.0 < $pickup['distance']) {
            return false;
        }
    }
    // The claim is advisory and becomes visible next tick. Wait for ownership.
    $pilot->claimTeamObjective('pickup', $pickup['id'], 80);
    return false;
}

$self = $pilot->selfState();
$battle = $pilot->battleState();
$scan = $pilot->scan();
$requests = $pilot->teamMessages('help.request')['messages'];
foreach ($requests as $request) {
    if ($request['deliveredTick'] === $battle['tick']) {
        $pilot->sendTeamMessage('ack', ['replyTo' => $request['id']], $request['senderId']);
        break;
    }
}
if ($self['stunRemaining'] > 0) {
    return;
}
$enemy = $scan['enemies'][0] ?? null;
$laser = $pilot->mountState(0);
$shield = $pilot->mountState(1);
$resources = $self['resources'];
$missing = $resources['shield']['max'] - $resources['shield']['current'];
$wantShield = $missing > ($shield['enabled'] ? 0.25 : 8.0)
    && $resources['energy']['current'] > $laser['energyCost'] + ($shield['enabled'] ? 4.0 : 12.0);
if ($shield['ready'] && $shield['enabled'] !== $wantShield) {
    $pilot->toggle(1, $wantShield);
}

if ($enemy !== null && $enemy['distance'] <= $laser['range']) {
    $x = $enemy['x'];
    $z = $enemy['z'];
    $shot = $pilot->estimateShot(0, $x, $z);
    $lane = $pilot->estimateFriendlyFire(0, $x, $z);
    if ($battle['friendlyFire'] && $lane !== null && $lane['atRisk'] !== []) {
        $bearing = atan2($x - $self['x'], $z - $self['z']);
        $bounds = $battle['movementBounds'];
        foreach ([1.0, -1.0] as $side) {
            $sx = max($bounds['minX'], min($bounds['maxX'], $self['x'] + cos($bearing) * 5.0 * $side));
            $sz = max($bounds['minZ'], min($bounds['maxZ'], $self['z'] - sin($bearing) * 5.0 * $side));
            $route = $pilot->estimateMove($sx, $sz);
            if ($route !== null && $route['driveSeconds'] > 0.15) {
                $pilot->moveTo($route['x'], $route['z']);
                break;
            }
        }
        return;
    }
    if ($shot['inRange'] ?? false) {
        if ($laser['ready'] && $enemy['distance'] <= $laser['effectiveRange']
            && $shot['aimSeconds'] <= $battle['tickDuration']) {
            $pilot->fire(0, $x, $z);
            return;
        }
        $pilot->aim(0, $x, $z);
    }
}

$pickup = $scan['pickups'][0] ?? null;
if ($pickup !== null && claimedPickup($pickup, $self, $battle, $scan['allies'])) {
    $pilot->moveTo($pickup['x'], $pickup['z']);
} elseif ($enemy === null) {
    $pilot->moveTo(0.0, 0.0);
} elseif ($enemy['distance'] > $laser['effectiveRange'] * 0.88) {
    $pilot->moveTo($enemy['x'], $enemy['z']);
}
```

The **Training bots** directory also contains the four benchmarks with their complete player-compatible source and exact mount order. They show a combined policy with target selection, projectile prediction, dodging, and resource tradeoffs.

## Where to go next

- [Equipment and loadouts](equipment.md)
- [Combat strategy](combat-strategy.md)
- [Team strategy](team-strategy.md)
- [Troubleshooting](troubleshooting.md)
