JA
games/rob-revisited / src / Revisited / Land / Combat.php · commit f9a1307
<?phpnamespace App\Revisited\Land;/** * The combat mode (docs/reborn.md "Combat mode"): it engages when a beast or a hostile person comes for Rob (hunting, * winding up a blow) or when Rob strikes one, and lets go when the foe dies, flees or is left behind. While it is on: * *  - a target (the nearest threat, the one nearest the crosshair first): its name, health and intention for the HUD *    (`info()`: the glow of a blow being wound up, "va charger"), and a soft camera assist toward it (only while the *    mouse / finger does not look: Intent::$assist); *  - the precision cursor: a melee blow is aimed (the cursor sweeps the bar in AIM seconds), the second press strikes: *    the centre is a critical (×CRIT), the middle a plain blow, the edges weak (×WEAK); no second press: weak at the end; *  - the dodge (the jump key: a step back, or aside with a turn held): DODGE metres in DODGE_TIME s, harmless blows for *    INVULNERABLE s (+ the footwork talent), a little rest spent; *  - popups (damage, CRITIQUE, contre, esquive) for the HUD. * * Pure logic on Game's state, not saved (a loaded game starts calm). */final class Combat{    public const HOSTILE = ['stalker', 'crawler', 'burrower', 'glacier_brute', 'swarm', 'river_croc', 'lava_crab'];    /** a threat this near engages the mode; the mode lets go past RELEASE metres or CALM s without a threat */    public const ENGAGE = 12.0;    public const RELEASE = 22.0;    public const CALM = 2.5;    /** the precision cursor: seconds to sweep the bar; the plain zone's half width; the multipliers */    public const AIM = 1.0;    public const GOOD = 0.32;    public const CRIT = 1.5;    public const WEAK = 0.7;    /** the dodge: metres, seconds of the move, seconds blows miss, seconds before the next, rest spent */    public const DODGE = 2.6;    public const DODGE_TIME = 0.26;    public const INVULNERABLE = 0.32;    public const DODGE_COOL = 0.7;    public const DODGE_COST = 1.6;    /** seconds a beast winds up its blow before it lands (the telegraph); 0: at once */    public const WINDUP = ['crawler' => 0.5, 'stalker' => 0.6, 'burrower' => 0.5, 'glacier_brute' => 0.85, 'river_croc' => 0.7, 'lava_crab' => 0.45, 'swarm' => 0.0];    /** a human's blow and an archer's aim */    public const HUMAN_WINDUP = 0.55;    public const BOW_AIM = 0.6;    public bool $active = false;    /** the foe followed: 'c' + creature id or 'n' + npc id */    public ?string $target = null;    private float $calm = 0.0;    /** seconds left of the dodge's move / of its invulnerability; its direction (x, z); seconds before the next */    public float $dodgeMove = 0.0;    public float $dodgeSafe = 0.0;    /** @var array{0: float, 1: float} */    public array $dodgeDir = [0.0, 0.0];    public float $dodgeCool = 0.0;    /** Rob shaken by a blow: slower for a moment */    public float $stagger = 0.0;    /** @var list<array{0: string, 1: float, 2: array{0: int, 1: int, 2: int}}> text, age (s), colour */    public array $popups = [];    /** the grade of the last aimed blow (crit | good | weak) and when (Game::$clock) */    public ?string $lastGrade = null;    public float $lastGradeAt = -9.0;    /** Grade of the cursor's position (0..1) with a critical zone $sweet wide: [grade, multiplier]. */    public static function grade(float $pos, float $sweet): array    {        $off = abs($pos - 0.5);        if ($off <= $sweet / 2) {            return ['crit', self::CRIT];        }        if ($off <= self::GOOD) {            return ['good', 1.0];        }        return ['weak', self::WEAK];    }    /** Is this beast or person one Rob may fight (and that may fight him)? */    public static function foe(Creature|Npc $t): bool    {        if (!empty($t->data['companion'])) {            return false;        }        return $t instanceof Creature ? in_array($t->species, self::HOSTILE, true) : $t->hostile;    }    /** Coming for Rob right now: hunting him, winding up a blow, an angry crawler, a person on the attack. */    public static function threatening(Game $g, Creature|Npc $t): bool    {        if (!self::foe($t)) {            return false;        }        $d = hypot($t->x - $g->x, $t->z - $g->z);        if ($t instanceof Npc) {            return in_array($t->state, ['attack', 'alert'], true) && $d < 20;        }        if ($t->state === 'buried' || $t->state === 'flee' || $t->state === 'dead') {            return false;        }        if ((float) ($t->data['wu'] ?? 0) > 0 || (float) ($t->data['angry'] ?? 0) > 0) {            return $d < self::RELEASE;        }        return in_array($t->state, ['hunt', 'attack'], true) && $d < self::ENGAGE;    }    /** The mode turns on with this foe as its target (Rob struck it, or it attacked). */    public function engage(Game $g, Creature|Npc $t): void    {        if (!self::foe($t) && !($t instanceof Npc && $t->state === 'surrender')) {            return;        }        if (!$this->active) {            $this->active = true;            $g->events[] = ['engage', 0.0, 0.7];        }        if ($t instanceof Creature) {            $t->data['hp0'] ??= max((float) (Wildlife::SPECIES[$t->species]['hp'] ?? $t->health), $t->health);        }        $this->target = ($t instanceof Creature ? 'c' : 'n') . $t->id;        $this->calm = 0.0;    }    /** The target, if still there. */    public function foeObject(Game $g): Creature|Npc|null    {        if ($this->target === null) {            return null;        }        $id = (int) substr($this->target, 1);        foreach ($this->target[0] === 'c' ? $g->creatures : $g->npcs as $t) {            if ($t->id === $id) {                return $t;            }        }        return null;    }    /** Each frame (Game::update): engages, picks the target, lets go, eases the camera, moves the dodge, ages popups. */    public function update(Game $g, float $dt, Intent $in): void    {        $this->dodgeCool = max(0.0, $this->dodgeCool - $dt);        $this->dodgeSafe = max(0.0, $this->dodgeSafe - $dt);        $this->stagger = max(0.0, $this->stagger - $dt);        if ($this->dodgeMove > 0) {            $step = min($dt, $this->dodgeMove);            $this->dodgeMove -= $step;            $v = self::DODGE / self::DODGE_TIME * $step;            $g->shove($this->dodgeDir[0] * $v, $this->dodgeDir[1] * $v);        }        $popups = [];        foreach ($this->popups as [$text, $age, $col]) {            if ($age + $dt < 1.4) {                $popups[] = [$text, $age + $dt, $col];            }        }        $this->popups = $popups;        // the threats: the one nearest the crosshair (then the nearest) leads        $best = null;        $bestScore = 1e9;        foreach (array_merge($g->creatures, $g->npcs) as $t) {            if (!self::threatening($g, $t)) {                continue;            }            $score = hypot($t->x - $g->x, $t->z - $g->z) + 4.0 * abs(self::angleTo($g, $t));            if ($score < $bestScore) {                $best = $t;                $bestScore = $score;            }        }        $cur = $this->foeObject($g);        if ($best !== null) {            if ($cur === null || !self::threatening($g, $cur)) {                $this->engage($g, $best);                $cur = $best;            }            $this->calm = 0.0;        } elseif ($this->active) {            $gone = $cur === null || ($cur instanceof Creature && ($cur->state === 'flee' || $cur->state === 'wander' || $cur->state === 'buried'))                || ($cur instanceof Npc && ($cur->state === 'flee' || !$cur->hostile))                || hypot($cur->x - $g->x, $cur->z - $g->z) > self::RELEASE;            $this->calm += $gone ? $dt * 2.0 : $dt * 0.5;            if ($this->calm >= self::CALM) {                $this->disengage();                return;            }        }        if (!$this->active || $cur === null) {            return;        }        // the soft camera assist: a little turn toward the target, never when the player looks himself        if ($in->assist && $g->sleeping === null) {            $diff = self::angleTo($g, $cur);            $d = hypot($cur->x - $g->x, $cur->z - $g->z);            if (abs($diff) < 1.4 && abs($diff) > 0.03 && $d > 0.6) {                $g->yaw += $diff * min(1.0, 2.4 * $dt) * 0.6;            }            if ($d < 8.0) {                // and a little down toward a low beast close by (a crawler at Rob's feet)                $want = max(-0.7, min(0.3, atan2($cur->y + 0.5 - $g->eyeY(), max(0.8, $d))));                $g->pitch += ($want - $g->pitch) * min(1.0, 2.0 * $dt) * 0.5;            }        }    }    public function disengage(): void    {        $this->active = false;        $this->target = null;        $this->calm = 0.0;    }    /** Radians from Rob's gaze to the foe (positive: to the left, the yaw grows that way). */    public static function angleTo(Game $g, Creature|Npc $t): float    {        $a = atan2($t->x - $g->x, $t->z - $g->z) - $g->yaw;        return atan2(sin($a), cos($a));    }    /** A blow lands right now? false: Rob is dodging (or got out of reach while it was wound up). */    public function evades(Game $g, Creature|Npc $t, float $reach): bool    {        return $this->dodgeSafe > 0 || hypot($t->x - $g->x, $t->z - $g->z) > $reach;    }    public function popup(string $text, array $col): void    {        $this->popups[] = [$text, 0.0, $col];        if (count($this->popups) > 4) {            array_shift($this->popups);        }    }    /**     * What the HUD shows of the target: name, health 0..1, intention (strike: a blow wound up, charge: running at Rob,     * aim: an archer aiming, keep: held off by the flame, flee), wind 0..1 (how far the blow is wound up), distance.     * @return array{name: string, hp: float, intent: ?string, wind: float, dist: float}|null     */    public function info(Game $g): ?array    {        $t = $this->active ? $this->foeObject($g) : null;        if ($t === null) {            return null;        }        $d = hypot($t->x - $g->x, $t->z - $g->z);        $wu = (float) ($t->data['wu'] ?? 0);        $wuT = max(0.01, (float) ($t->data['wuT'] ?? 1));        if ($t instanceof Creature) {            $name = Wildlife::the($t->species, true);            $hp = max(0.0, $t->health) / max(1.0, (float) ($t->data['hp0'] ?? Wildlife::SPECIES[$t->species]['hp'] ?? 100));            $intent = $wu > 0 ? 'strike' : match (true) {                $t->state === 'flee' => 'flee',                $t->state === 'keep' => 'keep',                $t->state === 'hunt' && $d > 3.5 => 'charge',                default => null,            };        } else {            $name = Folk::the($t, true);            $hp = max(0.0, $t->health) / 100.0;            $intent = $wu > 0 ? (($t->data['arm'] ?? '') === 'bow' ? 'aim' : 'strike') : ($t->state === 'flee' ? 'flee' : ($t->state === 'alert' && $d > 3.5 ? 'charge' : null));        }        return ['name' => $name, 'hp' => min(1.0, $hp), 'intent' => $intent, 'wind' => $wu > 0 ? 1 - $wu / $wuT : 0.0, 'dist' => $d];    }}