Lines 100.00% 20 / 20
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Joins 100.00% 20 / 20 100.00% 3 / 3 11 100.00% 1 / 1
 join 100.00% 10 / 10 100.00% 1 / 1 3
 leaveCombat 100.00% 7 / 7 100.00% 1 / 1 4
 refusal 100.00% 3 / 3 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Bot\Abilities\Moves;
6
7use Generator;
8use Lorekeeper\Client\Command\Map\JoinMapCommand;
9use Lorekeeper\Client\Script\Await;
10use Lorekeeper\Client\Script\Instruction;
11use Lorekeeper\Client\Script\TimedOut;
12use Lorekeeper\Core\Game\Combat\CombatState;
13use Lorekeeper\Core\World\Map\MapCell;
14use Lorekeeper\Core\World\Map\MapName;
15use Lorekeeper\Core\World\Map\MapPad;
16use Lorekeeper\Core\World\Map\MapSpot;
17use Lorekeeper\Server\Event\Event;
18use Lorekeeper\Server\Event\Map\MapJoins;
19use Lorekeeper\Server\Event\Map\MapRefusals;
20use Lorekeeper\Server\Event\Player\PlayerStateUpdatedEvent;
21use Psl\DateTime\Duration;
22use Psl\Option;
23use RuntimeException;
24
25trait Joins
26{
27    use Jumps;
28
29    private const int SECONDS_TO_LEAVE_COMBAT = 10;
30
31    /**
32     * @throws RuntimeException
33     *
34     * @return Generator<int, Instruction, null|Event|TimedOut, void>
35     */
36    protected function join(MapName $map): Generator
37    {
38        if ($this->me()->location()->map->name->value === $map->value) {
39            return;
40        }
41
42        yield from $this->leaveCombat();
43
44        /** @var Event|TimedOut $joined */
45        $joined = yield $this->send(new JoinMapCommand($this->me()->hero()->name, $map, Option\none()))->awaits(
46            Duration::seconds(15),
47            MapJoins::class,
48            MapRefusals::class,
49        );
50
51        if (!MapJoins::contains($joined)) {
52            throw new RuntimeException("Could not join {$map->value}: " . self::refusal($joined));
53        }
54    }
55
56    /** @return Generator<int, Instruction, null|Event|TimedOut, void> */
57    private function leaveCombat(): Generator
58    {
59        if ($this->me()->state() !== CombatState::Fighting) {
60            return;
61        }
62
63        yield from $this->jump(new MapSpot(new MapCell('Enter'), MapPad::Spawn));
64        for ($second = 0; $second < self::SECONDS_TO_LEAVE_COMBAT; $second++) {
65            if ($this->me()->state() !== CombatState::Fighting) {
66                return;
67            }
68
69            yield new Await([PlayerStateUpdatedEvent::class], Duration::seconds(1));
70        }
71    }
72
73    private static function refusal(mixed $answer): string
74    {
75        return match (true) {
76            $answer instanceof Event => $answer->summary(),
77            $answer instanceof TimedOut => 'no answer',
78            default => 'the server refused',
79        };
80    }
81}