ZH
games/rob-revisited / src / Revisited / Land / Wildlife.php · commit f9a1307
<?phpnamespace App\Revisited\Land;use App\Revisited\Sim\Talents;/** * The animals of Ysor (docs/reborn.md "Creatures"): one behaviour per species, spawning and despawning around Rob * with a cap per zone, wounds they give, carcasses they leave. Pure logic on Game's state. * *  grazer         prey: wanders in herds, flees when Rob comes close (less if he crouches), meat + hide *  bird           ambient: circles above its home *  stalker        night predator: stalks, pounces, bites, retreats when hurt; afraid of fire and torches *  crawler        cave insect: hunts in the dark, venomous bites (poison) *  burrower       canyon: buried in the sand, bursts out when Rob passes close, then buries again *  glacier_brute  plateau: slow and strong, its blows bruise and break bones *  swarm          swamp: a cloud of small biters over the mud; water and fire drive it off */final class Wildlife{    public const SPECIES = [        'grazer' => ['hp' => 60.0, 'walk' => 1.6, 'run' => 7.5, 'meat' => 3, 'hide' => 1, 'label' => 'brouteur'],        'bird' => ['hp' => 10.0, 'walk' => 7.0, 'run' => 9.0, 'meat' => 1, 'label' => 'oiseau'],        'stalker' => ['hp' => 90.0, 'walk' => 2.4, 'run' => 8.8, 'meat' => 2, 'hide' => 1, 'hit' => [0.25, 0.5], 'kind' => 'bite', 'every' => 1.6, 'label' => 'rôdeur de nuit'],        'crawler' => ['hp' => 35.0, 'walk' => 1.4, 'run' => 4.6, 'meat' => 0, 'hit' => [0.12, 0.28], 'kind' => 'bite', 'venom' => 0.22, 'every' => 1.8, 'label' => 'rampant'],        'burrower' => ['hp' => 70.0, 'walk' => 1.0, 'run' => 6.2, 'meat' => 2, 'hide' => 1, 'hit' => [0.2, 0.4], 'kind' => 'bite', 'every' => 1.5, 'label' => 'fouisseur'],        'glacier_brute' => ['hp' => 220.0, 'walk' => 1.3, 'run' => 4.8, 'meat' => 5, 'fur' => 3, 'hit' => [0.3, 0.65], 'kind' => 'bruise', 'every' => 2.2, 'label' => 'brute des glaces'],        'river_croc' => ['hp' => 160.0, 'walk' => 1.2, 'run' => 6.0, 'meat' => 4, 'scale' => 1, 'fat' => 2, 'hit' => [0.3, 0.6], 'kind' => 'bite', 'every' => 2.0, 'label' => 'croco des rivières'],        'climber' => ['hp' => 30.0, 'walk' => 2.0, 'run' => 7.0, 'meat' => 1, 'fur' => 1, 'label' => 'grimpeur'],        'stalker_cub' => ['hp' => 45.0, 'walk' => 2.2, 'run' => 6.5, 'meat' => 0, 'label' => 'petit rôdeur de nuit'],        'fish' => ['hp' => 6.0, 'walk' => 1.0, 'run' => 3.0, 'meat' => 0, 'label' => 'poisson'],        'lava_crab' => ['hp' => 28.0, 'walk' => 1.2, 'run' => 3.6, 'meat' => 0, 'crab' => 1, 'shell' => 1, 'hit' => [0.08, 0.2], 'kind' => 'cut', 'every' => 1.6, 'label' => 'crabe de lave'],        'swarm' => ['hp' => 15.0, 'walk' => 2.5, 'run' => 5.2, 'meat' => 0, 'hit' => [0.05, 0.1], 'kind' => 'bite', 'every' => 1.3, 'label' => 'essaim'],    ];    /** How many animals at once, per zone. */    public const CAPS = ['jungle' => 14, 'marsh' => 10, 'coast' => 10, 'caves3' => 7, 'valley' => 12, 'caves1' => 6, 'caves2' => 8, 'canyon' => 10, 'plateau' => 7];    private const PARTS = ['head', 'torso', 'larm', 'rarm', 'lleg', 'rleg'];    /** how far a beast's wound-up blow still reaches when it lands (metres): further, Rob stepped out of it */    private const REACH = ['crawler' => 2.3, 'stalker' => 2.8, 'burrower' => 2.6, 'glacier_brute' => 3.2, 'river_croc' => 3.2, 'lava_crab' => 2.2, 'swarm' => 2.4];    /** a hunter left this far behind gives up the chase (metres) */    public const GIVE_UP = ['stalker' => 30.0, 'crawler' => 16.0, 'glacier_brute' => 28.0];    /** seconds a provoked crawler stays angry (it attacks in spite of the flame) */    public const ANGRY = 30.0;    public static function label(string $species): string    {        return self::SPECIES[$species]['label'] ?? $species;    }    /**     * Each species with its article, whole (one text per form: the English dictionary translates each, no French grammar     * glued at run time): [the, The, of the, a].     */    private const FORMS = [        'grazer' => ['le brouteur', 'Le brouteur', 'du brouteur', 'un brouteur'],        'bird' => ['l\'oiseau', 'L\'oiseau', 'de l\'oiseau', 'un oiseau'],        'stalker' => ['le rôdeur de nuit', 'Le rôdeur de nuit', 'du rôdeur de nuit', 'un rôdeur de nuit'],        'crawler' => ['le rampant', 'Le rampant', 'du rampant', 'un rampant'],        'burrower' => ['le fouisseur', 'Le fouisseur', 'du fouisseur', 'un fouisseur'],        'glacier_brute' => ['la brute des glaces', 'La brute des glaces', 'de la brute des glaces', 'une brute des glaces'],        'river_croc' => ['le croco des rivières', 'Le croco des rivières', 'du croco des rivières', 'un croco des rivières'],        'climber' => ['le grimpeur', 'Le grimpeur', 'du grimpeur', 'un grimpeur'],        'stalker_cub' => ['le petit rôdeur de nuit', 'Le petit rôdeur de nuit', 'du petit rôdeur de nuit', 'un petit rôdeur de nuit'],        'fish' => ['le poisson', 'Le poisson', 'du poisson', 'un poisson'],        'lava_crab' => ['le crabe de lave', 'Le crabe de lave', 'du crabe de lave', 'un crabe de lave'],        'swarm' => ['l\'essaim', 'L\'essaim', 'de l\'essaim', 'un essaim'],    ];    /** "le brouteur", "la brute des glaces", "l'essaim" ($capital: "Le ..."). */    public static function the(string $species, bool $capital = false): string    {        return self::FORMS[$species][$capital ? 1 : 0] ?? self::label($species);    }    /** "du brouteur", "de la brute des glaces", "de l'essaim". */    public static function of(string $species): string    {        return self::FORMS[$species][2] ?? self::label($species);    }    /** "un brouteur", "une brute des glaces". */    public static function one(string $species): string    {        return self::FORMS[$species][3] ?? self::label($species);    }    public static function update(Game $g, float $dt): void    {        foreach ($g->creatures as $c) {            $c->anim += $dt;            $c->cooldown = max(0.0, $c->cooldown - $dt);            if (isset($c->data['wu'])) {                // a blow being wound up: it lands when the time is out (bite()), unless the beast lost Rob meanwhile                $c->data['wu'] = (float) $c->data['wu'] - $dt;                if ($c->state !== 'attack' && ((float) $c->data['wu'] <= 0 || self::dist($g, $c) > (self::REACH[$c->species] ?? 2.5) + 1.2)) {                    unset($c->data['wu'], $c->data['wuT']);                }            }            if ((float) ($c->data['stagger'] ?? 0) > 0) {                // countered: it reels a moment                $c->data['stagger'] = (float) $c->data['stagger'] - $dt;                continue;            }            match ($c->species) {                'grazer' => self::grazer($g, $c, $dt),                'bird' => self::bird($g, $c, $dt),                'stalker' => self::stalker($g, $c, $dt),                'crawler' => self::crawler($g, $c, $dt),                'burrower' => self::burrower($g, $c, $dt),                'glacier_brute' => self::brute($g, $c, $dt),                'swarm' => self::swarm($g, $c, $dt),                'river_croc' => self::croc($g, $c, $dt),                'climber' => self::climber($g, $c, $dt),                'fish' => self::fish($g, $c, $dt),                'lava_crab' => self::crab($g, $c, $dt),                'stalker_cub' => Companions::cub($g, $c, $dt),                default => self::wander($g, $c, $dt, 1.0),            };        }    }    // ------------------------------------------------------------------------------------------ behaviours    private static function grazer(Game $g, Creature $c, float $dt): void    {        $d = self::dist($g, $c);        $fear = $g->crouching ? 7.0 : ($g->running ? 26.0 : 16.0);        if ($d < $fear || ($c->data['scared'] ?? 0) > 0) {            $c->data['scared'] = max(0.0, ($c->data['scared'] ?? 6.0) - $dt);            if ($d < $fear) {                $c->data['scared'] = 6.0;            }            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, self::SPECIES['grazer']['run'], $dt);            return;        }        $c->state = 'wander';        self::wander($g, $c, $dt, self::SPECIES['grazer']['walk']);    }    /** The river crocodile: hidden under the water, it charges what comes to the shore or swims (and rams rafts). */    private static function croc(Game $g, Creature $c, float $dt): void    {        $z = $g->zone;        $d = self::dist($g, $c);        $wetRob = $z->waterDepth($g->x, $g->z) > -0.4 || $g->raft !== null;        if ($c->health < self::SPECIES['river_croc']['hp'] * (empty($c->data['boss']) ? 0.35 : 0.15) && $c->state !== 'flee') {            $c->state = 'flee';            $c->data['t'] = 20.0;        }        if ($c->state === 'flee') {            $c->data['t'] = (float) ($c->data['t'] ?? 10) - $dt;            self::moveAway($g, $c, $g->x, $g->z, 5.0, $dt);            if ($c->data['t'] <= 0) {                $c->state = 'lurk';            }        } elseif ($d < 11 && $wetRob && !$g->dead()) {            $c->state = $d < 2.6 ? 'attack' : 'hunt';            if ($d > 2.0) {                self::moveTo($g, $c, $g->x, $g->z, $z->waterDepth($c->x, $c->z) > 0.4 ? 6.0 : 3.0, $dt);            }            if ($d < 2.6 && $c->cooldown <= 0) {                if ($g->raft !== null && $g->rng()->chance(0.5)) {                    $c->cooldown = self::SPECIES['river_croc']['every'];                    $r = $g->raft;                    $r['hp'] -= 15;                    $g->raft = $r;                    $g->say('La gueule du croco s\'abat sur le radeau, qui craque !');                } else {                    self::bite($g, $c);                }            }        } else {            $c->state = 'lurk';            if ($z->waterDepth($c->x, $c->z) > 0.6) {                self::wander($g, $c, $dt, 0.6);            }        }        if ($z->waterDepth($c->x, $c->z) > 0.5) {            $c->y = $z->water - 0.35;        }    }    /** Climbers: they drop from the trees, snatch food from the bag and run. */    private static function climber(Game $g, Creature $c, float $dt): void    {        $d = self::dist($g, $c);        if (($c->data['stole'] ?? false) || ($c->data['scared'] ?? 0) > 0) {            $c->state = 'flee';            $c->data['scared'] = max(0.0, (float) ($c->data['scared'] ?? 8) - $dt);            self::moveAway($g, $c, $g->x, $g->z, self::SPECIES['climber']['run'], $dt);            return;        }        if ($d < 14 && !$g->dead()) {            $c->state = 'hunt';            self::moveTo($g, $c, $g->x, $g->z, 5.0, $dt);            if ($d < 1.4) {                foreach (['fruit', 'berries_blue', 'meat_cooked', 'smoked_fish', 'smoked_meat', 'dried_meat', 'fish_cooked', 'ration'] as $food) {                    if ($g->inv->has($food)) {                        $g->inv->remove($food);                        $g->say('Un grimpeur te file entre les jambes et t\'arrache : ' . mb_strtolower(\App\Revisited\Sim\Items::name($food)) . ' !');                        break;                    }                }                $c->data['stole'] = true;            }            return;        }        $c->state = 'wander';        self::wander($g, $c, $dt, self::SPECIES['climber']['walk']);    }    /** Fish: shadows that glide under the water (a harpoon or a line takes them). */    private static function fish(Game $g, Creature $c, float $dt): void    {        $z = $g->zone;        $c->state = 'swim';        $a = (float) ($c->data['a'] ?? $c->yaw) + $dt * 0.4;        $c->data['a'] = $a;        $nx = $c->x + sin($a) * 1.2 * $dt;        $nz = $c->z + cos($a) * 1.2 * $dt;        if ($z->waterDepth($nx, $nz) > 0.5 && $z->solidHit($nx, $nz, Solids::body('fish')) === null) {            $c->x = $nx;            $c->z = $nz;            $c->yaw = $a;        } else {            $c->data['a'] = $a + 2.5;        }        $c->y = $z->water - 0.4;    }    /** Lava crabs: they scuttle on the black sand and pinch what comes too close. */    private static function crab(Game $g, Creature $c, float $dt): void    {        $d = self::dist($g, $c);        if ($d < 5 && !$g->dead()) {            $c->state = $d < 1.6 ? 'attack' : 'hunt';            self::moveTo($g, $c, $g->x, $g->z, 2.6, $dt);            if ($d < 1.6 && $c->cooldown <= 0) {                self::bite($g, $c);            }            return;        }        $c->state = 'wander';        self::wander($g, $c, $dt, 0.8);    }    private static function bird(Game $g, Creature $c, float $dt): void    {        $hx = (float) ($c->data['hx'] ?? $c->x);        $hz = (float) ($c->data['hz'] ?? $c->z);        $a = (float) ($c->data['a'] ?? 0.0) + $dt * 0.35;        $c->data['a'] = $a;        $r = (float) ($c->data['r'] ?? 18.0);        $nx = $hx + sin($a) * $r;        $nz = $hz + cos($a) * $r;        $c->yaw = atan2($nx - $c->x, $nz - $c->z);        $c->x = max(2.0, min($g->zone->size - 2, $nx));        $c->z = max(2.0, min($g->zone->size - 2, $nz));        $ground = max($g->zone->heightAt($c->x, $c->z), $g->zone->water);        $c->y = $ground + (float) ($c->data['alt'] ?? 12.0) + sin($a * 3) * 1.5;        $c->state = 'fly';    }    /** A beast scared off (a torch brandished, a flare, fire): it runs from Rob while data['scared'] lasts. */    private static function scaredOff(Game $g, Creature $c, float $speed, float $dt): bool    {        $s = (float) ($c->data['scared'] ?? 0);        if ($s <= 0) {            return false;        }        $c->data['scared'] = $s - $dt;        $c->state = 'flee';        self::moveAway($g, $c, $g->x, $g->z, $speed, $dt);        return true;    }    private static function stalker(Game $g, Creature $c, float $dt): void    {        $sp = self::SPECIES['stalker'];        $d = self::dist($g, $c);        if (self::scaredOff($g, $c, $sp['run'] * 0.8, $dt)) {            return;        }        if (!$g->isNight() && !$g->zone->cave) {            // daylight: it slinks away            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, $sp['walk'] * 1.5, $dt);            return;        }        if ($c->state === 'flee') {            $c->data['t'] = (float) ($c->data['t'] ?? 10) - $dt;            self::moveAway($g, $c, $g->x, $g->z, $sp['run'] * 0.8, $dt);            if ($c->data['t'] <= 0) {                $c->state = 'stalk';                $c->data['hits'] = 0;            }            return;        }        if ($c->health < $sp['hp'] * 0.4) {            // badly hurt: it breaks off and runs            $c->state = 'flee';            $c->data['t'] = 12.0;            return;        }        if (self::givesUp($g, $c, $d, $dt)) {            return;        }        $keep = $g->nearFire() ? 13.0 : ($g->torchLit() ? 7.0 : 0.0);        if ($keep > 0 && $d < $keep + 4) {            // fire: it circles at a distance, growling            $c->state = 'stalk';            if ($d < $keep) {                self::moveAway($g, $c, $g->x, $g->z, $sp['walk'], $dt);            } else {                self::circle($g, $c, $sp['walk'], $dt);            }            return;        }        if ($d > 45) {            $c->state = 'wander';            self::wander($g, $c, $dt, $sp['walk']);            if ($d < 70) {                self::moveTo($g, $c, $g->x, $g->z, $sp['walk'], $dt);            }            return;        }        if ($d > 13) {            $c->state = 'stalk';            self::moveTo($g, $c, $g->x, $g->z, $sp['walk'] * 1.3, $dt);            return;        }        if ($d > 1.8) {            $c->state = 'hunt';            self::moveTo($g, $c, $g->x, $g->z, self::chaseSpeed($c, $sp['run']), $dt);            return;        }        $c->state = 'attack';        self::bite($g, $c);        if ((int) ($c->data['hits'] ?? 0) >= 2 || $c->health < $sp['hp'] * 0.4) { // @phpstan-ignore smaller.alwaysFalse (bite() can change the health: a counter)            $c->state = 'flee';            $c->data['t'] = 12.0;        }    }    /**     * The cave crawler hunts in the dark. A lit torch (either hand) draws it from further but keeps it off: it circles     * at TORCH_KEEP metres hissing ('keep'), backs away when Rob comes on; brandished, the near ones flee. Cornered     * (it cannot back away) or starving (a long while kept off), it still lunges. No flame: it attacks.     */    public const TORCH_KEEP = 4.5;    /** seconds kept off by a flame before a hungry crawler dares a lunge anyway */    public const CRAWLER_STARVE = 40.0;    private static function crawler(Game $g, Creature $c, float $dt): void    {        $sp = self::SPECIES['crawler'];        $d = self::dist($g, $c);        if ($c->health < $sp['hp'] * 0.3) {            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, $sp['run'], $dt);            return;        }        if (self::scaredOff($g, $c, $sp['run'], $dt)) {            return;        }        $angry = (float) ($c->data['angry'] ?? 0);        if ($angry > 0) {            $c->data['angry'] = $angry - $dt;        }        $torch = $g->torchLit();        $sense = $torch ? 14.0 : ($g->crouching ? 5.0 : 10.0);        $engaged = (in_array($c->state, ['hunt', 'keep', 'attack'], true) && $d < 18) || ($angry > 0 && $d < 22);        if ($d >= $sense && !$engaged) {            $c->state = 'wander';            self::wander($g, $c, $dt, $sp['walk']);            return;        }        $desperate = (float) ($c->data['starve'] ?? 0) > self::CRAWLER_STARVE || (float) ($c->data['cornered'] ?? 0) > 1.0;        if ($torch && !$desperate && $angry <= 0) {            $c->state = 'keep';            $c->data['starve'] = (float) ($c->data['starve'] ?? 0) + $dt;            $keep = self::TORCH_KEEP;            if ($d < $keep - 0.4) {                // too close to the flame: back off; held against a wall, it gets cornered                $x0 = $c->x;                $z0 = $c->z;                self::moveAway($g, $c, $g->x, $g->z, $sp['run'] * 0.8, $dt);                $moved = hypot($c->x - $x0, $c->z - $z0);                $c->data['cornered'] = $moved < $sp['run'] * 0.8 * $dt * 0.3 ? (float) ($c->data['cornered'] ?? 0) + $dt : 0.0;            } elseif ($d > $keep + 1.6) {                self::moveTo($g, $c, $g->x, $g->z, $sp['walk'] * 1.4, $dt);                $c->data['cornered'] = 0.0;            } else {                $side = $c->id % 2 === 0 ? 1.5708 : -1.5708;                $a = atan2($c->x - $g->x, $c->z - $g->z) + $side;                self::step($g, $c, sin($a), cos($a), $sp['walk'], $dt);                $c->data['cornered'] = 0.0;            }            $c->yaw = atan2($g->x - $c->x, $g->z - $c->z);   // it keeps its eyes on the flame            return;        }        if (self::givesUp($g, $c, $d, $dt)) {            unset($c->data['angry']);            return;        }        if ($d > 1.4) {            $c->state = 'hunt';            self::moveTo($g, $c, $g->x, $g->z, self::chaseSpeed($c, $sp['run']), $dt);            return;        }        $c->state = 'attack';        $before = (int) ($c->data['hits'] ?? 0);        $tried = self::bite($g, $c);        if ($tried && $desperate && $angry <= 0) {            // one lunge, then the flame holds it off again            $c->data['starve'] = 0.0;            $c->data['cornered'] = 0.0;            $c->data['hits'] = $before + 1;        }    }    private static function burrower(Game $g, Creature $c, float $dt): void    {        $sp = self::SPECIES['burrower'];        $d = self::dist($g, $c);        $ground = $g->zone->heightAt($c->x, $c->z);        if ($c->state === 'buried' || $c->state === 'idle') {            $c->state = 'buried';            $c->y = $ground - 1.2;            $c->data['rest'] = max(0.0, (float) ($c->data['rest'] ?? 0) - $dt);            $sense = $g->crouching ? 2.5 : ($g->running ? 9.0 : 6.0);            if ($d < $sense && $c->data['rest'] <= 0) {                $c->state = 'emerge';                $c->data['t'] = 0.6;                $c->anim = 0;                $g->say('Le sable explose sous tes pieds : un fouisseur !');            }            return;        }        if ($c->state === 'emerge') {            $c->data['t'] = (float) $c->data['t'] - $dt;            $c->y = $ground - 1.2 * max(0.0, (float) $c->data['t'] / 0.6);            if ($c->data['t'] <= 0) {                $c->state = 'hunt';                $c->data['t'] = 6.0;                $c->data['hits'] = 0;            }            return;        }        $c->y = $ground;        $c->data['t'] = (float) ($c->data['t'] ?? 6) - $dt;        if ((int) ($c->data['hits'] ?? 0) >= 2 && $d > 2.5) {            $c->data['t'] = 0.0;        }        if ($c->data['t'] <= 0 || $c->health < $sp['hp'] * 0.3) {            if ($c->health < $sp['hp'] * 0.3 && $d < 12) {                self::moveAway($g, $c, $g->x, $g->z, $sp['run'], $dt);                return;            }            $c->state = 'buried';            $c->data['rest'] = 25.0;            return;        }        if ((int) ($c->data['hits'] ?? 0) >= 2) {            // two bites, then it backs off before burying again            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, $sp['walk'] * 3, $dt);            return;        }        if ($d > 1.7) {            $c->state = 'hunt';            self::moveTo($g, $c, $g->x, $g->z, $sp['run'], $dt);        } else {            $c->state = 'attack';            self::bite($g, $c);        }    }    private static function brute(Game $g, Creature $c, float $dt): void    {        $sp = self::SPECIES['glacier_brute'];        $d = self::dist($g, $c);        if (self::scaredOff($g, $c, $sp['walk'] * 1.5, $dt)) {            return;        }        if ($c->health < $sp['hp'] * 0.25) {            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, $sp['run'], $dt);            return;        }        if (($g->nearFire() && $d < 10) || ($g->torchLit() && $d < 5 && $c->health > $sp['hp'] * 0.5 && ($g->isNight() || $g->zone->cave))) {            $c->state = 'stalk';            self::moveAway($g, $c, $g->x, $g->z, $sp['walk'], $dt);            return;        }        if (self::givesUp($g, $c, $d, $dt)) {            return;        }        $sense = $g->crouching ? 14.0 : 26.0;        if ($d < $sense || ($c->state === 'hunt' && $d < 40)) {            if ($d > 2.2) {                $c->state = 'hunt';                self::moveTo($g, $c, $g->x, $g->z, $d < 11 ? $sp['run'] : $sp['walk'] * 1.6, $dt);            } else {                $c->state = 'attack';                self::bite($g, $c);            }            return;        }        $c->state = 'wander';        self::wander($g, $c, $dt, $sp['walk']);    }    private static function swarm(Game $g, Creature $c, float $dt): void    {        $sp = self::SPECIES['swarm'];        $d = self::dist($g, $c);        $ground = max($g->zone->heightAt($c->x, $c->z), $g->zone->water);        $c->y = $ground + 1.2 + 0.3 * sin($c->anim * 5);        $hx = (float) ($c->data['hx'] ?? $c->x);        $hz = (float) ($c->data['hz'] ?? $c->z);        if ($g->swimming || $g->nearFire()) {            $c->state = 'flee';            self::moveAway($g, $c, $g->x, $g->z, $sp['run'], $dt, true);            return;        }        if ($d < 12 && hypot($g->x - $hx, $g->z - $hz) < 45) {            if ($d > 1.3) {                $c->state = 'hunt';                self::moveTo($g, $c, $g->x, $g->z, $sp['run'], $dt, true);            } else {                $c->state = 'attack';                self::bite($g, $c);            }            return;        }        $c->state = 'wander';        if (hypot($c->x - $hx, $c->z - $hz) > 10) {            self::moveTo($g, $c, $hx, $hz, $sp['walk'], $dt, true);        } else {            self::wander($g, $c, $dt, $sp['walk'], true);        }    }    // ------------------------------------------------------------------------------------------ fighting    /**     * The beast's blow: first wound up (Combat::WINDUP seconds: the telegraph the HUD shows; Rob may dodge, step back or     * counter), then it lands if Rob is still within reach and not dodging. True when the blow was resolved this call.     */    private static function bite(Game $g, Creature $c): bool    {        $c->yaw = atan2($g->x - $c->x, $g->z - $c->z);        if ($c->cooldown > 0) {            return false;        }        $wind = Combat::WINDUP[$c->species] ?? 0.4;        if ($wind > 0 && !isset($c->data['wu'])) {            $c->data['wu'] = $wind;            $c->data['wuT'] = $wind;            $c->anim = 0;            $g->combat->engage($g, $c);            return false;        }        if ($wind > 0 && (float) $c->data['wu'] > 0) {            return false;        }        unset($c->data['wu'], $c->data['wuT']);        $g->lunged();        $sp = self::SPECIES[$c->species];        $c->cooldown = $sp['every'] ?? 1.5;        $c->anim = 0;        if ($g->combat->evades($g, $c, self::REACH[$c->species] ?? 2.5)) {            $g->say('Tu esquives l\'attaque ' . self::of($c->species) . ' !');            $g->combat->popup('Esquivé !', [140, 220, 255]);            return true;        }        // a weapon held ready makes some blows miss; crouching does not help in a fight        $dodge = $g->inv->hand !== null ? 0.2 : 0.08;        if ($g->rng()->chance($dodge)) {            $g->say('Tu esquives l\'attaque ' . self::of($c->species) . '.');            return true;        }        [$lo, $hi] = $sp['hit'];        $sev = $g->rng()->range($lo, $hi) * 0.85;        $part = self::PARTS[$g->rng()->int(0, 5)];        if ($c->species === 'crawler' || $c->species === 'burrower') {            $part = $g->rng()->chance(0.7) ? ($g->rng()->chance(0.5) ? 'lleg' : 'rleg') : $part;        }        $kind = $sp['kind'];        if ($g->blockBlow($c, $sev, self::the($c->species, true))) {            $c->data['chase'] = 0.0;            return true;          // the shield took it (or parried it: the beast reels)        }        if ($c->species === 'glacier_brute' && $sev > 0.6 && $part !== 'head' && $part !== 'torso') {            $kind = 'fracture';        }        $g->hitPlayer($part, $kind, $sev, self::the($c->species, true));        if (isset($sp['venom'])) {            $g->body->poison($sp['venom']);            $g->say('Le venin brûle dans tes veines !');        }        $c->data['hits'] = (int) ($c->data['hits'] ?? 0) + 1;        $c->data['chase'] = 0.0;      // a bite that landed: the chase is fresh again        return true;    }    /**     * A hunter that cannot catch Rob gives up: left GIVE_UP metres behind, or 10 s of chase without a bite landed while he     * keeps away; it then wanders off for a while (unless he comes right back to it, within 3 m). The chase also tires it (chaseSpeed()).     */    private static function givesUp(Game $g, Creature $c, float $d, float $dt): bool    {        $gu = (float) ($c->data['giveup'] ?? 0);        if ($gu > 0) {            $c->data['giveup'] = $gu - $dt;            if ($d > 3.0) {                $c->state = 'wander';                self::wander($g, $c, $dt, (float) self::SPECIES[$c->species]['walk']);                return true;            }            unset($c->data['giveup']);        }        $chase = (float) ($c->data['chase'] ?? 0);        $chase = in_array($c->state, ['hunt', 'attack'], true) ? $chase + $dt : max(0.0, $chase - $dt);        $c->data['chase'] = $chase;        $far = self::GIVE_UP[$c->species] ?? 24.0;        // (only a beast that really chased: a prowler stalking from afar is not giving anything up)        if ((in_array($c->state, ['hunt', 'stalk'], true) && $d > $far && $chase > 2.0) || ($c->state === 'hunt' && $chase > 10.0 && $d > 4.0)) {            $c->data['giveup'] = 14.0;            $c->data['chase'] = 0.0;            unset($c->data['wu'], $c->data['wuT']);            $c->state = 'wander';            if ($d < 60.0) {                $g->say(self::the($c->species, true) . ' abandonne la poursuite.');            }            return true;        }        return false;    }    /** A long chase tires the hunter: full speed for 3 s, then slower and slower (half at the least, from 8 s). */    private static function chaseSpeed(Creature $c, float $speed): float    {        $t = (float) ($c->data['chase'] ?? 0);        return $t > 3.0 ? $speed * max(0.5, 1 - ($t - 3.0) * 0.1) : $speed;    }    /**     * A blade swung near crawlers (even ones held off by a torch): within $reach they feel threatened and attack in     * spite of the flame (ANGRY s), and the nearby ones join in. A brandished torch still scares them off. Returns how many.     */    public static function provoke(Game $g, float $reach): int    {        $n = 0;        foreach ($g->creatures as $c) {            if ($c->species === 'crawler' && empty($c->data['companion']) && $c->state !== 'flee' && self::dist($g, $c) < $reach) {                self::anger($g, $c);                $n++;            }        }        return $n;    }    /** One crawler turns on Rob (a blade near it, a blow), and calls the others within 12 m. */    public static function anger(Game $g, Creature $c): void    {        $was = (float) ($c->data['angry'] ?? 0) > 0;        $c->data['angry'] = self::ANGRY;        $c->data['starve'] = 0.0;        $c->data['cornered'] = 0.0;        unset($c->data['giveup']);        if ($c->state !== 'attack') {            $c->state = 'hunt';        }        $g->combat->engage($g, $c);        if ($was) {            return;        }        $others = 0;        foreach ($g->creatures as $o) {            if ($o !== $c && $o->species === 'crawler' && empty($o->data['companion']) && (float) ($o->data['angry'] ?? 0) <= 0                && hypot($o->x - $c->x, $o->z - $c->z) < 12.0) {                $o->data['angry'] = self::ANGRY;                $o->data['starve'] = 0.0;                unset($o->data['giveup']);                $o->state = 'hunt';                $others++;            }        }        $told = (float) ($g->flags['angry_told'] ?? -99);        if ($g->minutes - $told > 3) {            $g->flags['angry_told'] = $g->minutes;            $g->say($others > 0 ? 'Les rampants sifflent de rage : ta lame les menace, ils attaquent malgré la flamme !'                : 'Le rampant siffle de rage : ta lame le menace, il attaque malgré la flamme !');        }    }    /** Rob hits an animal. */    public static function hurt(Game $g, Creature $c, float $damage): void    {        $c->health -= $damage;        if ($c->species === 'burrower' && $c->state === 'buried') {            $c->state = 'hunt';            $c->data['t'] = 6.0;        }        if ($c->species === 'grazer') {            $c->data['scared'] = 8.0;        }        if ($c->species === 'crawler' && $c->health > 0) {            self::anger($g, $c);        } elseif ($c->species === 'glacier_brute') {            $c->state = 'hunt';        }        unset($c->data['giveup']);        if ($c->health <= 0) {            self::kill($g, $c);        }    }    public static function kill(Game $g, Creature $c): void    {        $c->health = 0;        $c->state = 'dead';        $k = array_search($c, $g->creatures, true);        if ($k !== false) {            array_splice($g->creatures, $k, 1);        }        $sp = self::SPECIES[$c->species] ?? [];        $g->flags['kills'] = (int) ($g->flags['kills'] ?? 0) + 1;        if (empty($c->data['companion'])) {            $g->gainXp(Talents::killXp($c->species, !empty($c->data['boss'])), true);        }        if ($c->species === 'swarm') {            $g->say('L\'essaim se disperse en bourdonnant.');            return;        }        if ($c->species === 'fish') {            if (self::dist($g, $c) < 6) {                $g->give('fish_raw');                $g->say('Tu remontes le poisson transpercé.');            }            return;        }        if (!empty($c->data['boss'])) {            $g->flags['croc_dead'] = true;            $g->say('La Vieille Mâchoire roule sur le dos et coule lentement. Le fleuve est libre.');        }        if (!empty($c->data['companion'])) {            $g->pet['state'] = 'dead';            $g->say('Le petit ne bouge plus. Tu restes longtemps à côté de lui.');            return;        }        if ($c->species === 'crawler') {            $g->addThing('bones', $c->x, $c->z, ['label' => 'Carapace de rampant', 'loot' => ['bone' => 1]]);            $g->say('Le rampant se recroqueville et meurt.');            return;        }        $meat = (int) ($sp['meat'] ?? 1);        if ($c->species === 'grazer' && $g->zone->id === 'plateau') {            $sp['fur'] = 1;        }        $g->addThing('carcass', $c->x, $c->z, [            'species' => $c->species, 'label' => 'Carcasse ' . self::of($c->species),            'meat' => $meat, 'hide' => (int) ($sp['hide'] ?? 0), 'fur' => (int) ($sp['fur'] ?? 0),            'fat' => (int) ($sp['fat'] ?? (in_array($c->species, ['grazer', 'stalker'], true) ? 1 : 0)) + (!empty($c->data['boss']) ? 2 : 0),            'scale' => (int) ($sp['scale'] ?? 0) + (!empty($c->data['boss']) ? 1 : 0), 'crab' => (int) ($sp['crab'] ?? 0), 'shell' => (int) ($sp['shell'] ?? 0),        ], $c->yaw);        $g->say(self::the($c->species, true) . ' s\'effondre.');    }    // ------------------------------------------------------------------------------------------ spawning    /** Removes animals far away, adds new ones out of sight (called every couple of seconds). */    public static function spawn(Game $g, bool $initial = false): void    {        $z = $g->zone;        $far = $z->cave ? 75.0 : 120.0;        foreach ($g->creatures as $c) {            $d = self::dist($g, $c);            if (!empty($c->data['companion']) || !empty($c->data['fixed'])) {                continue;            }            if ($d > $far || ($c->species === 'stalker' && !$g->isNight() && !$z->cave && $d > 45)) {                $k = array_search($c, $g->creatures, true);                array_splice($g->creatures, (int) $k, 1);            }        }        $cap = self::CAPS[$z->id] ?? 8;        $tries = $initial ? 30 : 2;        for ($t = 0; $t < $tries && count($g->creatures) < $cap; $t++) {            $species = self::pickSpecies($g);            if ($species === null) {                continue;            }            $min = $initial ? 22.0 : ($z->cave ? 20.0 : 38.0);            $max = $z->cave ? 45.0 : 75.0;            $pos = self::findSpot($g, $species, $min, $max);            if ($pos === null) {                continue;            }            $group = $species === 'grazer' ? $g->rng()->int(2, 4) : 1;            for ($k = 0; $k < $group && count($g->creatures) < $cap; $k++) {                $x = $pos[0] + ($k > 0 ? $g->rng()->range(-5, 5) : 0);                $zz = $pos[1] + ($k > 0 ? $g->rng()->range(-5, 5) : 0);                if (!in_array($species, ['bird', 'swarm'], true) && !Solids::free($z, $x, $zz, Solids::body($species))) {                    continue;                }                if ($z->solidAt($x, $zz)) {                    continue;                }                $g->creatures[] = self::make($g, $species, $x, $zz);            }        }    }    public static function make(Game $g, string $species, float $x, float $z): Creature    {        $c = new Creature($g->newId(), $species, $x, $g->zone->heightAt($x, $z), $z, $g->rng()->range(0, 6.28), self::SPECIES[$species]['hp'] ?? 50.0, 'idle');        $c->data['hx'] = $x;        $c->data['hz'] = $z;        if ($species === 'bird') {            $c->data['r'] = $g->rng()->range(10, 30);            $c->data['alt'] = $g->rng()->range(9, 20);            $c->data['a'] = $g->rng()->range(0, 6.28);        }        if ($species === 'burrower') {            $c->state = 'buried';            $c->y -= 1.2;        }        return $c;    }    private static function count(Game $g, string $species): int    {        $n = 0;        foreach ($g->creatures as $c) {            if ($c->species === $species) {                $n++;            }        }        return $n;    }    private static function pickSpecies(Game $g): ?string    {        $night = $g->isNight();        $table = match ($g->zone->id) {            'valley' => [['grazer', $night ? 1 : 4, 6], ['bird', $night ? 0 : 2, 3], ['stalker', $night ? 3 : 0, 2], ['swarm', 1, 1]],            'caves1' => [['crawler', 1, 5]],            'caves2' => [['crawler', 1, 7]],            'canyon' => [['grazer', $night ? 1 : 3, 5], ['bird', $night ? 0 : 2, 2], ['burrower', 2, 3], ['stalker', $night ? 2 : 0, 1]],            'plateau' => [['glacier_brute', 2, 2], ['grazer', 1, 3], ['bird', $night ? 0 : 1, 1]],            'jungle' => [['grazer', $night ? 1 : 3, 4], ['bird', $night ? 0 : 3, 3], ['climber', 2, 2], ['fish', 3, 5], ['river_croc', 1, 1], ['stalker', $night ? 2 : 0, 1]],            'marsh' => [['swarm', 3, 3], ['river_croc', 1, 2], ['fish', 2, 3], ['bird', $night ? 0 : 2, 2], ['stalker', $night ? 1 : 0, 1]],            'coast' => [['lava_crab', 3, 4], ['bird', $night ? 0 : 3, 3], ['fish', 2, 4], ['grazer', 1, 2]],            'caves3' => [['crawler', 1, 6]],            default => [],        };        $total = 0;        $ok = [];        foreach ($table as [$sp, $w, $max]) {            if ($w > 0 && self::count($g, $sp) < $max) {                $ok[] = [$sp, $w];                $total += $w;            }        }        if ($total === 0) {            return null;        }        $r = $g->rng()->next() * $total;        foreach ($ok as [$sp, $w]) {            $r -= $w;            if ($r < 0) {                return $sp;            }        }        return $ok[0][0];    }    private static function findSpot(Game $g, string $species, float $min, float $max): ?array    {        $z = $g->zone;        $village = $g->villageCentre();        for ($k = 0; $k < 8; $k++) {            $a = $g->rng()->range(0, 6.2832);            $d = $g->rng()->range($min, $max);            $x = $g->x + sin($a) * $d;            $zz = $g->z + cos($a) * $d;            if ($x < 8 || $zz < 8 || $x > $z->size - 8 || $zz > $z->size - 8 || $z->solidAt($x, $zz)) {                continue;            }            $biome = $z->biomeAt($x, $zz);            $wet = $z->waterDepth($x, $zz) > -0.1;            if ($species === 'fish' || $species === 'river_croc') {                if ($z->waterDepth($x, $zz) < ($species === 'fish' ? 0.8 : 0.7)) {                    continue;                }                return [$x, $zz];            }            if ($species !== 'bird' && $species !== 'swarm' && $wet) {                continue;            }            if ($species === 'swarm' && !in_array($biome, ['mud', 'marsh'], true)) {                continue;            }            if ($species === 'burrower' && !in_array($biome, ['sand', 'redrock'], true)) {                continue;            }            if ($village !== null && $species !== 'bird' && $species !== 'grazer' && hypot($x - $village[0], $zz - $village[1]) < 60) {                continue;            }            if ($z->cave) {                $ceil = $z->ceilingAt($x, $zz);                if ($ceil === null || $ceil - $z->heightAt($x, $zz) < 1.6) {                    continue;                }            }            return [$x, $zz];        }        return null;    }    // ------------------------------------------------------------------------------------------ moving    public static function dist(Game $g, Creature $c): float    {        return hypot($c->x - $g->x, $c->z - $g->z);    }    public static function wander(Game $g, Creature $c, float $dt, float $speed, bool $flying = false): void    {        $c->data['wt'] = (float) ($c->data['wt'] ?? 0) - $dt;        if ($c->data['wt'] <= 0) {            $c->data['wt'] = $g->rng()->range(2.5, 6.0);            $c->data['still'] = $g->rng()->chance(0.35);            $c->yaw += $g->rng()->range(-1.6, 1.6);        }        if (!empty($c->data['still'])) {            return;        }        // stay near home        $hx = (float) ($c->data['hx'] ?? $c->x);        $hz = (float) ($c->data['hz'] ?? $c->z);        if (hypot($c->x - $hx, $c->z - $hz) > 35) {            $c->yaw = atan2($hx - $c->x, $hz - $c->z);        }        self::step($g, $c, sin($c->yaw), cos($c->yaw), $speed, $dt, $flying);    }    private static function circle(Game $g, Creature $c, float $speed, float $dt): void    {        $a = atan2($c->x - $g->x, $c->z - $g->z) + 1.5708;        self::step($g, $c, sin($a), cos($a), $speed, $dt);    }    public static function moveTo(Game $g, Creature $c, float $tx, float $tz, float $speed, float $dt, bool $flying = false): void    {        $dx = $tx - $c->x;        $dz = $tz - $c->z;        $l = hypot($dx, $dz);        if ($l < 0.01) {            return;        }        self::step($g, $c, $dx / $l, $dz / $l, $speed, $dt, $flying);    }    public static function moveAway(Game $g, Creature $c, float $fx, float $fz, float $speed, float $dt, bool $flying = false): void    {        $dx = $c->x - $fx;        $dz = $c->z - $fz;        $l = hypot($dx, $dz);        if ($l < 0.01) {            $dx = 1.0;            $l = 1.0;        }        self::step($g, $c, $dx / $l, $dz / $l, $speed, $dt, $flying);    }    /**     * One step along a direction; walls, cliffs, deep water and solid things (Solids: rocks, trunks, huts...) turn the     * animal aside: it slides along an obstacle, else tries angles left and right, keeping the side it chose a moment     * (data 'av': side and seconds) so that it walks round a boulder instead of dithering in front of it.     */    private static function step(Game $g, Creature $c, float $dx, float $dz, float $speed, float $dt, bool $flying = false): void    {        $z = $g->zone;        $s = $speed * $dt;        $h0 = $z->heightAt($c->x, $c->z);        $ok = function (float $nx, float $nz) use ($z, $h0, $s, $flying): bool {            $h1 = $z->heightAt($nx, $nz);            if (!$flying && ($h1 - $h0 > $s * 1.2 + 0.01 || $z->waterDepth($nx, $nz) > 0.8)) {                return false;            }            if ($z->cave) {                $ceil = $z->ceilingAt($nx, $nz);                if ($ceil !== null && $ceil - $h1 < 1.0) {                    return false;                }            }            return true;        };        $side = (float) ($c->data['av'] ?? 0.0);        $turns = $side > 0 ? [0.0, 0.7, 1.5, -0.7, -1.5, 2.3, 3.1] : ($side < 0 ? [0.0, -0.7, -1.5, 0.7, 1.5, -2.3, 3.1] : [0.0, 0.7, -0.7, 1.5, -1.5, 2.3, -2.3, 3.1]);        if ($side !== 0.0) {            // keep going round the same side for a while: try that side first, straight only once it is clear            $keep = $side > 0 ? 0.7 : -0.7;            $turns = [$keep, ...$turns];            $left = abs($side) - $dt;            $c->data['av'] = $left > 0 ? ($side > 0 ? $left : -$left) : 0.0;            if ($left <= 0) {                unset($c->data['av']);            }        }        $r = $flying ? 0.0 : Solids::body($c->species);        $step = $flying ? self::flyStep($z, $c, $dx, $dz, $s, $turns, $ok) : Solids::step($z, $c->x, $c->z, $dx, $dz, $s, $r, $turns, $ok);        if ($step === null) {            $c->vx = 0.0;            $c->vz = 0.0;            return;        }        [$nx, $nz, $mx, $mz, $turn] = $step;        $c->x = $nx;        $c->z = $nz;        $c->yaw = atan2($mx, $mz);        if (!$flying) {            $c->y = $z->heightAt($nx, $nz);        }        $c->vx = $mx * $speed;        $c->vz = $mz * $speed;        if ($turn !== 0.0 && !isset($c->data['av']) && abs($turn) > 0.05) {            $c->data['av'] = $turn > 0 ? 0.8 : -0.8;        }        if ($turn !== 0.0 && empty($c->data['still'])) {            $c->data['wt'] = min((float) ($c->data['wt'] ?? 1), 1.0);        }    }    /** Birds and swarms fly over the things: only the walls (and the zone's edge) turn them. @param list<float> $turns */    private static function flyStep(Zone $z, Creature $c, float $dx, float $dz, float $s, array $turns, \Closure $ok): ?array    {        foreach ($turns as $turn) {            $mx = $dx * cos($turn) + $dz * sin($turn);            $mz = -$dx * sin($turn) + $dz * cos($turn);            $nx = $c->x + $mx * $s;            $nz = $c->z + $mz * $s;            if (!$z->solidAt($nx, $nz) && $ok($nx, $nz)) {                return [$nx, $nz, $mx, $mz, $turn];            }        }        return null;    }}