DE
games/rob-revisited / src / Revisited / Sim / Body.php · commit f9a1307
<?phpnamespace App\Revisited\Sim;/** * Rob's body. Vitals: health, hunger, thirst, fatigue, morale are 0..100 and HIGHER IS BETTER (hunger 100 = full, * fatigue 100 = rested). Blood in litres (5.5 full), temperature in °C. Time is given to tick() in game minutes. */final class Body{    public const PARTS = ['head', 'torso', 'larm', 'rarm', 'lleg', 'rleg'];    public const BLOOD_MAX = 5.5;    public const BLOOD_DEATH = 2.0;    public const BLOOD_SHOCK = 3.6;       // below it health drains    public const CLOT = 0.003;            // fraction of a bleed that clots per minute    public const INFECT_DELAY = 300.0;    // minutes before a dirty wound can infect    public const INFECT_RATE = 0.0007;    // per minute    public const THIRST_RATE = 0.045;     // points per minute at full pace    public const HUNGER_RATE = 0.022;    public const FATIGUE_RATE = 0.07;    public const SLEEP_RECOVERY = 0.35;    public const SHELTER_WARMTH = 4.0;    public const FIRE_WARMTH = 14.0;    public const EFFORT_WARMTH = 8.0;    public const WET_COLD = 10.0;    public const COLD_SLOPE = 0.2;        // °C of core temperature lost per degree of discomfort    public const HEAT_SLOPE = 0.1;    public const DEHYDRATION_LOSS = 0.12; // health per minute at thirst 0    public const STARVATION_LOSS = 0.03;    public const POISON_LOSS = 0.22;      // times severity, per minute    public const REGEN = 0.015;    /** fitness (percent around 0): the range, the most a day of training gives (at 0), the training that gives 63 % of it */    public const FIT_MIN = -20.0;    public const FIT_MAX = 40.0;    public const FIT_GAIN = ['endurance' => 1.5, 'force' => 1.2];    public const FIT_TAU = ['endurance' => 60.0, 'force' => 45.0];    /** percent lost per day without training (above 0; below it, slower and slower toward FIT_MIN) */    public const FIT_DECAY = 0.8;    private const DAY = 1440.0;    private const KIND_LABEL = ['cut' => 'Coupure', 'bite' => 'Morsure', 'burn' => 'Brûlure', 'bruise' => 'Contusion', 'fracture' => 'Fracture'];    private const PART_LABEL = ['head' => 'à la tête', 'torso' => 'au torse', 'larm' => 'au bras gauche', 'rarm' => 'au bras droit', 'lleg' => 'à la jambe gauche', 'rleg' => 'à la jambe droite'];    private const PART_NAME = ['head' => 'la tête', 'torso' => 'le torse', 'larm' => 'le bras gauche', 'rarm' => 'le bras droit', 'lleg' => 'la jambe gauche', 'rleg' => 'la jambe droite'];    private const SHOCK = ['cut' => 8.0, 'bite' => 14.0, 'burn' => 12.0, 'bruise' => 5.0, 'fracture' => 12.0];    private const DEATH_TEXT = [        'blood' => 'Tu t\'es vidé de ton sang. Une plaie laissée sans soin a eu raison de toi.',        'dehydration' => 'La soif t\'a tué : sans eau, le corps lâche en quelques jours.',        'starvation' => 'Tu t\'es éteint de faim, trop faible pour continuer.',        'hypothermia' => 'Le froid t\'a emporté : ton corps ne s\'est jamais réchauffé.',        'heatstroke' => 'Un coup de chaleur t\'a terrassé : la fièvre du soleil et de la soif.',        'poison' => 'Le poison a fait son œuvre. Sans antidote, il n\'y avait plus d\'espoir.',        'infection' => 'Une plaie infectée a tourné en septicémie. La fièvre ne t\'a plus quitté.',        'dysentery' => 'La dysenterie t\'a vidé : l\'eau sale t\'a tué.',        'exhaustion' => 'Tu t\'es effondré d\'épuisement pour ne plus te relever.',        'trauma' => 'Tes blessures étaient trop graves. Rob Calder ne reverra jamais la station.',    ];    public bool $lastActionOk = true;   // did the last consume / treat / drink do something (the item is then spent)    public float $loadRatio = 0.0;      // Inventory::load(): a heavy bag slows the walk    private float $health = 100.0;    private float $blood = self::BLOOD_MAX;    private float $temp = 37.0;    private float $hunger = 85.0;    private float $thirst = 85.0;    private float $fatigue = 90.0;    private float $morale = 70.0;    /** @var list<array{part:string,kind:string,sev:float,treated:bool,bleed:float,dirty:bool,infection:float,age:float}> */    private array $inj = [];    private float $poison = 0.0;    private float $dysentery = 0.0;    private float $fever = 0.0;    private float $tea = 0.0;          // minutes left of the fever tea    private float $concussion = 0.0;   // minutes left    private bool $dead = false;    private ?string $cause = null;    /** @var array<string,float> recent damage by cause */    private array $dmg = [];    private int $seed = 20241;    private bool $lastWet = false;    private float $minutes = 0.0;    /** skin temperature (°C) of the hands and the feet: they freeze first */    private float $handsT = 33.0;    private float $feetT = 32.0;    /** long-term fitness, percent around 0: endurance (cardio: running, swimming, climbing), force (carrying, chopping, climbing, fighting) */    private float $endurance = 0.0;    private float $force = 0.0;    /** the training of the current day (effort-minutes) and that day's number */    private float $cardioToday = 0.0;    private float $strengthToday = 0.0;    private int $fitDay = 0;    /** @var array<int, array{0: float, 1: float}> day => [endurance, force] at its end (the last 8 days: the trend) */    private array $fitLog = [];    /** the 5 % step each stat was last told at */    private int $endStep = 0;    private int $forceStep = 0;    /** @var list<string> what Rob feels about his fitness, not told yet (Game says it: fitnessNews()) */    private array $fitNews = [];    // ---------------------------------------------------------------- time    public function tick(float $minutes, Environment $env): void    {        if ($this->dead || !($minutes > 0) || !is_finite($minutes)) {            return;            // NaN / INF minutes would loop forever below (INF - 5 = INF)        }        $minutes = min($minutes, 60.0 * 24 * 3);        $this->lastWet = $env->wet;        $left = $minutes;        while ($left > 0 && !$this->dead) {            $dt = min(5.0, $left);            $left -= $dt;            $this->step($dt, $env);        }    }    private function step(float $dt, Environment $env): void    {        $this->minutes += $dt;        $sleep = $env->sleeping;        $effort = $sleep ? 0.0 : max(0.0, min(1.6, $env->effort));        $loss = [];        // wounds: bleeding, infection, healing        $bled = 0.0;        foreach ($this->inj as $i => &$w) {            $w['age'] += $dt;            if ($w['bleed'] > 0) {                $bled += $w['bleed'] * $dt;                $w['bleed'] *= max(0.0, 1 - self::CLOT * $dt);                if ($w['bleed'] < 0.0002) {                    $w['bleed'] = 0.0;                }            }            $open = in_array($w['kind'], ['cut', 'bite', 'burn'], true);            if ($open && $w['dirty'] && $w['age'] > self::INFECT_DELAY) {                $rate = self::INFECT_RATE * (0.5 + $w['sev']) * ($w['treated'] ? 0.3 : 1.0) * ($env->wet ? 1.5 : 1.0);                $w['infection'] = min(1.2, $w['infection'] + $rate * $dt);            } elseif (!$w['dirty'] && $w['infection'] > 0) {                $w['infection'] = max(0.0, $w['infection'] - 0.0006 * $dt);            }            if ($w['kind'] === 'fracture') {                $heal = $w['treated'] ? 0.00018 : 0.0;            } elseif ($w['kind'] === 'bruise') {                $heal = 0.0005;            } else {                $heal = $w['treated'] ? 0.0006 : 0.0002;            }            if ($w['infection'] > 0.2) {                $heal = 0.0;            }            $w['sev'] -= $heal * $dt * ($sleep ? 1.5 : 1.0) * (($this->hunger > 25 && $this->thirst > 25) ? 1.0 : 0.4);            if ($w['sev'] <= 0.02) {                if ($w['infection'] < 0.05) {                    unset($this->inj[$i]);                } else {                    $w['sev'] = 0.02;                }            }        }        unset($w);        $this->inj = array_values($this->inj);        $this->blood -= $bled;        if ($bled <= 0 && $this->hunger > 20 && $this->thirst > 20 && $this->blood < self::BLOOD_MAX) {            $this->blood = min(self::BLOOD_MAX, $this->blood + 0.0003 * $dt);        }        if ($this->blood < self::BLOOD_SHOCK) {            $loss['blood'] = (self::BLOOD_SHOCK - $this->blood) * 0.08 * $dt;        }        $inf = $this->maxInfection();        if ($inf > 0.7) {            $loss['infection'] = ($inf - 0.6) * 0.25 * $dt;        }        // fever        $feverTarget = max($inf * 0.9, $this->dysentery * 0.5);        if ($this->tea > 0) {            $feverTarget *= 0.3;            $this->tea = max(0.0, $this->tea - $dt);        }        $this->fever += ($feverTarget - $this->fever) * min(1.0, 0.004 * $dt * ($feverTarget > $this->fever ? 1.0 : 2.0));        // temperature        $air = $env->airTemp;        $clothes = $env->clothing * max(0.0, min(1.0, (28 - $air) / 18));        $fire = $env->nearFire ? self::FIRE_WARMTH * max(0.15, min(1.0, (26 - $air) / 16)) : 0.0;        $eff = $air + $clothes + ($env->sheltered ? self::SHELTER_WARMTH : 0.0) + $fire + ($air < 22 ? $env->coldResist : 0.0)            + $effort * self::EFFORT_WARMTH - ($env->wet ? self::WET_COLD : 0.0);        // a bare head loses much of the body's heat in the cold        if ($env->regions !== []) {            $headBare = max(0.0, 2.5 - (float) ($env->regions['head'] ?? 0.0)) / 2.5;            $eff -= 3.0 * $headBare * max(0.0, min(1.0, (20 - $air) / 15));        }        $this->extremities($dt, $env, $air, $effort);        $target = 37.0;        if ($eff < 18) {            $target -= (18 - $eff) * self::COLD_SLOPE;        } elseif ($eff > 26) {            $target += ($eff - 26) * self::HEAT_SLOPE + ($this->thirst < 25 ? 0.8 : 0.0);        }        $target += $this->fever * 2.2;        $this->temp += ($target - $this->temp) * min(1.0, ($target < $this->temp ? 0.006 : 0.005) * $dt);        if (min($this->handsT, $this->feetT) < 5.0) {            $loss['hypothermia'] = 0.006 * (5.0 - min($this->handsT, $this->feetT)) * $dt;   // frostbite        }        if ($this->temp < 35.0) {            $loss['hypothermia'] = ($loss['hypothermia'] ?? 0.0) + ($this->temp < 32 ? 0.04 + (32 - $this->temp) * 0.05 : (35 - $this->temp) * 0.012) * $dt;        } elseif ($this->temp > 39.5) {            $loss['heatstroke'] = ($this->temp - 39.5) * 0.08 * $dt;        }        $ttl = ($sleep ? 0.6 : 1.0);        // thirst        $thirstRate = self::THIRST_RATE * (0.7 + $effort * 1.2) * $ttl * (1 + $this->fever)            * ($air > 30 ? 1 + ($air - 30) * 0.04 : 1.0) * ($this->dysentery > 0.02 ? 2.0 : 1.0) * ($this->poison > 0.02 ? 1.4 : 1.0) * $env->thirstMul;        $this->thirst = max(0.0, $this->thirst - $thirstRate * $dt);        if ($this->thirst <= 0) {            $loss['dehydration'] = self::DEHYDRATION_LOSS * $dt;        } elseif ($this->thirst < 12) {            $loss['dehydration'] = 0.02 * $dt;        }        // hunger        $hungerRate = self::HUNGER_RATE * (0.7 + $effort * 0.9) * $ttl * ($this->temp < 37 ? 1 + (37 - $this->temp) * 0.3 : 1.0)            * ($this->dysentery > 0.02 ? 1.5 : 1.0) * $env->hungerMul;        $this->hunger = max(0.0, $this->hunger - $hungerRate * $dt);        if ($this->hunger <= 0) {            $loss['starvation'] = self::STARVATION_LOSS * $dt;        }        // fatigue and sleep        if ($env->resting && !$sleep) {            // sitting down: a little rest, no more effort            $this->fatigue = min(100.0, $this->fatigue + self::SLEEP_RECOVERY * 0.3 * $this->recoveryFactor() * $dt);        } elseif ($sleep) {            $rec = self::SLEEP_RECOVERY * $env->comfort * ($env->sheltered ? 1.4 : 1.0) * ($env->nearFire ? 1.2 : 1.0) * ($this->temp < 35 ? 0.5 : 1.0)                * ($this->pain() > 0.5 ? 0.7 : 1.0) * $this->recoveryFactor();            $this->fatigue = min(100.0, $this->fatigue + $rec * $dt);        } else {            $this->fatigue = max(0.0, $this->fatigue - self::FATIGUE_RATE * (0.6 + $effort * 1.4 * $this->effortCost())                * ($this->concussion > 0 ? 1.4 : 1.0) * $dt);            if ($this->fatigue <= 0) {                $loss['exhaustion'] = 0.04 * $dt;            }        }        $this->trainTick($dt, $env, $sleep);        // poison, dysentery, concussion        if ($this->poison > 0) {            $loss['poison'] = $this->poison * self::POISON_LOSS * $dt;            $this->poison = max(0.0, $this->poison - 0.0008 * $dt);        }        if ($this->dysentery > 0) {            $loss['dysentery'] = $this->dysentery * 0.02 * $dt;            $this->dysentery = max(0.0, $this->dysentery - 0.0004 * $dt);        }        $this->concussion = max(0.0, $this->concussion - $dt);        // morale        $mt = 70 - $this->pain() * 30 - ($this->hunger < 30 ? 15 : 0) - ($this->thirst < 30 ? 20 : 0)            - ($this->temp < 35 ? 15 : 0) - ($this->fatigue < 25 ? 10 : 0) + ($env->sheltered ? 5 : 0) + ($env->nearFire ? 6 : 0);        $this->morale += ($mt - $this->morale) * min(1.0, 0.02 * $dt);        // apply damage / regeneration        $total = array_sum($loss);        foreach ($this->dmg as $c => $v) {            $this->dmg[$c] = $v * max(0.0, 1 - 0.001 * $dt);        }        if ($total > 0) {            $this->health -= $total;            foreach ($loss as $c => $v) {                $this->dmg[$c] = ($this->dmg[$c] ?? 0.0) + $v;            }        } elseif ($bled <= 0 && $this->health < 100) {            $good = ($this->hunger > 40 && $this->thirst > 40) ? 1.0 : 0.3;            $this->health = min(100.0, $this->health + self::REGEN * $dt * ($sleep ? 2.0 : 1.0) * $good);        }        if ($this->blood <= self::BLOOD_DEATH) {            $this->die('blood');        } elseif ($this->temp < 27.0) {            $this->die('hypothermia');        } elseif ($this->temp > 42.0) {            $this->die('heatstroke');        } elseif ($this->health <= 0) {            $this->die($this->worstCause());        }    }    /** The hands and the feet cool down faster than the core: gloves, boots, a fire or effort keep them warm. */    private function extremities(float $dt, Environment $env, float $air, float $effort): void    {        if ($env->regions === []) {            return;     // a caller that does not give the regions (old code, tests): nothing to follow        }        $fire = $env->nearFire ? 16.0 * max(0.2, min(1.0, (26 - $air) / 16)) : 0.0;        foreach (['hands' => 'handsT', 'feet' => 'feetT'] as $region => $field) {            $cover = (float) ($env->regions[$region] ?? 0.0);            $local = $air + $fire + ($env->sheltered ? self::SHELTER_WARMTH : 0.0) + $effort * 5.0 + $cover * 3.2                - ($env->wet ? 8.0 : 6.0 * $env->wetness) - ($region === 'feet' && $env->wet ? 3.0 : 0.0);            $core = min($this->temp, 37.0);            $target = $local >= 22 ? $core - 4.0 : max($local, $core - 4.0 - (22 - $local) * 0.75);            $target = max(-5.0, min($core - 3.0, $target));            $this->$field += ($target - $this->$field) * min(1.0, 0.04 * $dt);        }    }    /** @return array{hands: float, feet: float} skin temperature of the extremities (°C) */    public function extremityTemps(): array    {        return ['hands' => $this->handsT, 'feet' => $this->feetT];    }    private function worstCause(): string    {        $best = 'trauma';        $v = -1.0;        foreach ($this->dmg as $c => $x) {            if ($x > $v) {                $v = $x;                $best = $c;            }        }        return $best;    }    private function die(string $cause): void    {        $this->dead = true;        $this->health = 0.0;        $this->cause = $cause;    }    // ---------------------------------------------------------------- state    public function dead(): bool    {        return $this->dead;    }    public function causeOfDeath(): ?string    {        return $this->cause === null ? null : (self::DEATH_TEXT[$this->cause] ?? self::DEATH_TEXT['trauma']);    }    /** Machine id of the cause (blood, dehydration, starvation, hypothermia, heatstroke, poison, infection, ...). */    public function causeId(): ?string    {        return $this->cause;    }    /** @return array<string,float> */    public function vitals(): array    {        $bleed = 0.0;        foreach ($this->inj as $w) {            $bleed += $w['bleed'];        }        return [            'health' => $this->health, 'blood' => $this->blood, 'temperature' => $this->temp,            'hunger' => $this->hunger, 'thirst' => $this->thirst, 'fatigue' => $this->fatigue, 'morale' => $this->morale,            'bleeding' => $bleed,      // litres per minute right now            'fever' => $this->fever,   // 0..1        ];    }    /** @return list<array{part:string,kind:string,severity:float,treated:bool,label:string}> */    public function injuries(): array    {        $out = [];        foreach ($this->inj as $w) {            $label = self::KIND_LABEL[$w['kind']] . ' ' . self::PART_LABEL[$w['part']];            if ($w['treated']) {                $label .= $w['kind'] === 'fracture' ? ' (attelle)' : ' (soignée)';            } elseif ($w['bleed'] > 0) {                $label .= ' (saigne)';            }            if ($w['infection'] > 0.15) {                $label .= ' (infectée)';            }            $out[] = ['part' => $w['part'], 'kind' => $w['kind'], 'severity' => $w['sev'], 'treated' => $w['treated'], 'label' => $label];        }        return $out;    }    /** @return list<array{id:string,label:string,severity:float}> */    public function conditions(): array    {        $c = [];        $add = function (string $id, string $label, float $sev) use (&$c) {            $c[] = ['id' => $id, 'label' => $label, 'severity' => max(0.0, min(1.0, $sev))];        };        $bleed = $this->vitals()['bleeding'];        if ($bleed > 0) {            $add('bleeding', 'Hémorragie', $bleed / 0.008);        }        if ($this->blood < self::BLOOD_SHOCK) {            $add('shock', 'Choc hémorragique', (self::BLOOD_SHOCK - $this->blood) / 1.6);        }        $inf = $this->maxInfection();        if ($inf > 0.1) {            $add('infection', 'Infection', $inf);        }        if ($this->fever > 0.15) {            $add('fever', 'Fièvre', $this->fever);        }        if ($this->poison > 0.02) {            $add('poison', 'Empoisonnement', $this->poison);        }        if ($this->dysentery > 0.02) {            $add('dysentery', 'Dysenterie', $this->dysentery);        }        if ($this->temp < 35.0) {            $add('hypothermia', 'Hypothermie', (35 - $this->temp) / 6);        }        if ($this->temp > 39.5) {            $add('heatstroke', 'Coup de chaleur', ($this->temp - 39.5) / 2.5);        }        if ($this->fatigue < 12) {            $add('exhaustion', 'Épuisement', (12 - $this->fatigue) / 12);        }        if ($this->hunger < 8) {            $add('starvation', 'Inanition', (8 - $this->hunger) / 8);        }        if ($this->thirst < 12) {            $add('dehydration', 'Déshydratation', (12 - $this->thirst) / 12);        }        if ($this->concussion > 0) {            $add('concussion', 'Commotion', $this->concussion / 360);        }        if ($this->handsT < 15) {            $add('cold_hands', $this->handsT < 6 ? 'Mains gelées' : 'Mains engourdies', (15 - $this->handsT) / 15);        }        if ($this->feetT < 15) {            $add('cold_feet', $this->feetT < 6 ? 'Pieds gelés' : 'Pieds engourdis', (15 - $this->feetT) / 15);        }        return $c;    }    // ---------------------------------------------------------------- hurting    public function wound(string $part, string $kind, float $severity): void    {        if ($this->dead || !in_array($part, self::PARTS, true) || !isset(self::KIND_LABEL[$kind])) {            return;        }        $severity = max(0.05, min(1.0, $severity));        $shock = self::SHOCK[$kind] * $severity * ($part === 'head' ? 1.5 : ($part === 'torso' ? 1.3 : 1.0));        $this->health -= $shock;        $this->dmg['trauma'] = ($this->dmg['trauma'] ?? 0.0) + $shock;        if ($part === 'head' && $severity >= 0.4) {            $this->concussion = max($this->concussion, 120 + 360 * $severity);        }        $bleed = match ($kind) {            'cut' => $severity * 0.008,            'bite' => $severity * 0.006,            'fracture' => $severity > 0.85 ? 0.004 : 0.0,            default => 0.0,        };        $dirty = $kind === 'bite' || ($kind === 'cut' && ($this->lastWet || $severity >= 0.4)) || ($kind === 'burn' && $severity >= 0.5);        foreach ($this->inj as &$w) {            if ($w['part'] === $part && $w['kind'] === $kind) {                $w['sev'] = min(1.0, max($w['sev'], $severity) + 0.3 * min($w['sev'], $severity));                $w['bleed'] += $bleed;                $w['treated'] = false;                $w['dirty'] = $w['dirty'] || $dirty;                unset($w);                $this->checkTrauma();                return;            }        }        unset($w);        $this->inj[] = ['part' => $part, 'kind' => $kind, 'sev' => $severity, 'treated' => false, 'bleed' => $bleed,            'dirty' => $dirty, 'infection' => 0.0, 'age' => 0.0];        $this->checkTrauma();    }    /** A venom or poison dose (a crawler's sting): severity 0..1. */    public function poison(float $severity): void    {        if (!$this->dead) {            $this->poison = min(1.0, $this->poison + max(0.0, $severity));        }    }    public function concuss(float $minutes): void    {        $this->concussion = max($this->concussion, $minutes);    }    private function checkTrauma(): void    {        if ($this->health <= 0 && !$this->dead) {            $this->die('trauma');        }    }    // ---------------------------------------------------------------- acting    public function consume(string $itemId): string    {        $this->lastActionOk = false;        if ($this->dead) {            return 'Tu ne peux plus rien faire.';        }        $d = Items::get($itemId);        $food = (float) ($d['food'] ?? 0);        $water = (float) ($d['water'] ?? 0);        $heal = $d['heal'] ?? [];        $risk = $d['risk'] ?? [];        $morale = (float) ($d['morale'] ?? 0);        if ($food <= 0 && $water <= 0 && !$heal && !$risk && $morale == 0) {            return 'Tu ne peux pas manger cela.';        }        $msgs = [];        if ($heal) {            $msgs = array_merge($msgs, $this->applyHeal($heal, null));            if (!$this->lastActionOk /* set by applyHeal() */ && $food <= 0 && $water <= 0) { // @phpstan-ignore booleanNot.alwaysTrue                return $msgs ? implode(' ', $msgs) : 'Cela ne te soigne pas pour l\'instant.';            }        }        if ($food > 0 && $water <= 0 && !$heal && $this->hunger > 95) {            return 'Tu n\'as pas faim.';        }        if ($water > 0 && $food <= 0 && !$heal && $this->thirst > 95) {            return 'Tu n\'as pas soif.';        }        if ($food > 0) {            $this->hunger = min(100.0, $this->hunger + $food);            $msgs[] = $food >= 30 ? 'Tu te sens rassasié.' : 'Cela calme un peu ta faim.';        }        if ($water > 0) {            $this->thirst = min(100.0, $this->thirst + $water);            if (!isset($risk['dirty'])) {                $msgs[] = 'Tu bois : la soif recule.';            }        }        if ($morale != 0) {            $this->morale = max(0.0, min(100.0, $this->morale + $morale));            if ($morale < 0) {                $msgs[] = 'Pouah ! Il faut avoir faim pour avaler ça... Ton moral en prend un coup.';            }        }        if (isset($risk['poison'])) {            $this->poison((float) $risk['poison']);            $msgs[] = 'Un goût âcre... Ton ventre se tord : tu es empoisonné !';        }        if (isset($risk['raw']) && $this->rnd() < $risk['raw']) {            $this->dysentery = max($this->dysentery, $risk['raw'] < 0.2 ? 0.2 : 0.35);            $msgs[] = $risk['raw'] < 0.2 ? 'Ton ventre se tord : c\'était cru, et pas très propre.' : 'Cette chair crue ne passe pas : ton ventre gronde.';        }        if (isset($risk['dirty']) && $this->rnd() < $risk['dirty']) {            $this->dysentery = max($this->dysentery, $risk['dirty'] < 0.3 ? 0.3 : 0.5);            $msgs[] = $risk['dirty'] < 0.3 ? 'Cette eau n\'était pas si propre : ton ventre se révolte, dysenterie.' : 'Cette eau trouble te donne la dysenterie.';        } elseif (isset($risk['dirty'])) {            $msgs[] = $risk['dirty'] < 0.3 ? 'Tu bois l\'eau filtrée. Elle a encore un petit goût de terre.' : 'Tu bois l\'eau trouble. Cette fois, rien... pour l\'instant.';        }        $this->lastActionOk = true;        return implode(' ', $msgs);    }    /**     * Water from a lake or stream (dirty: dysentery risk $risk, 0.6 for still water) or clean (a spring, a waterfall:     * $risk 0 unless given: running water is safer than the lake, not perfectly safe).     */    public function drink(bool $clean, ?float $risk = null): string    {        $risk ??= $clean ? 0.0 : 0.6;        $this->lastActionOk = false;        if ($this->dead) {            return 'Tu ne peux plus rien faire.';        }        if ($this->thirst > 95) {            return 'Tu n\'as pas soif.';        }        $this->thirst = min(100.0, $this->thirst + 35);        $this->lastActionOk = true;        if ($risk <= 0.0) {            return 'Tu bois à longues gorgées une eau pure.';        }        if ($this->rnd() < $risk) {            if ($risk < 0.3) {                $this->dysentery = max($this->dysentery, 0.25);                return 'L\'eau vive semblait pure... ton ventre n\'est pas d\'accord : un début de dysenterie.';            }            $this->dysentery = max($this->dysentery, 0.5);            return 'Tu bois à même la mare... Ton ventre se révolte : dysenterie !';        }        return 'Tu bois l\'eau trouble. Tu as de la chance : pour l\'instant, rien.';    }    /** Use a medical item on a body part. The item is spent when $lastActionOk is true. */    public function treat(string $itemId, string $part): string    {        $this->lastActionOk = false;        if ($this->dead) {            return 'Tu ne peux plus rien faire.';        }        $heal = Items::get($itemId)['heal'] ?? [];        if (!$heal) {            return 'Cela ne soigne rien.';        }        if (!in_array($part, self::PARTS, true)) {            $part = 'torso';        }        $msgs = $this->applyHeal($heal, $part);        return $msgs !== [] ? implode(' ', $msgs) : 'Il n\'y a rien à soigner ici.';    }    /** @return list<string> messages; sets lastActionOk when something was done */    private function applyHeal(array $heal, ?string $part): array    {        $this->lastActionOk = false;        $msgs = [];        $ok = false;        $partName = $part !== null ? self::PART_NAME[$part] : 'le corps';        if (!empty($heal['bleed'])) {            $n = 0;            foreach ($this->inj as &$w) {                if (($part === null || $w['part'] === $part) && in_array($w['kind'], ['cut', 'bite', 'burn'], true) && !$w['treated']) {                    $w['treated'] = true;                    $w['bleed'] = 0.0;                    $n++;                }            }            unset($w);            if ($n > 0) {                $ok = true;                $msgs[] = 'Tu bandes la plaie sur ' . $partName . ' : le sang ne coule plus.';            } else {                $msgs[] = 'Il n\'y a pas de plaie à bander sur ' . $partName . '.';            }        }        if (!empty($heal['fracture'])) {            $n = 0;            foreach ($this->inj as &$w) {                if (($part === null || $w['part'] === $part) && $w['kind'] === 'fracture' && !$w['treated']) {                    $w['treated'] = true;                    $w['bleed'] = 0.0;                    $n++;                }            }            unset($w);            if ($n > 0) {                $ok = true;                $msgs[] = 'Tu poses une attelle sur ' . $partName . ' : l\'os est maintenu.';            } else {                $msgs[] = 'Aucune fracture à immobiliser sur ' . $partName . '.';            }        }        if (isset($heal['infection'])) {            $n = 0;            foreach ($this->inj as &$w) {                if (($part === null || $w['part'] === $part) && $w['kind'] !== 'fracture' && $w['kind'] !== 'bruise') {                    $w['infection'] = max(0.0, $w['infection'] - (float) $heal['infection']);                    if (!empty($heal['clean'])) {                        $w['dirty'] = false;                    }                    $w['treated'] = true;                    $n++;                }            }            unset($w);            if ($n > 0) {                $ok = true;                $msgs[] = 'Tu nettoies et soignes la plaie sur ' . $partName . '.';            } else {                $msgs[] = 'Il n\'y a pas de plaie à nettoyer sur ' . $partName . '.';            }        }        if (!empty($heal['poison'])) {            if ($this->poison > 0.02) {                $this->poison = 0.0;                $ok = true;                $msgs[] = 'L\'antidote agit : le poison se dissipe.';            } else {                $msgs[] = 'Tu n\'es pas empoisonné.';            }        }        if (isset($heal['fever'])) {            if ($this->fever > 0.05) {                $this->fever = max(0.0, $this->fever - (float) $heal['fever']);                $this->tea = 240.0;                $this->temp = max(36.0, $this->temp - 0.6);                $ok = true;                $msgs[] = 'La tisane amère fait baisser la fièvre.';            } else {                $msgs[] = 'Tu n\'as pas de fièvre.';            }        }        if (isset($heal['health'])) {            if ($this->health < 100) {                $this->health = min(100.0, $this->health + (float) $heal['health']);                $ok = true;                $msgs[] = 'Tu te sens un peu mieux.';            } elseif (count($heal) === 1) {                $msgs[] = 'Tu es en pleine forme.';            }        }        $this->lastActionOk = $ok;        return $msgs;    }    // ---------------------------------------------------------------- derived    /** 0..1: how much the wounds hurt. */    /** A lift (or a blow) to the spirits: a pet's purr, a kind word, a death seen. */    public function morale(float $points): void    {        $this->morale = max(0.0, min(100.0, $this->morale + $points));    }    /** A hard effort (climbing): rest spent at once, the breath short (less for a fit, strong body). */    public function exert(float $points): void    {        $e = $this->endurance / 100;        $f = $this->force / 100;        $this->fatigue = max(0.0, $this->fatigue - $points * max(0.5, 1 - 0.4 * $e - 0.4 * $f));    }    // ---------------------------------------------------------------- fitness    /**     * The long-term training. Each day, effort trains (diminishing returns: the first hour of running gives most, the     * day's gain is capped by FIT_GAIN; the higher the stat, the smaller the gain), and a day without it loses some.     * Hunger, illness and wounds slow the gains.     */    private function trainTick(float $dt, Environment $env, bool $sleep): void    {        $day = (int) floor($this->minutes / self::DAY);        if ($day !== $this->fitDay) {            $this->fitLog[$this->fitDay] = [round($this->endurance, 2), round($this->force, 2)];            ksort($this->fitLog);            $this->fitLog = array_slice($this->fitLog, -8, null, true);            $this->fitDay = $day;            $this->cardioToday = $this->strengthToday = 0.0;        }        if (!$sleep) {            // running 1, sprinting / climbing 1.5, swimming 0.6, walking 0            $cardio = max(0.0, min(1.5, ($env->effort - 0.5) / 0.5));            if ($cardio > 0) {                $this->train('endurance', $cardio * $dt);            }            if ($env->strain > 0) {                $this->train('force', min(1.5, $env->strain) * $dt);            }        }        // without training, the body forgets (a sick or hurt body faster); a little training that day stops it        $sick = 1.0 + $this->pain() + $this->fever + min(1.0, $this->maxInfection());        foreach (['endurance' => $this->cardioToday, 'force' => $this->strengthToday] as $k => $today) {            $idle = max(0.0, 1.0 - $today / (self::FIT_TAU[$k] * 0.4));            if ($idle <= 0) {                continue;            }            $v = $this->$k;            $rate = $v > 0 ? self::FIT_DECAY : self::FIT_DECAY * 0.5 * ($v - self::FIT_MIN) / -self::FIT_MIN;            $this->$k = max(self::FIT_MIN, $v - $rate * $idle * $sick * $dt / self::DAY);        }        $this->fitSteps();    }    /**     * Training: $minutes of effort of that kind ('endurance': running, swimming, climbing; 'force': carrying, chopping,     * mining, climbing, fighting). Game calls it for the actions that are not a pace (a tree chopped: 12 minutes of force).     */    public function train(string $kind, float $minutes): void    {        if (!isset(self::FIT_GAIN[$kind]) || !($minutes > 0) || $this->dead) {            return;        }        $field = $kind === 'endurance' ? 'cardioToday' : 'strengthToday';        $a = $this->$field;        $b = $a + $minutes;        $this->$field = $b;        $tau = self::FIT_TAU[$kind];        $v = $this->$kind;        $room = max(0.0, (self::FIT_MAX - $v) / (self::FIT_MAX - self::FIT_MIN)) * 1.5;     // 1 at 0 %, 1.5 at the bottom, 0 at the top        $gain = self::FIT_GAIN[$kind] * $room * $this->trainFactor() * (exp(-$a / $tau) - exp(-$b / $tau));        $this->$kind = min(self::FIT_MAX, $v + $gain);        $this->fitSteps();    }    /** 0.1..1: how well the body builds up now (a hungry, sick or hurt body barely does). */    public function trainFactor(): float    {        $f = $this->hunger < 20 ? 0.25 : ($this->hunger < 45 ? 0.6 : 1.0);        $f *= $this->thirst < 20 ? 0.5 : 1.0;        $f *= 1.0 - min(0.7, $this->fever * 0.8 + $this->poison + $this->dysentery + max(0.0, $this->maxInfection() - 0.2));        $f *= 1.0 - 0.6 * $this->pain();        return max(0.1, $f);    }    /** Each 5 % step crossed: a word for the player (going down: once a point under the line, no flicker around it). */    private function fitSteps(): void    {        foreach ([['endurance', 'endStep', 'Tu te sens plus endurant : %+d %%', 'Ton endurance baisse : %+d %%'],            ['force', 'forceStep', 'Tu te sens plus fort : %+d %%', 'Ta force diminue : %+d %%']] as [$k, $stepField, $up, $down]) {            $v = $this->$k;            $step = (int) floor(($v + 0.0001) / 5);            $was = $this->$stepField;            if ($step > $was) {                $this->fitNews[] = sprintf($up, $step * 5);                $this->$stepField = $step;            } elseif ($v < $was * 5 - 1.0) {                $this->fitNews[] = sprintf($down, (int) round($v));                $this->$stepField = $step;            }        }    }    /** What Rob felt about his fitness since the last call (Game says it and shows it). @return list<string> */    public function fitnessNews(): array    {        $n = $this->fitNews;        $this->fitNews = [];        return $n;    }    /**     * The fitness, for the Body tab: each stat in percent, its change over the last 7 days.     * @return array{endurance: float, force: float, enduranceTrend: float, forceTrend: float}     */    public function fitness(): array    {        $old = null;        foreach ($this->fitLog as $d => $v) {            if ($d >= $this->fitDay - 7) {                $old = $v;                break;            }        }        $old ??= [$this->endurance, $this->force];        return ['endurance' => $this->endurance, 'force' => $this->force,            'enduranceTrend' => $this->endurance - $old[0], 'forceTrend' => $this->force - $old[1]];    }    /** Test bench / tools: sets the fitness (percent). */    public function setFitness(float $endurance, float $force): void    {        $this->endurance = max(self::FIT_MIN, min(self::FIT_MAX, $endurance));        $this->force = max(self::FIT_MIN, min(self::FIT_MAX, $force));        $this->endStep = (int) floor(($this->endurance + 0.0001) / 5);        $this->forceStep = (int) floor(($this->force + 0.0001) / 5);    }    /** The cost of effort on the rest (fatigue): an enduring body tires less (0.76 at +40 %, 1.12 at -20 %). */    public function effortCost(): float    {        return 1.0 - 0.6 * $this->endurance / 100;    }    /** How fast rest and sleep give the breath back (1.16 at +40 %, 0.92 at -20 %). */    public function recoveryFactor(): float    {        return 1.0 + 0.4 * $this->endurance / 100;    }    /** The rest (fatigue) the sprint needs: an enduring body sprints longer (12 at +40 %, 24 at -20 %). */    public function sprintThreshold(): float    {        return 20.0 * (1.0 - $this->endurance / 100);    }    /** The bag's capacity times this: 1.2 at +40 % force, 0.9 at -20 %. */    public function carryFactor(): float    {        return 1.0 + 0.5 * $this->force / 100;    }    /** Melee damage times this: 1.24 at +40 % force, 0.88 at -20 %. */    public function strengthFactor(): float    {        return 1.0 + 0.6 * $this->force / 100;    }    public function pain(): float    {        $p = 0.0;        foreach ($this->inj as $w) {            $k = $w['kind'] === 'fracture' ? ($w['treated'] ? 0.4 : 1.0) : ($w['treated'] ? 0.3 : 0.7);            $p += $w['sev'] * $k * ($w['infection'] > 0.3 ? 1.3 : 1.0);        }        return min(1.0, $p);    }    /** Walk speed multiplier: leg wounds, fatigue, cold, concussion and the bag's weight slow Rob. */    public function speedFactor(): float    {        $f = 1.0;        foreach ($this->inj as $w) {            if ($w['part'] !== 'lleg' && $w['part'] !== 'rleg') {                continue;            }            if ($w['kind'] === 'fracture') {                $f *= $w['treated'] ? 0.7 : 0.35;            } else {                $f *= 1 - $w['sev'] * ($w['treated'] ? 0.2 : 0.4);            }        }        if ($this->fatigue < 20) {            $f *= 0.7;        } elseif ($this->fatigue < 40) {            $f *= 0.9;        }        if ($this->temp < 33) {            $f *= 0.7;        }        if ($this->concussion > 0) {            $f *= 0.85;        }        if ($this->thirst < 10 || $this->hunger < 5) {            $f *= 0.8;        }        if ($this->feetT < 10) {            $f *= $this->feetT < 4 ? 0.7 : 0.88;        }        $f *= 1 - 0.3 * max(0.0, min(1.0, $this->loadRatio - 0.6) / 0.4);        return max(0.15, $f);    }    /** 0.2..1: how well the arms can fight. */    public function fightFactor(): float    {        $f = 1.0;        foreach ($this->inj as $w) {            if ($w['part'] === 'larm' || $w['part'] === 'rarm') {                $f *= $w['kind'] === 'fracture' ? ($w['treated'] ? 0.6 : 0.3) : 1 - $w['sev'] * 0.4;            }        }        if ($this->fatigue < 20) {            $f *= 0.8;        }        if ($this->concussion > 0) {            $f *= 0.85;        }        if ($this->handsT < 12) {            $f *= $this->handsT < 5 ? 0.6 : 0.8;        }        return max(0.2, $f);    }    /** The worst feelings, in French, worst first. */    public function feelings(): array    {        $f = [];        $add = function (float $weight, string $text) use (&$f) {            $f[] = [$weight, $text];        };        $v = $this->vitals();        if ($this->blood < self::BLOOD_SHOCK) {            $add(95, 'Tu es pâle, la tête te tourne : tu as perdu beaucoup de sang.');        } elseif ($v['bleeding'] > 0) {            $add(70, 'Tu saignes.');        }        if ($this->thirst < 12) {            $add(90, 'Ta gorge est en feu, tu as une soif terrible.');        } elseif ($this->thirst < 35) {            $add(60, 'Tu as soif.');        }        if ($this->hunger < 8) {            $add(85, 'Tu es affamé, tes jambes tremblent.');        } elseif ($this->hunger < 35) {            $add(50, 'Tu as faim.');        }        if ($this->temp < 33) {            $add(92, 'Tu grelottes violemment, tes pensées s\'engourdissent.');        } elseif ($this->temp < 35) {            $add(75, 'Tu as très froid.');        } elseif ($this->temp > 39.5) {            $add(92, 'Tu brûles, ta peau est sèche : coup de chaleur.');        } elseif ($this->temp > 38.2) {            $add(60, 'Tu as de la fièvre.');        }        if ($this->fatigue < 12) {            $add(80, 'Tu tombes de fatigue.');        } elseif ($this->fatigue < 35) {            $add(45, 'Tu es fatigué.');        }        if ($this->poison > 0.02) {            $add(88, 'Des crampes et des sueurs froides : tu es empoisonné.');        }        if ($this->dysentery > 0.02) {            $add(65, 'Ton ventre te fait souffrir : dysenterie.');        }        if ($this->handsT < 8) {            $add(70, 'Tes doigts ne t\'obéissent plus : il te faut des gants ou un feu.');        } elseif ($this->handsT < 15) {            $add(42, 'Tes mains sont engourdies de froid.');        }        if ($this->feetT < 8) {            $add(70, 'Tu ne sens plus tes pieds : il te faut des bottes sèches, un feu.');        } elseif ($this->feetT < 15) {            $add(42, 'Tes pieds sont glacés.');        }        if ($this->maxInfection() > 0.3) {            $add(72, 'Une de tes plaies est chaude et gonflée : elle s\'infecte.');        }        if ($this->concussion > 0) {            $add(55, 'Ta tête bourdonne.');        }        foreach ($this->inj as $w) {            if ($w['kind'] === 'fracture' && !$w['treated']) {                $add(78, 'Une fracture te fait hurler de douleur ' . self::PART_LABEL[$w['part']] . '.');            } elseif ($w['sev'] > 0.5 && !$w['treated']) {                $add(52, 'Tu as mal ' . self::PART_LABEL[$w['part']] . '.');            }        }        if ($this->morale < 20) {            $add(40, 'Le désespoir te gagne.');        }        usort($f, fn ($a, $b) => $b[0] <=> $a[0]);        return array_values(array_unique(array_map(fn ($x) => $x[1], $f)));    }    private function maxInfection(): float    {        $m = 0.0;        foreach ($this->inj as $w) {            $m = max($m, $w['infection']);        }        return $m;    }    /** Park-Miller random in 0..1 with 32-bit safe arithmetic (deterministic, saved). */    private function rnd(): float    {        $hi = intdiv($this->seed, 44488);        $lo = $this->seed % 44488;        $t = 48271 * $lo - 3399 * $hi;        $this->seed = $t > 0 ? $t : $t + 2147483647;        return $this->seed / 2147483647;    }    // ---------------------------------------------------------------- save    public function toArray(): array    {        return [            'health' => $this->health, 'blood' => $this->blood, 'temp' => $this->temp, 'hunger' => $this->hunger,            'thirst' => $this->thirst, 'fatigue' => $this->fatigue, 'morale' => $this->morale, 'inj' => $this->inj,            'poison' => $this->poison, 'dysentery' => $this->dysentery, 'fever' => $this->fever, 'tea' => $this->tea,            'concussion' => $this->concussion, 'dead' => $this->dead, 'cause' => $this->cause, 'dmg' => $this->dmg,            'seed' => $this->seed, 'wet' => $this->lastWet, 'minutes' => $this->minutes, 'load' => $this->loadRatio,            'handsT' => round($this->handsT, 2), 'feetT' => round($this->feetT, 2),            'fit' => ['e' => round($this->endurance, 3), 'f' => round($this->force, 3), 'ct' => round($this->cardioToday, 2),                'st' => round($this->strengthToday, 2), 'day' => $this->fitDay, 'log' => $this->fitLog, 'es' => $this->endStep, 'fs' => $this->forceStep],        ];    }    public static function fromArray(array $a): self    {        $b = new self();        foreach (['health', 'blood', 'temp', 'hunger', 'thirst', 'fatigue', 'morale', 'poison', 'dysentery', 'fever', 'tea', 'concussion', 'minutes', 'handsT', 'feetT'] as $k) {            if (isset($a[$k]) && is_finite((float) $a[$k])) {                $b->$k = (float) $a[$k];            }        }        $b->loadRatio = (float) ($a['load'] ?? 0.0);        // fitness (saves before it: 0 %, today's training starts now)        $fit = is_array($a['fit'] ?? null) ? $a['fit'] : [];        $b->setFitness((float) ($fit['e'] ?? 0.0), (float) ($fit['f'] ?? 0.0));        $b->cardioToday = max(0.0, (float) ($fit['ct'] ?? 0.0));        $b->strengthToday = max(0.0, (float) ($fit['st'] ?? 0.0));        $b->fitDay = (int) ($fit['day'] ?? floor($b->minutes / self::DAY));        foreach ((is_array($fit['log'] ?? null) ? $fit['log'] : []) as $d => $v) {            if (is_array($v) && count($v) >= 2) {                $b->fitLog[(int) $d] = [(float) $v[0], (float) $v[1]];            }        }        $b->endStep = isset($fit['es']) ? (int) $fit['es'] : $b->endStep;        $b->forceStep = isset($fit['fs']) ? (int) $fit['fs'] : $b->forceStep;        $b->dead = (bool) ($a['dead'] ?? false);        $b->cause = $a['cause'] ?? null;        $b->seed = (int) ($a['seed'] ?? 20241);        $b->lastWet = (bool) ($a['wet'] ?? false);        foreach (($a['dmg'] ?? []) as $c => $v) {            $b->dmg[(string) $c] = (float) $v;        }        foreach (($a['inj'] ?? []) as $w) {            if (isset($w['part'], $w['kind']) && in_array($w['part'], self::PARTS, true) && isset(self::KIND_LABEL[$w['kind']])) {                $b->inj[] = ['part' => $w['part'], 'kind' => $w['kind'], 'sev' => (float) ($w['sev'] ?? 0.1), 'treated' => (bool) ($w['treated'] ?? false),                    'bleed' => (float) ($w['bleed'] ?? 0), 'dirty' => (bool) ($w['dirty'] ?? false),                    'infection' => (float) ($w['infection'] ?? 0), 'age' => (float) ($w['age'] ?? 0)];            }        }        return $b;    }}