# Lesson 5. Dodge and recover from a blocked route

[Tutorials](tutorials.md) · [Lesson 4. Shields, repair, and resupply](tutorial-sustain.md) · [Combat strategy](combat-strategy.md)

Keep the same Mediumweight **Relay · Energy** chassis (`medium-energy`) with Pulse Laser, Shield Generator, and Nanobot Repair System. This final pilot keeps the aiming and recovery logic and adds one movement decision before combat and pickups. It can try a sidestep when it sees a threat coming or when its last move was blocked by another bot.

## What changes

- **Compare danger with travel time.** Read the first result from `estimateThreats()`. If a visible effect is projected to hit within 2.2 seconds, evaluate two diagonal routes to either side of the chassis. They can take less time to start than a perpendicular turn. Clamp each point to the driving bounds and reject points too close to count as a sidestep.
- **Check both drive directions.** Use `estimateMove()` forward and backward. For an evasion, require a point that `estimateThreatsAt()` considers clear and a route that can finish before the projected impact. For `blockedByBot`, use the same candidate points to try to get around the obstruction.
- **Remember the route.** The detour stores only its point, drive direction, and expiry tick. Keep issuing it until arrival, a new block, or expiry. Remember which side to try first on a later attempt. Cancel the pending shot while following the detour so the turret does not fire at an old coordinate.

Forecasts use the projectiles and waves the pilot can already see. Beams can hit immediately, and estimates assume the candidate route is open. You can still be hit while turning or encounter a second bot on the way. The trace tells you what the engine actually resolved. [Pilot API](pilot-api.md) · [Troubleshooting](troubleshooting.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);
    }
}

function followDetour(array $self, array $battle): bool
{
    $tick = $battle['tick'];
    $previous = $pilot->actionResults()['move'] ?? null;
    $detour = $pilot->recall('detour');
    if ($detour !== null) {
        if ($tick < $detour['until'] && $previous !== 'blockedByBot' && $previous !== 'arrived') {
            return $pilot->moveTo($detour['x'], $detour['z'], $detour['reverse']);
        }
        $pilot->remember('detour', null);
    }

    $impact = $pilot->estimateThreats()[0]['impactSeconds'] ?? null;
    $evade = $impact !== null && $impact <= 2.2;
    if (!$evade && $previous !== 'blockedByBot') {
        return false;
    }

    $bounds = $battle['movementBounds'];
    $firstSide = $pilot->recall('detour-side') ?? 1;
    $best = null;
    foreach ([$firstSide, -$firstSide] as $side) {
        $angle = $evade ? M_PI_4 : M_PI_2;
        $distance = $evade ? 2.1 : 3.5;
        $heading = $self['heading'] + $side * $angle;
        $x = min($bounds['maxX'], max($bounds['minX'], $self['x'] + $distance * sin($heading)));
        $z = min($bounds['maxZ'], max($bounds['minZ'], $self['z'] + $distance * cos($heading)));
        if (hypot($x - $self['x'], $z - $self['z']) < 2.0) {
            continue;
        }

        $move = $pilot->estimateMove($x, $z);
        $backward = $pilot->estimateMove($x, $z, true);
        if ($move === null || $backward === null) {
            continue;
        }

        $reverse = $backward['totalSeconds'] < $move['totalSeconds'];
        $seconds = $reverse ? $backward['totalSeconds'] : $move['totalSeconds'];
        if ($evade && ($seconds + $battle['tickDuration'] >= $impact || $pilot->estimateThreatsAt($x, $z) !== [])) {
            continue;
        }

        if ($best === null || $seconds < $best['seconds']) {
            $best = ['x' => $x, 'z' => $z, 'reverse' => $reverse, 'seconds' => $seconds, 'side' => $side];
        }
    }

    if ($best === null || !$pilot->moveTo($best['x'], $best['z'], $best['reverse'])) {
        return false;
    }

    $pilot->remember('detour', [
        'x' => $best['x'], 'z' => $best['z'], 'reverse' => $best['reverse'],
        'until' => $tick + (int) ceil($best['seconds'] / $battle['tickDuration']) + 4,
    ]);
    $pilot->remember('detour-side', -$best['side']);
    $pilot->debug($evade ? 'evasion' : 'unblock', ['eta' => $best['seconds'], 'impact' => $impact]);
    return true;
}

$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 (followDetour($self, $battle)) {
    if ($weapon['pendingAim'] !== null) {
        $pilot->cancelAim(0);
    }
    return;
}

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

1. Run **Solo combat**, seed `77`, against **Basic Bot**. The pilot approaches, lands six reported hits, and activates both recovery mounts. Basic Bot's Pulse Laser fires an instant beam, so there is no incoming projectile to dodge.
2. Against the Plasma Station below, keep **Solo combat** and seed `77`. On tick 30 the trace records `evasion`, an estimated arrival of `0.8` seconds, and an impact estimate of about `0.89` seconds. The command list shows the accepted move. Check the following movement results and hull readings to see what happened during the detour.
3. Run each saved lesson version in **Practice battles** with a 96-unit arena, a 45-second normal phase, seed `101`, pickups off, and Field Technician as the second team's bot. Compare the time and position of the first shot and how much hull each version keeps before sudden death. Keep the same seat positions and options. [Testing](testing.md)

**Challenge** Increase the evasion distance from 2.1 units to 2.8. Compare the number of completed detours and whether any proposed route can beat the impact estimate. A point farther from the shot can also take too long to reach.

### Optional practice target

Save a second bot named **Plasma Station** with the Lightweight **Pioneer · Balanced** chassis (`light-balanced`), Plasma Cannon in the first mount, and Propulsion Booster in the second. This stationary opponent aims and fires at the nearest visible bot using the following source. Select it as the opponent in the Relay bot's **Practice** tab.

```php
<?php
$target = $pilot->scan()['enemies'][0] ?? null;
if ($target !== null && $pilot->mountState(0)['ready']) {
    $pilot->fire(0, $target['x'], $target['z']);
}
```

Try a teammate scenario next. Give one bot a clear route to the side and avoid doubling up on a pickup. [Team strategy](team-strategy.md) · [Worked examples](examples.md)
