BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

require a doctor for cures
timfa Tim Falken · pushed by timfa · 9 months ago
496a3606 History
game.php 28.3 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../vendor/autoload.php';
4require_once __DIR__ . '/../../src/Database/Database.php';
5require_once __DIR__ . '/../../src/Classes/User.php';
6require_once __DIR__ . '/../../src/Classes/Tribe.php';
7require_once __DIR__ . '/../../src/Classes/Kobold.php';
8require_once __DIR__ . '/../../src/Classes/Injury.php';
9require_once __DIR__ . '/../../src/System/SaveManager.php';
10
11foreach (glob(__DIR__ . "/../../src/Events/*Event.php") as $file) {
12 require_once $file;
13}
14
15$method = $_SERVER['REQUEST_METHOD'];
16
17if ($method === 'POST') {
18 $input = json_decode(file_get_contents('php://input'), true);
19
20 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
21
22 if (strpos($apiPath, 'generation') !== false) {
23 // Generate initial kobolds for new game
24 try {
25 $userId = $input['userId'] ?? null;
26 if (!$userId) {
27 throw new \Exception('User ID required');
28 }
29
30 $tribe = Tribe::create($userId, $input['saveName']);
31
32 $kobolds = [];
33 for ($i = 0; $i < 18; $i++) {
34 $kobold = Kobold::generate($userId, $tribe->getSaveId(), rand(15, 45));
35 $tribe->addKobold($kobold);
36
37 $kobolds[] = [
38 'id' => $kobold->getId(),
39 'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
40 'ageCategory' => $kobold->getAgeCategory(),
41 'age' => $kobold->getAge(),
42 'stats' => [
43 'vitality' => $kobold->getStat('vitality'),
44 'intelligence' => $kobold->getStat('intelligence'),
45 'medicine' => $kobold->getStat('medicine'),
46 'crafting' => $kobold->getStat('crafting'),
47 'personality' => $kobold->getStat('personality'),
48 'will' => $kobold->getStat('will'),
49 'fighting' => $kobold->getStat('fighting')
50 ],
51 'fatigue' => $kobold->getFatigue(),
52 'fatigue_label' => $kobold->getFatigueLabel()
53 ];
54 }
55
56 $tribe->save();
57
58 echo json_encode([
59 'success' => true,
60 'save' => [
61 'id' => $tribe->getSaveId(),
62 'name' => $input['saveName']
63 ],
64 'kobolds' => $kobolds
65 ]);
66 } catch (\Exception $e) {
67 http_response_code(400);
68 echo json_encode([
69 'success' => false,
70 'error' => $e->getMessage()
71 ]);
72 }
73 } elseif (strpos($apiPath, 'cureInjury') !== false) {
74 // Cure an injury using an item from a kobold's inventory
75 try {
76 $userId = $input['userId'] ?? null;
77 $saveId = $input['saveId'] ?? null;
78 $koboldId = $input['koboldId'] ?? null;
79 $injuryId = $input['injuryId'] ?? null;
80 $itemId = $input['itemId'] ?? null;
81
82 if (!$userId || !$saveId || !$koboldId || !$injuryId || !$itemId) {
83 throw new \Exception('userId, saveId, koboldId, injuryId and itemId are required');
84 }
85
86 $tribe = Tribe::load($userId, $saveId);
87
88 // find kobold
89 $target = null;
90 foreach ($tribe->getKobolds(false) as $k) {
91 if ($k->getId() === $koboldId) {
92 $target = $k;
93 break;
94 }
95 }
96
97 if (!$target)
98 throw new \Exception('Kobold not found');
99
100 // find injury in kobold
101 $injuries = $target->getInjuries() ?? [];
102 $injury = null;
103 foreach ($injuries as $inj) {
104 if ($inj['id'] === $injuryId) {
105 $injury = $inj;
106 break;
107 }
108 }
109
110 if (!$injury)
111 throw new \Exception('Injury not found');
112
113 // malnourished cannot be cured via item
114 if (($injury['category'] ?? '') === 'malnourished') {
115 throw new \Exception('Malnourishment is cured via feeding at month end');
116 }
117
118 // required medicine by category
119 $required = Injury::getCureForCategory($injury['category'] ?? null);
120 if (!$required)
121 throw new \Exception('This injury cannot be cured with items');
122
123 if ($required !== $itemId) {
124 throw new \Exception('Provided item does not match required medicine');
125 }
126
127 $requiredStat = Injury::getStatRequiredToCure($injury['severity'] ?? null);
128 $doctor = null;
129 if ($requiredStat !== null) {
130 $bestOther = null;
131 $bestOtherMed = -1;
132 foreach ($tribe->getKobolds(false) as $k) {
133 if ($k->getId() === $koboldId) {
134 continue;
135 }
136 $med = (int) ($k->getStat('medicine') ?? 0);
137 if ($med >= $requiredStat && $med > $bestOtherMed) {
138 $bestOther = $k;
139 $bestOtherMed = $med;
140 }
141 }
142
143 if ($bestOther) {
144 $doctor = $bestOther;
145 } else {
146 $selfMed = (int) ($target->getStat('medicine') ?? 0);
147 if ($selfMed >= $requiredStat) {
148 $doctor = $target;
149 }
150 }
151
152 if (!$doctor) {
153 throw new \Exception('No kobold has sufficient medicine skill to treat this injury');
154 }
155 }
156
157 // check kobold has the item
158 $has = false;
159 $itemName = $itemId;
160 $newItems = [];
161 foreach ($target->getItems() ?? [] as $it) {
162 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
163 if ($iid === $itemId && !$has) {
164 $has = true;
165 // capture name if present
166 if (is_array($it) && isset($it['name']))
167 $itemName = $it['name'];
168 elseif (is_object($it) && method_exists($it, 'getName'))
169 $itemName = $it->getName();
170 // consume (skip adding to newItems)
171 continue;
172 }
173 $newItems[] = $it;
174 }
175
176 if (!$has)
177 throw new \Exception('Kobold does not have the required item');
178
179 // remove injury
180 $target->removeInjury($injuryId);
181
182 // set kobold items to newItems (consumed)
183 $reflection = new ReflectionClass($target);
184 if ($reflection->hasProperty('items')) {
185 $prop = $reflection->getProperty('items');
186 $prop->setValue($target, $newItems);
187 }
188
189 // save tribe
190 $tribe->save();
191
192 $koboldName = $target->getName();
193 $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');
194
195 $doctorName = $doctor ? $doctor->getName() : $koboldName;
196 if ($doctor && $doctor->getId() !== $target->getId()) {
197 $story = "{$doctorName} treated {$koboldName}'s {$injuryName} using the {$itemName}.";
198 } else {
199 $story = "{$doctorName} used the {$itemName} to cure the {$injuryName}.";
200 }
201
202 echo json_encode(['success' => true, 'story' => $story]);
203 } catch (\Exception $e) {
204 http_response_code(400);
205 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
206 }
207 } elseif (strpos($apiPath, 'giveItem') !== false) {
208 // Move item from tribe storage to kobold inventory and save
209 try {
210 $userId = $input['userId'] ?? null;
211 $saveId = $input['saveId'] ?? null;
212 $koboldId = $input['koboldId'] ?? null;
213 $itemId = $input['itemId'] ?? null;
214
215 if (!$userId || !$saveId || !$koboldId || !$itemId) {
216 throw new \Exception('userId, saveId, koboldId and itemId are required');
217 }
218
219 $tribe = Tribe::load($userId, $saveId);
220
221 // find item in storage
222 $storage = $tribe->getStorage() ?? [];
223 $found = null;
224 $newStorage = [];
225 foreach ($storage as $s) {
226 $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
227 if ($sid === $itemId && $found === null) {
228 $found = $s;
229 continue;
230 }
231 $newStorage[] = $s;
232 }
233
234 if ($found === null)
235 throw new \Exception('Item not found in storage');
236
237 // find kobold
238 $target = null;
239 foreach ($tribe->getKobolds(false) as $k) {
240 if ($k->getId() === $koboldId) {
241 $target = $k;
242 break;
243 }
244 }
245 if (!$target)
246 throw new \Exception('Kobold not found');
247
248 // add item to kobold
249 if (method_exists($target, 'addItem')) {
250 $target->addItem($found);
251 } else {
252 // fallback: set via reflection
253 $ref = new ReflectionClass($target);
254 if ($ref->hasProperty('items')) {
255 $prop = $ref->getProperty('items');
256 $items = $prop->getValue($target) ?? [];
257 $items[] = $found;
258 $prop->setValue($target, $items);
259 }
260 }
261
262 // write back storage
263 $refT = new ReflectionClass($tribe);
264 if ($refT->hasProperty('storage')) {
265 $p = $refT->getProperty('storage');
266 $p->setValue($tribe, array_values($newStorage));
267 }
268
269 $tribe->save();
270
271 $koboldName = $target->getName();
272 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
273 $story = "{$itemName} was given to {$koboldName}.";
274
275 echo json_encode(['success' => true, 'story' => $story]);
276 } catch (\Exception $e) {
277 http_response_code(400);
278 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
279 }
280 } elseif (strpos($apiPath, 'returnItem') !== false) {
281 // Move item from kobold inventory back to tribe storage and save
282 try {
283 $userId = $input['userId'] ?? null;
284 $saveId = $input['saveId'] ?? null;
285 $koboldId = $input['koboldId'] ?? null;
286 $itemId = $input['itemId'] ?? null;
287
288 if (!$userId || !$saveId || !$koboldId || !$itemId) {
289 throw new \Exception('userId, saveId, koboldId and itemId are required');
290 }
291
292 $tribe = Tribe::load($userId, $saveId);
293
294 // find kobold
295 $target = null;
296 foreach ($tribe->getKobolds(false) as $k) {
297 if ($k->getId() === $koboldId) {
298 $target = $k;
299 break;
300 }
301 }
302 if (!$target)
303 throw new \Exception('Kobold not found');
304
305 // find item in kobold inventory
306 $found = null;
307 $newItems = [];
308 foreach ($target->getItems() ?? [] as $it) {
309 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
310 if ($iid === $itemId && $found === null) {
311 $found = $it;
312 continue;
313 }
314 $newItems[] = $it;
315 }
316 if ($found === null)
317 throw new \Exception('Item not found on kobold');
318
319 // set kobold items
320 if (method_exists($target, 'removeItem')) {
321 $target->removeItem($itemId);
322 } else {
323 $ref = new ReflectionClass($target);
324 if ($ref->hasProperty('items')) {
325 $p = $ref->getProperty('items');
326 $p->setValue($target, $newItems);
327 }
328 }
329
330 // add to tribe storage
331 $storage = $tribe->getStorage() ?? [];
332 $storage[] = $found;
333 $refT = new ReflectionClass($tribe);
334 if ($refT->hasProperty('storage')) {
335 $p = $refT->getProperty('storage');
336 $p->setValue($tribe, $storage);
337 }
338
339 $tribe->save();
340
341 $koboldName = $target->getName();
342 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
343 $story = "{$koboldName} returned the {$itemName} to storage.";
344
345 echo json_encode(['success' => true, 'story' => $story]);
346 } catch (\Exception $e) {
347 http_response_code(400);
348 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
349 }
350 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
351 // Save tribe setup
352 try {
353 $userId = $input['userId'] ?? null;
354 $saveId = $input['saveId'] ?? null;
355 $environmentId = $input['environmentId'] ?? null;
356
357 if (!$userId || !$saveId) {
358 throw new \Exception('User ID and Save ID required');
359 }
360
361 $tribe = Tribe::load($userId, $saveId);
362
363 if ($environmentId !== null) {
364 $tribe->setEnvironmentId($environmentId);
365 }
366
367 $leaderI = intval($input['leaderId']) ?? 0;
368
369 $keys = array_keys($tribe->kobolds);
370 $i = $keys[$leaderI];
371 $tribe->kobolds[$i]->setName($input['leaderName']);
372 $tribe->kobolds[$i]->setLeader();
373
374 for ($i = 0; $i < count($input['memberIndices']); $i++) {
375 $input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
376 }
377
378 $tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
379 return in_array($index, $input['memberIndices']);
380 }, ARRAY_FILTER_USE_BOTH);
381
382 $tribe->kobolds = array_values($tribe->kobolds);
383 $tribe->save();
384
385 echo json_encode([
386 'success' => true,
387 'tribe' => []
388 ]);
389 } catch (\Exception $e) {
390 http_response_code(400);
391 echo json_encode([
392 'success' => false,
393 'error' => $e->getMessage()
394 ]);
395 }
396 } elseif (strpos($apiPath, 'event') !== false) {
397 // Execute an event
398 try {
399 $userId = $input['userId'] ?? null;
400 $saveId = $input['saveId'] ?? null;
401
402 if (!$userId || !$saveId) {
403 throw new \Exception('User ID and Save ID required');
404 }
405
406 $tribe = Tribe::load($userId, $saveId);
407
408 // Execute event and get story. Allow passing participant kobold IDs.
409 $className = $input['eventType'] . "Event";
410 if (!class_exists($className))
411 throw new \Exception('Unknown event type');
412 $event = new $className($tribe);
413
414 if (method_exists($event, 'isAvailable') && !$event->isAvailable()) {
415 throw new \Exception('That event is not available right now.');
416 }
417
418 // Player-started events MUST provide participants (array of kobold IDs)
419 $participants = $input['participants'] ?? null;
420 if (empty($participants) || !is_array($participants)) {
421 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
422 }
423
424 // validate count against event limits
425 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
426 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
427 $count = count($participants);
428 if ($count < $min || $count > $max) {
429 throw new \Exception("Participants must be between {$min} and {$max}");
430 }
431
432 $cost = $event->getCost();
433 $participantKobolds = [];
434 $ineligible = [];
435 foreach ($participants as $pid) {
436 $kobold = $tribe->getKobold($pid);
437 if (!$kobold || $kobold->isDead()) {
438 throw new \Exception('One or more selected kobolds are unavailable.');
439 }
440
441 if (($kobold->getFatigue() + $cost) > $kobold->getStat('vitality')) {
442 $ineligible[] = $kobold->getName();
443 } else {
444 $participantKobolds[] = $kobold;
445 }
446 }
447
448 if (!empty($ineligible)) {
449 $names = implode(', ', $ineligible);
450 throw new \Exception("These kobolds are too fatigued for this event: {$names}");
451 }
452
453 $event->setParticipants($participants);
454
455 $event?->execute();
456 $story = $event?->getStory() ?? 'No event occurred.';
457
458 foreach ($participantKobolds as $kobold) {
459 $kobold->addFatigue($cost);
460 if ($kobold->isDead()) {
461 $story = $story . "\n" . $kobold->getName() . " has died.";
462 }
463 }
464
465 $tribe->save();
466
467 echo json_encode([
468 'success' => true,
469 'story' => $story
470 ]);
471 } catch (\Exception $e) {
472 http_response_code(400);
473 echo json_encode([
474 'success' => false,
475 'error' => $e->getMessage()
476 ]);
477 }
478 } elseif (strpos($apiPath, 'endMonth') !== false) {
479 // End the current month
480 try {
481 $userId = $input['userId'] ?? null;
482 $saveId = $input['saveId'] ?? null;
483
484 if (!$userId || !$saveId) {
485 throw new \Exception('User ID and Save ID required');
486 }
487
488 $tribe = Tribe::load($userId, $saveId);
489 $foodStory = $tribe->endMonth();
490
491 echo json_encode([
492 'success' => true,
493 'save' => [
494 'id' => $tribe->getSaveId(),
495 'current_month' => $tribe->getCurrentMonth(),
496 'current_season' => $tribe->getCurrentSeason(),
497 'food_count' => $tribe->getFoodCount()
498 ],
499 'monthStory' => $foodStory
500 ]);
501 } catch (\Exception $e) {
502 http_response_code(400);
503 echo json_encode([
504 'success' => false,
505 'error' => $e->getMessage()
506 ]);
507 }
508 }
509} elseif ($method === 'GET') {
510 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
511
512 if (strpos($apiPath, 'sprite') !== false) {
513 // Serve a kobold sprite image
514 try {
515 $userId = $_GET['userId'] ?? null;
516 $koboldId = $_GET['koboldId'] ?? null;
517
518 if (!$userId || !$koboldId) {
519 throw new \Exception('User ID and Kobold ID required');
520 }
521
522 $saveManager = new SaveManager();
523 $ageSprite = $_GET['age'] ?? 'adult';
524 $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
525 $spriteFile = $spritePath;
526
527 if (!file_exists($spriteFile)) {
528 throw new \Exception('Sprite not found');
529 }
530
531 // Serve the sprite image
532 header('Content-Type: image/png');
533 header('Cache-Control: public, max-age=3600');
534 readfile($spriteFile);
535 exit;
536 } catch (\Exception $e) {
537 http_response_code(404);
538 echo json_encode([
539 'success' => false,
540 'error' => $e->getMessage()
541 ]);
542 }
543 } elseif (strpos($apiPath, 'environments') !== false) {
544 // List available environments and metadata
545 try {
546 $basePath = __DIR__ . '/../../assets/environments';
547 if (!is_dir($basePath)) {
548 throw new \Exception('Environments directory not found');
549 }
550
551 $envs = [];
552 $dirs = array_filter(scandir($basePath), function ($dir) use ($basePath) {
553 return $dir[0] !== '.' && is_dir($basePath . '/' . $dir);
554 });
555
556 $seasons = ['spring', 'summer', 'autumn', 'winter'];
557
558 foreach ($dirs as $dir) {
559 $metaFile = $basePath . '/' . $dir . '/metadata.json';
560 $meta = [];
561 if (file_exists($metaFile)) {
562 $meta = json_decode(file_get_contents($metaFile), true) ?? [];
563 }
564
565 $images = [];
566 foreach ($seasons as $season) {
567 $imgPath = $basePath . '/' . $dir . '/' . $season . '.png';
568 if (file_exists($imgPath)) {
569 $images[] = 'assets/environments/' . $dir . '/' . $season . '.png';
570 }
571 }
572
573 if (empty($images)) {
574 foreach (glob($basePath . '/' . $dir . '/*.png') as $img) {
575 $images[] = 'assets/environments/' . $dir . '/' . basename($img);
576 }
577 }
578
579 $envs[] = [
580 'id' => $dir,
581 'name' => $meta['name'] ?? $dir,
582 'description' => $meta['description'] ?? '',
583 'koboldLocations' => $meta['koboldLocations'] ?? [],
584 'images' => $images
585 ];
586 }
587
588 echo json_encode([
589 'success' => true,
590 'environments' => $envs
591 ]);
592 } catch (\Exception $e) {
593 http_response_code(400);
594 echo json_encode([
595 'success' => false,
596 'error' => $e->getMessage()
597 ]);
598 }
599 } elseif (strpos($apiPath, 'list') !== false) {
600 // List saves for user
601 try {
602 $userId = $_SESSION['user_email'] ?? null;
603
604 if (!$userId) {
605 throw new \Exception('Not authenticated');
606 }
607
608 $user = new User($userId, '');
609 $saves = $user->getSaves();
610
611 echo json_encode([
612 'success' => true,
613 'saves' => $saves
614 ]);
615 } catch (\Exception $e) {
616 http_response_code(400);
617 echo json_encode([
618 'success' => false,
619 'error' => $e->getMessage()
620 ]);
621 }
622 } elseif (strpos($apiPath, 'load') !== false) {
623 // Load a specific game save
624 try {
625 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
626 $saveId = $_GET['saveId'] ?? null;
627
628 if (!$userId || !$saveId) {
629 throw new \Exception('User ID and Save ID required');
630 }
631
632 $tribe = Tribe::load($userId, $saveId);
633
634 // Get kobolds with full stats, items and injuries
635 $kobolds = getKobolds($tribe, true);
636 $rivals = getKobolds($tribe, false);
637
638 // Get storage items
639 $storage = $tribe->getStorage();
640
641 echo json_encode([
642 'success' => true,
643 'save' => [
644 'id' => $tribe->getSaveId(),
645 'name' => $tribe->getName(),
646 'current_month' => $tribe->getCurrentMonth(),
647 'current_season' => $tribe->getCurrentSeason(),
648 'environment_id' => $tribe->getEnvironmentId(),
649 'food_count' => $tribe->getFoodCount(),
650 'food_time_remaining' => $tribe->foodTimeStr($tribe->getFoodCount()),
651 'created_at' => $tribe->getCreatedAt(),
652 'last_played' => $tribe->getLastPlayed(),
653 'rivals' => $rivals
654 ],
655 'tribe' => [
656 'kobolds' => $kobolds,
657 'storage' => $storage
658 ]
659 ]);
660 } catch (\Exception $e) {
661 http_response_code(400);
662 echo json_encode([
663 'success' => false,
664 'error' => $e->getMessage()
665 ]);
666 }
667 } elseif (strpos($apiPath, 'events') !== false) {
668 // List available events and their costs
669 try {
670 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
671 $saveId = $_GET['saveId'] ?? null;
672
673 if (!$userId || !$saveId) {
674 throw new \Exception('User ID and Save ID required');
675 }
676
677 $tribe = Tribe::load($userId, $saveId);
678
679 $events = [];
680 foreach (get_declared_classes() as $className) {
681 if (!is_subclass_of($className, 'Event') || $className === 'MonthEndEvent') {
682 continue;
683 }
684
685 $event = new $className($tribe);
686
687 if ($event->isEndOfMonth())
688 continue;
689
690 $type = preg_replace('/Event$/', '', $className);
691
692 $events[] = [
693 'type' => $type,
694 'name' => $type,
695 'cost' => $event->getCost(),
696 'available' => $event->isAvailable(),
697 'min_participants' => $event->getMinParticipants(),
698 'max_participants' => $event->getMaxParticipants(),
699 'min_age' => $event->getMinAge(),
700 ];
701 }
702
703 echo json_encode([
704 'success' => true,
705 'events' => $events
706 ]);
707 } catch (\Exception $e) {
708 http_response_code(400);
709 echo json_encode([
710 'success' => false,
711 'error' => $e->getMessage()
712 ]);
713 }
714 }
715}
716
717function getKobolds($tribe, $tribeMembers): array
718{
719 $kobolds = [];
720 foreach ($tribe->getKobolds(!$tribeMembers) as $kobold) {
721 $kInjuries = $kobold->getInjuries() ?? [];
722 // enrich injuries with required medicine mapping
723 foreach ($kInjuries as &$inj) {
724 $req = null;
725 if (class_exists('Injury')) {
726 $req = Injury::getCureForCategory($inj['category'] ?? null);
727 }
728 if ($req !== null) {
729 $inj['required_medicine'] = $req;
730
731 $category = $inj['category'] ?? null;
732 if ($category !== 'malnourished' && $category !== 'old-age') {
733 $statReq = Injury::getStatRequiredToCure($inj['severity'] ?? null);
734 if ($statReq !== null) {
735 $inj['stat_required_to_cure'] = $statReq;
736 }
737 }
738 }
739 }
740
741 $kobolds[] = [
742 'id' => $kobold->getId(),
743 'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
744 'age' => $kobold->getAge(),
745 'ageCategory' => $kobold->getAgeCategory(),
746 'stats' => [
747 'vitality' => $kobold->getStat('vitality'),
748 'intelligence' => $kobold->getStat('intelligence'),
749 'medicine' => $kobold->getStat('medicine'),
750 'crafting' => $kobold->getStat('crafting'),
751 'personality' => $kobold->getStat('personality'),
752 'will' => $kobold->getStat('will'),
753 'fighting' => $kobold->getStat('fighting')
754 ],
755 'fatigue' => $kobold->getFatigue(),
756 'fatigue_label' => $kobold->getFatigueLabel(),
757 'items' => $kobold->getItems() ?? [],
758 'injuries' => $kInjuries,
759 'is_leader' => $kobold->isLeader(),
760 'male' => $kobold->getMale(),
761 'likes' => isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass
762 && isset($kobold->dataStore->likes) && is_array($kobold->dataStore->likes)
763 ? $kobold->dataStore->likes
764 : []
765 ];
766 }
767
768 return $kobolds;
769}