# Lesson 4. Shields, repair, and resupply

[Tutorials](tutorials.md) · [Lesson 3. Track and aim](tutorial-aim.md) · [Lesson 5. Tactical movement](tutorial-tactics.md)

The pilot from Lesson 3 can approach, aim through cooldown, and fire its Pulse Laser. Keep that firing decision and add a recovery policy. Use the same Mediumweight **Relay · Energy** chassis (`medium-energy`) with Pulse Laser, Shield Generator, and Nanobot Repair System in that order.

## What changes

1. **Keep a firing reserve.** `mountState(0)['energyCost']` gives the actual cost through this build's equipment. Keep two shots' worth of energy available and subtract the shield's activation cost from the energy left for starting repair in the same tick. Toggles resolve before shots and the pilot reads one snapshot per tick, so the second toggle decision needs its own accounting.
2. **Recover when it will help.** Enable shield recharge after losing at least 10 charge and stop near full or when energy drops toward the reserve. Existing shield charge still absorbs damage with recharge off. Repair starts after a larger hull loss, spends ammo as well as energy, and pauses in sudden death. Separate start and stop thresholds give the equipment time to do useful work.
3. **Take short, useful detours.** The revised `collectPickup()` checks the amount the bot can actually gain and estimates travel time including the chassis turn. Take a shot when it is ready and aligned. Between shots, divert for useful hull, energy, or ammo within a short detour. Ammo pickups replenish the repair budget because this laser fires with energy.

The thresholds are starting points for this loadout. Repair and shield upkeep can continue spending after activation, so check the reserves on every tick. [Equipment](equipment.md) · [Pilot API](pilot-api.md)

## Full pilot

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

function collectPickup(array $scan, float $minimumGain = 1.0, float $maximumDetour = 8.0): bool
{
    $pickup = $scan['pickups'][0] ?? null;
    if ($pickup === null) {
        return false;
    }

    $self = $pilot->selfState();
    $resource = $self['resources'][$pickup['kind']];
    $gain = min($pickup['amount'], $resource['max'] - $resource['current']);
    if ($gain < $minimumGain || $self['driveSpeed'] <= 0.0) {
        return false;
    }

    $move = $pilot->estimateMove($pickup['x'], $pickup['z']);
    if ($move === null) {
        return false;
    }

    $radius = $pilot->battleState()['pickupRules']['collectionRadius'];
    $seconds = $move['turnSeconds'] + max(0.0, $move['driveSeconds'] - $radius / $self['driveSpeed']);
    if ($seconds > $maximumDetour || $seconds + 0.2 >= $pickup['secondsRemaining']) {
        return false;
    }

    return $pilot->moveTo($move['x'], $move['z']);
}

function attackPoint(array $enemy, array $battle): array
{
    $vx = $enemy['velocity']['x'] ?? 0.0;
    $vz = $enemy['velocity']['z'] ?? 0.0;
    $x = $enemy['x'] + $vx * $battle['tickDuration'];
    $z = $enemy['z'] + $vz * $battle['tickDuration'];
    $lead = $pilot->estimateIntercept(0, $x, $z, $vx, $vz);

    return ['x' => $lead['x'] ?? $enemy['x'], 'z' => $lead['z'] ?? $enemy['z']];
}

function manageRecovery(array $self, array $battle, array $weapon): void
{
    $shield = $pilot->mountState(1);
    $repair = $pilot->mountState(2);
    if ($shield === null || $repair === null) {
        return;
    }
    $resources = $self['resources'];
    $available = $resources['energy']['current'] - 2.0 * $weapon['energyCost'];

    $shieldLoss = $resources['shield']['max'] - $resources['shield']['current'];
    $wantShield = $shieldLoss >= ($shield['enabled'] ? 0.5 : 10.0)
        && $available >= ($shield['enabled'] ? 3.0 : $shield['energyCost'] + 6.0);
    if ($wantShield !== $shield['enabled']) {
        if ($pilot->toggle(1, $wantShield) && $wantShield) {
            $available -= $shield['energyCost'];
        }
    }

    $hullLoss = $resources['hull']['max'] - $resources['hull']['current'];
    $wantRepair = $battle['phase'] === 'normal'
        && $hullLoss >= ($repair['enabled'] ? 0.5 : 12.0)
        && $resources['ammo']['current'] >= ($repair['enabled'] ? 4.0 : 8.0)
        && $available >= ($repair['enabled'] ? 6.0 : $repair['energyCost'] + 12.0);
    if ($wantRepair !== $repair['enabled']) {
        $pilot->toggle(2, $wantRepair);
    }
}

$self = $pilot->selfState();
if ($self['stunRemaining'] > 0.0) {
    return;
}

$scan = $pilot->scan();
$enemy = $scan['enemies'][0] ?? null;
$weapon = $pilot->mountState(0);
if ($weapon === null || $weapon['targeting'] !== 'point') {
    return;
}
$battle = $pilot->battleState();
manageRecovery($self, $battle, $weapon);

if ($enemy === null) {
    if ($weapon['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    collectPickup($scan);
    return;
}

$point = attackPoint($enemy, $battle);
$shot = $pilot->estimateShot(0, $point['x'], $point['z']);
if (!($shot['inRange'] ?? false)) {
    $point = ['x' => $enemy['x'], 'z' => $enemy['z']];
    $shot = $pilot->estimateShot(0, $point['x'], $point['z']);
}
$preferredRange = max(1.0, $weapon['effectiveRange'] - 3.0);
$atFiringDistance = $enemy['distance'] <= $preferredRange && ($shot['inRange'] ?? false);
if ($atFiringDistance && $weapon['ready'] && $shot['aimSeconds'] <= $battle['tickDuration']) {
    $pilot->holdPosition();
    $pilot->fire(0, $point['x'], $point['z']);
    return;
}

if (collectPickup($scan, 8.0, 2.5)) {
    if ($weapon['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    return;
}

if (!$atFiringDistance) {
    if ($shot['inRange'] ?? false) {
        $pilot->aim(0, $point['x'], $point['z']);
    } elseif ($weapon['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    $pilot->moveTo($enemy['x'], $enemy['z']);
    return;
}

$pilot->aim(0, $point['x'], $point['z']);
```

## Try it

Compile and run **Solo combat** against **Basic Bot** with seed `77`. Both recovery mounts activate, and the pilot keeps firing. Repeat with the Lesson 3 source and compare the same part of the trace. Check the `toggle` results for when slots `1` and `2` switch on. Check the energy and ammo readings before and after a recovery window, then look for a later `shotLaunched` event.

Switch to **Field Technician** with seed `101`. In this run, Lesson 3 wins before the practice deadline and Lesson 4 reaches the deadline with both bots still active. Compare hull, firing gaps, and the time each version spends moving. Recovery spending changes when the laser can fire. In a wider practice battle, compare the same seed with pickups off and on to distinguish what the equipment recovers from what the bot collects. [Testing](testing.md)

To see a useful detour with an enemy still visible, choose **Contested pickups**, seed `77`, and keep **Practice Partner** as the teammate. Pick **Turret Trainer** and **Resource Collector** as the opponents in that order. Look for a move toward the hull pickup on tick 122 and its collection at 8.25 seconds. The pilot later collects ammo for repair.

**Challenge** Reserve energy for three shots in `manageRecovery()` and keep the original trace. Compare when both toggles first activate and whether the bot fires more often. Revert the change if it leaves the bot under sustained fire for longer without improving its shot opportunities.
