Lines 100.00% 117 / 117
Functions and Methods 100.00% 9 / 9
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
MovedToMapEvent 100.00% 117 / 117 100.00% 9 / 9 30 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 from 100.00% 17 / 17 100.00% 1 / 1 4
 summary 100.00% 1 / 1 100.00% 1 / 1 1
 arrival 100.00% 40 / 40 100.00% 1 / 1 2
 monsters 100.00% 25 / 25 100.00% 1 / 1 6
 players 100.00% 13 / 13 100.00% 1 / 1 1
 vitals 100.00% 6 / 6 100.00% 1 / 1 2
 room 100.00% 5 / 5 100.00% 1 / 1 4
 race 100.00% 9 / 9 100.00% 1 / 1 9
1<?php
2
3declare(strict_types=1);
4
5namespace Lorekeeper\Server\Event\Map;
6
7use InvalidArgumentException;
8use Lorekeeper\Core\Game\Asset\Gamefile;
9use Lorekeeper\Core\Game\Asset\Linkage;
10use Lorekeeper\Core\Game\Attribute\Health;
11use Lorekeeper\Core\Game\Attribute\Mana;
12use Lorekeeper\Core\Game\Attribute\Vitals;
13use Lorekeeper\Core\Player\Player;
14use Lorekeeper\Core\Player\PlayerLevel;
15use Lorekeeper\Core\Player\PlayerName;
16use Lorekeeper\Core\Player\PlayerSpawnId;
17use Lorekeeper\Core\Support\Gauge;
18use Lorekeeper\Core\World\Map\Map;
19use Lorekeeper\Core\World\Map\MapCell;
20use Lorekeeper\Core\World\Map\MapMonster;
21use Lorekeeper\Core\World\Map\MapMonsters;
22use Lorekeeper\Core\World\Map\MapName;
23use Lorekeeper\Core\World\Map\MapPlayer;
24use Lorekeeper\Core\World\Map\MapPlayers;
25use Lorekeeper\Core\World\Map\MapRoom;
26use Lorekeeper\Core\World\Map\MapSpot;
27use Lorekeeper\Core\World\Monster\Monster;
28use Lorekeeper\Core\World\Monster\MonsterAppearance;
29use Lorekeeper\Core\World\Monster\MonsterLevel;
30use Lorekeeper\Core\World\Monster\MonsterName;
31use Lorekeeper\Core\World\Monster\MonsterRace;
32use Lorekeeper\Core\World\Monster\MonsterSpawnId;
33use Lorekeeper\Server\AreaId;
34use Lorekeeper\Server\Event\Combat\Helper\CombatStates;
35use Lorekeeper\Server\Event\Event;
36use Lorekeeper\Server\Event\Map\Helper\MapPads;
37use Lorekeeper\Server\Event\NamedAfterClass;
38use Lorekeeper\Server\Exception\MalformedEventException;
39use Lorekeeper\Server\Message\JsonMessage;
40use Lorekeeper\Server\Message\Message;
41use Override;
42use Psl\Option;
43use Psl\Type;
44use Psl\Type\Exception\CoercionException;
45
46/**
47 * Our player arrived in a map, with the monsters and players already in the room.
48 *
49 * @psalm-type Arrival = array{
50 *     areaId: positive-int,
51 *     areaName: non-empty-string,
52 *     strMapName: non-empty-string,
53 *     strMapFileName: non-empty-string,
54 *     mondef?: list<array{MonID: positive-int, strMonName: non-empty-string, intLevel: positive-int, sRace: string, strMonFileName: non-empty-string, strLinkage: non-empty-string, ...}>,
55 *     monmap?: list<array{MonMapID: positive-int, MonID: positive-int, strFrame: non-empty-string, ...}>,
56 *     monBranch?: list<array{MonMapID: positive-int, intState: int<0, 2>, intHP: non-negative-int, intHPMax: non-negative-int, intMP: non-negative-int, intMPMax: non-negative-int, ...}>,
57 *     uoBranch?: list<array{entID: positive-int, strUsername: non-empty-string, intLevel: int<1, 100>, strFrame: non-empty-string, strPad: non-empty-string, intState: int<0, 2>, intHP: non-negative-int, intHPMax: non-negative-int, intMP: non-negative-int, intMPMax: non-negative-int, ...}>,
58 *     ...
59 * }
60 *
61 * @mago-expect lint:cyclomatic-complexity
62 */
63final readonly class MovedToMapEvent implements Event
64{
65    use NamedAfterClass;
66
67    public function __construct(
68        public AreaId $areaId,
69        public Map $map,
70    ) {}
71
72    /** @return Option\Option<static> */
73    #[Override]
74    public static function from(Message $message): Option\Option
75    {
76        if (!$message instanceof JsonMessage || ($message->data['cmd'] ?? null) !== 'moveToArea') {
77            return Option\none();
78        }
79
80        $data = self::arrival($message->data);
81
82        try {
83            $map = new Map(
84                new MapName($data['strMapName']),
85                self::room($data['areaName']),
86                new Gamefile($data['strMapFileName']),
87                new MapMonsters(self::monsters($data)),
88                new MapPlayers(self::players($data)),
89            );
90        } catch (InvalidArgumentException $exception) {
91            throw new MalformedEventException(
92                static::class,
93                'a monster or player is in the room more than once',
94                $exception,
95            );
96        }
97
98        return Option\some(new static(new AreaId($data['areaId']), $map));
99    }
100
101    #[Override]
102    public function summary(): string
103    {
104        return "{$this->map->name->value} (room {$this->map->room->value})";
105    }
106
107    /**
108     * @param array<array-key, mixed> $data
109     *
110     * @throws MalformedEventException
111     *
112     * @return Arrival
113     */
114    private static function arrival(array $data): array
115    {
116        $vitals = [
117            'intState' => Type\int_range(min: 0, max: 2),
118            'intHP' => Type\uint(),
119            'intHPMax' => Type\uint(),
120            'intMP' => Type\uint(),
121            'intMPMax' => Type\uint(),
122        ];
123
124        try {
125            return Type\shape([
126                'areaId' => Type\positive_int(),
127                'areaName' => Type\non_empty_string(),
128                'strMapName' => Type\non_empty_string(),
129                'strMapFileName' => Type\non_empty_string(),
130                'mondef' => Type\optional(Type\vec(Type\shape([
131                    'MonID' => Type\positive_int(),
132                    'strMonName' => Type\non_empty_string(),
133                    'intLevel' => Type\positive_int(),
134                    'sRace' => Type\string(),
135                    'strMonFileName' => Type\non_empty_string(),
136                    'strLinkage' => Type\non_empty_string(),
137                ], allowUnknownFields: true))),
138                'monmap' => Type\optional(Type\vec(Type\shape([
139                    'MonMapID' => Type\positive_int(),
140                    'MonID' => Type\positive_int(),
141                    'strFrame' => Type\non_empty_string(),
142                ], allowUnknownFields: true))),
143                'monBranch' => Type\optional(Type\vec(Type\shape([
144                    'MonMapID' => Type\positive_int(),
145                    ...$vitals,
146                ], allowUnknownFields: true))),
147                'uoBranch' => Type\optional(Type\vec(Type\shape([
148                    'entID' => Type\positive_int(),
149                    'strUsername' => Type\non_empty_string(),
150                    'intLevel' => Type\int_range(min: 1, max: 100),
151                    'strFrame' => Type\non_empty_string(),
152                    'strPad' => Type\non_empty_string(),
153                    ...$vitals,
154                ], allowUnknownFields: true))),
155            ], allowUnknownFields: true)->coerce($data);
156        } catch (CoercionException $exception) {
157            throw new MalformedEventException(static::class, 'map data is missing or invalid', $exception);
158        }
159    }
160
161    /**
162     * @param Arrival $data
163     *
164     * @throws MalformedEventException
165     *
166     * @return list<MapMonster>
167     */
168    private static function monsters(array $data): array
169    {
170        $kinds = [];
171        foreach ($data['mondef'] ?? [] as $kind) {
172            $kinds[$kind['MonID']] = new Monster(
173                new MonsterName($kind['strMonName']),
174                new MonsterLevel($kind['intLevel']),
175                self::race($kind['sRace']),
176                new MonsterAppearance(new Gamefile($kind['strMonFileName']), new Linkage($kind['strLinkage'])),
177            );
178        }
179
180        $seen = [];
181        foreach ($data['monBranch'] ?? [] as $spawn) {
182            $seen[$spawn['MonMapID']] = $spawn;
183        }
184
185        $monsters = [];
186        foreach ($data['monmap'] ?? [] as $placement) {
187            $kind = $kinds[$placement['MonID']] ?? null;
188            $spawn = $seen[$placement['MonMapID']] ?? null;
189            if ($kind === null || $spawn === null) {
190                continue;
191            }
192
193            $monsters[] = new MapMonster(
194                new MonsterSpawnId($placement['MonMapID']),
195                $kind,
196                new MapCell($placement['strFrame']),
197                self::vitals($spawn),
198                CombatStates::read($spawn['intState']),
199            );
200        }
201
202        return $monsters;
203    }
204
205    /**
206     * @param Arrival $data
207     *
208     * @throws MalformedEventException
209     *
210     * @return list<MapPlayer>
211     */
212    private static function players(array $data): array
213    {
214        return array_map(
215            static fn(array $player): MapPlayer => new MapPlayer(
216                new Player(
217                    new PlayerSpawnId($player['entID']),
218                    new PlayerName($player['strUsername']),
219                    new PlayerLevel($player['intLevel']),
220                    self::vitals($player),
221                ),
222                new MapSpot(new MapCell($player['strFrame']), MapPads::read($player['strPad'], static::class)),
223                CombatStates::read($player['intState']),
224            ),
225            $data['uoBranch'] ?? [],
226        );
227    }
228
229    /**
230     * @param array{intHP: non-negative-int, intHPMax: non-negative-int, intMP: non-negative-int, intMPMax: non-negative-int, ...} $someone
231     *
232     * @throws MalformedEventException
233     */
234    private static function vitals(array $someone): Vitals
235    {
236        try {
237            return new Vitals(
238                new Gauge(new Health($someone['intHP']), new Health($someone['intHPMax'])),
239                new Gauge(new Mana($someone['intMP']), new Mana($someone['intMPMax'])),
240            );
241        } catch (InvalidArgumentException $exception) {
242            throw new MalformedEventException(static::class, 'health or mana is above its maximum', $exception);
243        }
244    }
245
246    /** @throws MalformedEventException */
247    private static function room(string $areaName): MapRoom
248    {
249        $separator = strrpos($areaName, needle: '-');
250        $room = $separator === false ? '' : substr($areaName, $separator + 1);
251
252        if (!ctype_digit($room) || (int) $room < 1) {
253            throw new MalformedEventException(static::class, "area name '{$areaName}' has no room number");
254        }
255
256        return new MapRoom((int) $room);
257    }
258
259    /** @throws MalformedEventException */
260    private static function race(string $race): MonsterRace
261    {
262        return match ($race) {
263            'None' => MonsterRace::None,
264            'Undead' => MonsterRace::Undead,
265            'Human' => MonsterRace::Human,
266            'Elemental' => MonsterRace::Elemental,
267            'Dragonkin' => MonsterRace::Dragonkin,
268            'Chaos' => MonsterRace::Chaos,
269            'Unknown' => MonsterRace::Unknown,
270            default => throw new MalformedEventException(static::class, "unknown race '{$race}'"),
271        };
272    }
273}