BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

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