JA
games/rob-revisited / src / Revisited / Land / Companions.php · commit f9a1307
<?phpnamespace App\Revisited\Land;use App\Revisited\Sim\Inventory;/** * Companions (docs/reborn.md "Wave 2"). The animal: a stalker cub found wounded in its den in the jungle (its mother killed * by the Ouvi's hunters). Healed (a bandage, a healing herb) and fed (raw or cooked meat), it trusts Rob little by little; * tamed, it follows him through the zones, growls at danger, bites what attacks him, hunts on command, and waits where it * is told. It has its own health and hunger: forgotten too long, it goes back to the wild. Game::$pet holds it. * * The human: later in the game, Tamu (an Ouvi fisher who came to trust Rob) or Grell (a Rôdeur spared on his knees) * follows Rob: carries some of his load, fights at his side, keeps watch while he sleeps, and eats from his bag once a * day (two days without food and they leave). Game::$companion holds the People key. */final class Companions{    public const CARRY = 8.0;    public const DEN = [150.0, 92.0];    /** The cub and the companion in the zone Rob enters (Folk::populate()). */    public static function populate(Game $g): void    {        $p = $g->pet;        $state = (string) ($p['state'] ?? 'wild');        if ($state === 'wild' && $g->zone->id === 'jungle') {            $c = Wildlife::make($g, 'stalker_cub', self::DEN[0] + 2, self::DEN[1] + 1);            $c->state = 'wounded';            $c->health = 18.0;            $c->data['fixed'] = true;            $c->data['cub'] = true;            $g->creatures[] = $c;        }        if ($state === 'tame') {            $here = ($p['mode'] ?? 'follow') !== 'stay' || ($p['zone'] ?? '') === $g->zone->id;            if ($here) {                [$x, $z] = ($p['mode'] ?? 'follow') === 'stay' ? [(float) $p['x'], (float) $p['z']] : [$g->x - 2, $g->z - 2];                $c = Wildlife::make($g, 'stalker_cub', $x, $z);                $c->health = (float) ($p['health'] ?? 45);                $c->data['companion'] = true;                $c->data['cub'] = true;                $c->state = 'follow';                $g->creatures[] = $c;            }        }        if ($g->companion !== null) {            $key = $g->companion;            $n = People::npc($g, $key, People::group($key), $g->x - 2.5, $g->z - 2.5, 500);            $n->data['companion'] = true;            $n->data['role'] = 'companion';            $g->npcs[] = $n;        }    }    /** Re-places the followers next to Rob after a door (they came through with him). */    public static function arrive(Game $g): void    {        foreach ($g->creatures as $c) {            if (!empty($c->data['companion']) && ($g->pet['mode'] ?? 'follow') !== 'stay') {                $c->x = $g->x - sin($g->yaw) * 2;                $c->z = $g->z - cos($g->yaw) * 2;                $c->y = $g->zone->heightAt($c->x, $c->z);            }        }        foreach ($g->npcs as $n) {            if (!empty($n->data['companion'])) {                $n->x = $g->x - sin($g->yaw) * 2.5 + 1;                $n->z = $g->z - cos($g->yaw) * 2.5;                $n->y = $g->zone->heightAt($n->x, $n->z);            }        }    }    public static function pet(Game $g): ?Creature    {        foreach ($g->creatures as $c) {            if (!empty($c->data['cub'])) {                return $c;            }        }        return null;    }    public static function petFollowing(Game $g): bool    {        return ($g->pet['state'] ?? '') === 'tame';    }    // ------------------------------------------------------------------------------------------ the cub    /** Context actions on the cub (Game::options()). */    public static function options(Game $g, array &$o): void    {        $c = self::pet($g);        if ($c === null || hypot($c->x - $g->x, $c->z - $g->z) > 3.0) {            return;        }        $state = (string) ($g->pet['state'] ?? 'wild');        if ($state === 'wild') {            if (empty($g->pet['healed'])) {                $o[] = ['id' => 'pet_heal', 'label' => 'Soigner le petit blessé', 'run' => fn (): string => self::heal($g, $c)];            }            $o[] = ['id' => 'pet_feed', 'label' => 'Nourrir le petit', 'run' => fn (): string => self::feed($g, $c)];            return;        }        $o[] = ['id' => 'pet_talk', 'label' => 'Donner un ordre au petit', 'run' => function () use ($g): string {            $g->talkToPet();            return '';        }];        if ((float) ($g->pet['hunger'] ?? 0) > 30) {            $o[] = ['id' => 'pet_feed', 'label' => 'Nourrir le petit', 'run' => fn (): string => self::feed($g, $c)];        }    }    public static function heal(Game $g, Creature $c): string    {        $care = null;        foreach (['bandage', 'herb_heal', 'poultice', 'medkit'] as $id) {            if ($g->inv->has($id)) {                $care = $id;                break;            }        }        if ($care === null) {            return 'Sa patte saigne : il te faudrait un bandage ou une herbe cicatrisante.';        }        $g->inv->remove($care);        $p = $g->pet;        $p['healed'] = true;        $p['tame'] = (float) ($p['tame'] ?? 0) + 30;        $g->pet = $p;        $c->health = 40.0;        $g->passTime(10);        return 'Il grogne, montre les crocs... puis te laisse bander sa patte. Ses yeux jaunes ne te quittent pas.' . self::maybeTame($g);    }    public static function feed(Game $g, Creature $c): string    {        $food = null;        foreach (['meat_raw', 'meat_cooked', 'fish_raw', 'dried_meat', 'smoked_meat', 'fish_cooked', 'smoked_fish', 'crab_meat'] as $id) {            if ($g->inv->has($id)) {                $food = $id;                break;            }        }        if ($food === null) {            return 'Il renifle tes mains vides. Un petit rôdeur mange de la viande ou du poisson.';        }        $g->inv->remove($food);        $p = $g->pet;        $p['hunger'] = max(0.0, (float) ($p['hunger'] ?? 50) - 45);        $p['neglect'] = 0.0;        $last = (float) ($p['fedAt'] ?? -999);        if ($g->minutes - $last >= 180) {            $p['tame'] = (float) ($p['tame'] ?? 0) + 15;   // a meal every few hours wins him over, not a heap at once        }        $p['fedAt'] = $g->minutes;        $g->pet = $p;        return ($p['state'] ?? 'wild') === 'tame' ? 'Le petit dévore sa part en remuant la queue.' : 'Il arrache la viande et recule pour la manger, sans cesser de te fixer.' . self::maybeTame($g);    }    private static function maybeTame(Game $g): string    {        $p = $g->pet;        if (($p['state'] ?? 'wild') === 'wild' && !empty($p['healed']) && (float) ($p['tame'] ?? 0) >= 60) {            $p['state'] = 'tame';            $p['mode'] = 'follow';            $p['health'] = 45.0;            $p['hunger'] = (float) ($p['hunger'] ?? 20);            $g->pet = $p;            $g->flags['q_pet'] = true;            foreach ($g->creatures as $c) {                if (!empty($c->data['cub'])) {                    $c->data['companion'] = true;                    unset($c->data['fixed']);                    $c->state = 'follow';                }            }            $g->say('Le petit rôdeur de nuit vient frotter sa tête contre ta jambe. Il te suivra désormais.');            return ' Puis il vient se coucher contre ta jambe.';        }        return '';    }    /** The cub's behaviour each frame (Wildlife::update()). */    public static function cub(Game $g, Creature $c, float $dt): void    {        if ($c->state === 'wounded' || empty($c->data['companion'])) {            $c->state = 'wounded';            return;        }        $p = $g->pet;        $mode = (string) ($p['mode'] ?? 'follow');        $d = Wildlife::dist($g, $c);        // danger: growl, then bite what threatens Rob        $foe = null;        foreach ($g->creatures as $o) {            if ($o !== $c && in_array($o->species, ['stalker', 'crawler', 'burrower', 'glacier_brute', 'river_croc', 'lava_crab', 'climber'], true)                && $o->state !== 'buried' && $o->state !== 'dead' && hypot($o->x - $g->x, $o->z - $g->z) < 25) {                if ($foe === null || hypot($o->x - $c->x, $o->z - $c->z) < hypot($foe->x - $c->x, $foe->z - $c->z)) {                    $foe = $o;                }            }        }        if ($foe !== null && $g->minutes - (float) ($p['warned'] ?? -99) > 20) {            $p['warned'] = $g->minutes;            $g->pet = $p;            $g->say('Le petit gronde, le poil hérissé : ' . Wildlife::the($foe->species) . ' approche !');        }        if ($foe !== null && hypot($foe->x - $g->x, $foe->z - $g->z) < 9 && $mode !== 'stay') {            $c->state = 'attack';            Wildlife::moveTo($g, $c, $foe->x, $foe->z, 6.0, $dt);            if (hypot($foe->x - $c->x, $foe->z - $c->z) < 1.8 && $c->cooldown <= 0) {                $c->cooldown = 1.2;                $c->anim = 0;                Wildlife::hurt($g, $foe, 9.0);            }            return;        }        if ($mode === 'hunt') {            $prey = null;            foreach ($g->creatures as $o) {                if (in_array($o->species, ['grazer', 'bird', 'climber'], true) && hypot($o->x - $c->x, $o->z - $c->z) < 50) {                    $prey = $o;                    break;                }            }            if ($prey !== null) {                $c->state = 'hunt';                Wildlife::moveTo($g, $c, $prey->x, $prey->z, 6.5, $dt);                if (hypot($prey->x - $c->x, $prey->z - $c->z) < 1.8 && $c->cooldown <= 0) {                    $c->cooldown = 1.0;                    Wildlife::hurt($g, $prey, 18.0);                    if ($prey->health <= 0) {                        $g->say('Le petit a abattu ' . Wildlife::one($prey->species) . ' : la carcasse t\'attend.');                        $p['mode'] = 'follow';                        $g->pet = $p;                    }                }                return;            }        }        if ($mode === 'stay') {            $c->state = 'sit';            return;        }        if ($d > 3.0) {            $c->state = 'follow';            Wildlife::moveTo($g, $c, $g->x, $g->z, $d > 12 ? 7.0 : 3.6, $dt);            if ($d > 40) {                $c->x = $g->x - 2;                $c->z = $g->z - 2;            }        } else {            $c->state = 'idle';        }    }    /** The cub's orders (a small talk). @return array{text: string, choices: list<array{0: string, 1: string}>} */    public static function petNode(Game $g): array    {        $p = $g->pet;        $hunger = (int) ($p['hunger'] ?? 0);        $t = 'Le petit rôdeur de nuit lève vers toi ses yeux jaunes.' . ($hunger > 60 ? ' Il a faim : son ventre gronde.' : '') . ' (Santé ' . (int) ($p['health'] ?? 45) . ', faim ' . $hunger . ')';        return ['text' => $t, 'choices' => [['Suis-moi.', 'do:follow'], ['Reste ici, garde cet endroit.', 'do:stay'], ['Va chasser !', 'do:hunt'], ['(Le caresser)', 'do:pat'], ['Rien.', 'end']]];    }    public static function petDo(Game $g, string $action): string    {        $p = $g->pet;        switch ($action) {            case 'follow':            case 'stay':            case 'hunt':                $p['mode'] = $action;                if ($action === 'stay') {                    $c = self::pet($g);                    $p['zone'] = $g->zone->id;                    $p['x'] = $c !== null ? $c->x : $g->x;                    $p['z'] = $c !== null ? $c->z : $g->z;                }                $g->pet = $p;                return ['follow' => 'Le petit trottine dans tes pas.', 'stay' => 'Le petit se couche et pose le museau sur ses pattes. Il t\'attendra ici.', 'hunt' => 'Le petit file dans les herbes, le ventre au ras du sol.'][$action];            case 'pat':                $p['tame'] = min(100.0, (float) ($p['tame'] ?? 60) + 2);                $g->pet = $p;                $g->body->morale(3);                return 'Il ferme les yeux et ronronne comme un moteur. Ça fait du bien, à tous les deux.';        }        return '';    }    // ------------------------------------------------------------------------------------------ the human companion    public static function recruit(Game $g, Npc $n): string    {        $key = People::keyOf($n);        if ($key === null || $g->companion !== null) {            return 'Tu as déjà quelqu\'un avec toi.';        }        $g->companion = $key;        $g->companionFed = $g->minutes;        $n->data['companion'] = true;        $n->hostile = false;        $n->state = 'follow';        $g->inv->setCapacity(Inventory::DEFAULT_CAPACITY + self::CARRY);        $g->flags['q_companion'] = true;        $g->say(People::name($key) . ' te suit désormais : il porte une partie de ta charge, se bat à tes côtés et veille la nuit.');        return People::name($key) . ' ramasse ses affaires. « Allons-y. »';    }    public static function dismiss(Game $g, string $why): void    {        if ($g->companion === null) {            return;        }        $name = People::name($g->companion);        People::change($g, $g->companion, -20, false);        $g->companion = null;        $g->inv->setCapacity(Inventory::DEFAULT_CAPACITY);        foreach ($g->npcs as $k => $n) {            if (!empty($n->data['companion'])) {                array_splice($g->npcs, $k, 1);                break;            }        }        $g->say($name . ' s\'en va : ' . $why);    }    /** Followers' needs and the human companion's moves, each frame. */    public static function update(Game $g, float $dt): void    {        $mins = $dt * Game::TIME_RATE;        // the cub's hunger and loyalty        if (($g->pet['state'] ?? '') === 'tame') {            $p = $g->pet;            $p['hunger'] = min(100.0, (float) ($p['hunger'] ?? 0) + $mins / 60 * 4);            if ($p['hunger'] >= 100) {                $p['neglect'] = (float) ($p['neglect'] ?? 0) + $mins;                if ($p['neglect'] > 24 * 60) {                    $p['state'] = 'gone';                    $g->say('Le petit a trop faim. Il te regarde une dernière fois et retourne à la forêt.');                    foreach ($g->creatures as $k => $c) {                        if (!empty($c->data['cub'])) {                            array_splice($g->creatures, $k, 1);                            break;                        }                    }                }            }            $c = self::pet($g);            if ($c !== null) {                $p['health'] = $c->health;            }            $g->pet = $p;        }        if ($g->companion === null) {            return;        }        // the companion eats once a day from the bag        if ($g->minutes - $g->companionFed > 24 * 60) {            $ate = null;            foreach (['smoked_fish', 'smoked_meat', 'dried_meat', 'meat_cooked', 'fish_cooked', 'crab_cooked', 'root_cooked', 'fruit', 'berries_blue', 'ration'] as $f) {                if ($g->inv->has($f)) {                    $ate = $f;                    break;                }            }            if ($ate !== null) {                $g->inv->remove($ate);                $g->companionFed = $g->minutes;                $g->say(People::name($g->companion) . ' mange sa part.');            } elseif ($g->minutes - $g->companionFed > 48 * 60) {                self::dismiss($g, 'deux jours sans manger, c\'est trop.');                return;            }        }        foreach ($g->npcs as $n) {            if (empty($n->data['companion'])) {                continue;            }            $n->anim += $dt;            $n->data['cool'] = max(0.0, (float) ($n->data['cool'] ?? 0) - $dt);            $foe = null;            foreach ($g->creatures as $c) {                if (in_array($c->species, ['stalker', 'crawler', 'burrower', 'glacier_brute', 'river_croc', 'lava_crab', 'swarm'], true) && $c->state !== 'buried'                    && hypot($c->x - $g->x, $c->z - $g->z) < 12) {                    $foe = $c;                    break;                }            }            if ($foe !== null) {                $n->state = 'attack';                self::walk($g, $n, $foe->x, $foe->z, 4.5, $dt);                if (hypot($foe->x - $n->x, $foe->z - $n->z) < 2.2 && $n->data['cool'] <= 0) {                    $n->data['cool'] = 1.4;                    $n->anim = 0;                    Wildlife::hurt($g, $foe, 11.0);                }                continue;            }            $d = hypot($g->x - $n->x, $g->z - $n->z);            if ($d > 3.2) {                $n->state = 'walk';                self::walk($g, $n, $g->x, $g->z, $d > 10 ? 6.0 : 3.4, $dt);                if ($d > 40) {                    $n->x = $g->x - 2;                    $n->z = $g->z - 2;                }            } else {                $n->state = 'idle';                $n->yaw = atan2($g->x - $n->x, $g->z - $n->z);            }        }    }    private static function walk(Game $g, Npc $n, float $tx, float $tz, float $speed, float $dt): void    {        $dx = $tx - $n->x;        $dz = $tz - $n->z;        $l = hypot($dx, $dz);        if ($l < 0.05) {            return;        }        $step = Solids::step($g->zone, $n->x, $n->z, $dx / $l, $dz / $l, $speed * $dt, Solids::PERSON, [0.0, 0.7, -0.7, 1.4, -1.4],            static fn (float $nx, float $nz): bool => !Raft::forbidden($g, $nx, $nz));        if ($step !== null) {            $n->x = $step[0];            $n->z = $step[1];            $n->y = $g->zone->heightAt($step[0], $step[1]);        }        $n->yaw = atan2($dx, $dz);    }    /** Does someone keep watch over Rob's sleep? */    public static function watch(Game $g): bool    {        return $g->companion !== null || (self::petFollowing($g) && ($g->pet['mode'] ?? '') !== 'stay');    }}