BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

game.php 23.7 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 < 12; $i++) {
34 $kobold = Kobold::generate($userId, $tribe->getSaveId());
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(true) 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 // check kobold has the item
128 $has = false;
129 $itemName = $itemId;
130 $newItems = [];
131 foreach ($target->getItems() ?? [] as $it) {
132 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
133 if ($iid === $itemId && !$has) {
134 $has = true;
135 // capture name if present
136 if (is_array($it) && isset($it['name']))
137 $itemName = $it['name'];
138 elseif (is_object($it) && method_exists($it, 'getName'))
139 $itemName = $it->getName();
140 // consume (skip adding to newItems)
141 continue;
142 }
143 $newItems[] = $it;
144 }
145
146 if (!$has)
147 throw new \Exception('Kobold does not have the required item');
148
149 // remove injury
150 $target->removeInjury($injuryId);
151
152 // set kobold items to newItems (consumed)
153 $reflection = new ReflectionClass($target);
154 if ($reflection->hasProperty('items')) {
155 $prop = $reflection->getProperty('items');
156 $prop->setValue($target, $newItems);
157 }
158
159 // save tribe
160 $tribe->save();
161
162 $koboldName = $target->getName();
163 $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');
164
165 $story = "{$koboldName} used the {$itemName} to cure their {$injuryName}.";
166
167 echo json_encode(['success' => true, 'story' => $story]);
168 } catch (\Exception $e) {
169 http_response_code(400);
170 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
171 }
172 } elseif (strpos($apiPath, 'giveItem') !== false) {
173 // Move item from tribe storage to kobold inventory and save
174 try {
175 $userId = $input['userId'] ?? null;
176 $saveId = $input['saveId'] ?? null;
177 $koboldId = $input['koboldId'] ?? null;
178 $itemId = $input['itemId'] ?? null;
179
180 if (!$userId || !$saveId || !$koboldId || !$itemId) {
181 throw new \Exception('userId, saveId, koboldId and itemId are required');
182 }
183
184 $tribe = Tribe::load($userId, $saveId);
185
186 // find item in storage
187 $storage = $tribe->getStorage() ?? [];
188 $found = null;
189 $newStorage = [];
190 foreach ($storage as $s) {
191 $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
192 if ($sid === $itemId && $found === null) {
193 $found = $s;
194 continue;
195 }
196 $newStorage[] = $s;
197 }
198
199 if ($found === null)
200 throw new \Exception('Item not found in storage');
201
202 // find kobold
203 $target = null;
204 foreach ($tribe->getKobolds(true) as $k) {
205 if ($k->getId() === $koboldId) {
206 $target = $k;
207 break;
208 }
209 }
210 if (!$target)
211 throw new \Exception('Kobold not found');
212
213 // add item to kobold
214 if (method_exists($target, 'addItem')) {
215 $target->addItem($found);
216 } else {
217 // fallback: set via reflection
218 $ref = new ReflectionClass($target);
219 if ($ref->hasProperty('items')) {
220 $prop = $ref->getProperty('items');
221 $items = $prop->getValue($target) ?? [];
222 $items[] = $found;
223 $prop->setValue($target, $items);
224 }
225 }
226
227 // write back storage
228 $refT = new ReflectionClass($tribe);
229 if ($refT->hasProperty('storage')) {
230 $p = $refT->getProperty('storage');
231 $p->setValue($tribe, array_values($newStorage));
232 }
233
234 $tribe->save();
235
236 $koboldName = $target->getName();
237 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
238 $story = "{$itemName} was given to {$koboldName}.";
239
240 echo json_encode(['success' => true, 'story' => $story]);
241 } catch (\Exception $e) {
242 http_response_code(400);
243 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
244 }
245 } elseif (strpos($apiPath, 'returnItem') !== false) {
246 // Move item from kobold inventory back to tribe storage and save
247 try {
248 $userId = $input['userId'] ?? null;
249 $saveId = $input['saveId'] ?? null;
250 $koboldId = $input['koboldId'] ?? null;
251 $itemId = $input['itemId'] ?? null;
252
253 if (!$userId || !$saveId || !$koboldId || !$itemId) {
254 throw new \Exception('userId, saveId, koboldId and itemId are required');
255 }
256
257 $tribe = Tribe::load($userId, $saveId);
258
259 // find kobold
260 $target = null;
261 foreach ($tribe->getKobolds(true) as $k) {
262 if ($k->getId() === $koboldId) {
263 $target = $k;
264 break;
265 }
266 }
267 if (!$target)
268 throw new \Exception('Kobold not found');
269
270 // find item in kobold inventory
271 $found = null;
272 $newItems = [];
273 foreach ($target->getItems() ?? [] as $it) {
274 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
275 if ($iid === $itemId && $found === null) {
276 $found = $it;
277 continue;
278 }
279 $newItems[] = $it;
280 }
281 if ($found === null)
282 throw new \Exception('Item not found on kobold');
283
284 // set kobold items
285 if (method_exists($target, 'removeItem')) {
286 $target->removeItem($itemId);
287 } else {
288 $ref = new ReflectionClass($target);
289 if ($ref->hasProperty('items')) {
290 $p = $ref->getProperty('items');
291 $p->setValue($target, $newItems);
292 }
293 }
294
295 // add to tribe storage
296 $storage = $tribe->getStorage() ?? [];
297 $storage[] = $found;
298 $refT = new ReflectionClass($tribe);
299 if ($refT->hasProperty('storage')) {
300 $p = $refT->getProperty('storage');
301 $p->setValue($tribe, $storage);
302 }
303
304 $tribe->save();
305
306 $koboldName = $target->getName();
307 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
308 $story = "{$koboldName} returned the {$itemName} to storage.";
309
310 echo json_encode(['success' => true, 'story' => $story]);
311 } catch (\Exception $e) {
312 http_response_code(400);
313 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
314 }
315 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
316 // Save tribe setup
317 try {
318 $userId = $input['userId'] ?? null;
319 $saveId = $input['saveId'] ?? null;
320
321 if (!$userId || !$saveId) {
322 throw new \Exception('User ID and Save ID required');
323 }
324
325 $tribe = Tribe::load($userId, $saveId);
326
327 $leaderI = intval($input['leaderId']) ?? 0;
328
329 $keys = array_keys($tribe->kobolds);
330 $i = $keys[$leaderI];
331 $tribe->kobolds[$i]->setName($input['leaderName']);
332 $tribe->kobolds[$i]->setLeader();
333
334 for ($i = 0; $i < count($input['memberIndices']); $i++) {
335 $input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
336 }
337
338 $tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
339 return in_array($index, $input['memberIndices']);
340 }, ARRAY_FILTER_USE_BOTH);
341
342 $tribe->kobolds = array_values($tribe->kobolds);
343 $tribe->save();
344
345 echo json_encode([
346 'success' => true,
347 'tribe' => []
348 ]);
349 } catch (\Exception $e) {
350 http_response_code(400);
351 echo json_encode([
352 'success' => false,
353 'error' => $e->getMessage()
354 ]);
355 }
356 } elseif (strpos($apiPath, 'event') !== false) {
357 // Execute an event
358 try {
359 $userId = $input['userId'] ?? null;
360 $saveId = $input['saveId'] ?? null;
361
362 if (!$userId || !$saveId) {
363 throw new \Exception('User ID and Save ID required');
364 }
365
366 $tribe = Tribe::load($userId, $saveId);
367
368 // Execute event and get story. Allow passing participant kobold IDs.
369 $className = $input['eventType'] . "Event";
370 if (!class_exists($className))
371 throw new \Exception('Unknown event type');
372 $event = new $className($tribe);
373
374 if (method_exists($event, 'isAvailable') && !$event->isAvailable()) {
375 throw new \Exception('That event is not available right now.');
376 }
377
378 // Player-started events MUST provide participants (array of kobold IDs)
379 $participants = $input['participants'] ?? null;
380 if (empty($participants) || !is_array($participants)) {
381 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
382 }
383
384 // validate count against event limits
385 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
386 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
387 $count = count($participants);
388 if ($count < $min || $count > $max) {
389 throw new \Exception("Participants must be between {$min} and {$max}");
390 }
391
392 $cost = $event->getCost();
393 $participantKobolds = [];
394 $ineligible = [];
395 foreach ($participants as $pid) {
396 $kobold = $tribe->getKobold($pid);
397 if (!$kobold || $kobold->isDead()) {
398 throw new \Exception('One or more selected kobolds are unavailable.');
399 }
400
401 if (($kobold->getFatigue() + $cost) > $kobold->getStat('vitality')) {
402 $ineligible[] = $kobold->getName();
403 } else {
404 $participantKobolds[] = $kobold;
405 }
406 }
407
408 if (!empty($ineligible)) {
409 $names = implode(', ', $ineligible);
410 throw new \Exception("These kobolds are too fatigued for this event: {$names}");
411 }
412
413 $event->setParticipants($participants);
414
415 $event?->execute();
416 $story = $event?->getStory() ?? 'No event occurred.';
417
418 foreach ($participantKobolds as $kobold) {
419 $kobold->addFatigue($cost);
420 if ($kobold->isDead()) {
421 $story = $story . "\n" . $kobold->getName() . " has died.";
422 }
423 }
424
425 $tribe->save();
426
427 echo json_encode([
428 'success' => true,
429 'story' => $story
430 ]);
431 } catch (\Exception $e) {
432 http_response_code(400);
433 echo json_encode([
434 'success' => false,
435 'error' => $e->getMessage()
436 ]);
437 }
438 } elseif (strpos($apiPath, 'endMonth') !== false) {
439 // End the current month
440 try {
441 $userId = $input['userId'] ?? null;
442 $saveId = $input['saveId'] ?? null;
443
444 if (!$userId || !$saveId) {
445 throw new \Exception('User ID and Save ID required');
446 }
447
448 $tribe = Tribe::load($userId, $saveId);
449 $foodStory = $tribe->endMonth();
450
451 echo json_encode([
452 'success' => true,
453 'save' => [
454 'id' => $tribe->getSaveId(),
455 'current_month' => $tribe->getCurrentMonth(),
456 'current_season' => $tribe->getCurrentSeason(),
457 'food_count' => $tribe->getFoodCount()
458 ],
459 'monthStory' => $foodStory
460 ]);
461 } catch (\Exception $e) {
462 http_response_code(400);
463 echo json_encode([
464 'success' => false,
465 'error' => $e->getMessage()
466 ]);
467 }
468 }
469} elseif ($method === 'GET') {
470 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
471
472 if (strpos($apiPath, 'sprite') !== false) {
473 // Serve a kobold sprite image
474 try {
475 $userId = $_GET['userId'] ?? null;
476 $koboldId = $_GET['koboldId'] ?? null;
477
478 if (!$userId || !$koboldId) {
479 throw new \Exception('User ID and Kobold ID required');
480 }
481
482 $saveManager = new SaveManager();
483 $ageSprite = $_GET['age'] ?? 'adult';
484 $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
485 $spriteFile = $spritePath;
486
487 if (!file_exists($spriteFile)) {
488 throw new \Exception('Sprite not found');
489 }
490
491 // Serve the sprite image
492 header('Content-Type: image/png');
493 header('Cache-Control: public, max-age=3600');
494 readfile($spriteFile);
495 exit;
496 } catch (\Exception $e) {
497 http_response_code(404);
498 echo json_encode([
499 'success' => false,
500 'error' => $e->getMessage()
501 ]);
502 }
503 } elseif (strpos($apiPath, 'list') !== false) {
504 // List saves for user
505 try {
506 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
507
508 if (!$userId) {
509 throw new \Exception('Not authenticated');
510 }
511
512 $user = new User($userId, '');
513 $saves = $user->getSaves();
514
515 echo json_encode([
516 'success' => true,
517 'saves' => $saves
518 ]);
519 } catch (\Exception $e) {
520 http_response_code(400);
521 echo json_encode([
522 'success' => false,
523 'error' => $e->getMessage()
524 ]);
525 }
526 } elseif (strpos($apiPath, 'load') !== false) {
527 // Load a specific game save
528 try {
529 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
530 $saveId = $_GET['saveId'] ?? null;
531
532 if (!$userId || !$saveId) {
533 throw new \Exception('User ID and Save ID required');
534 }
535
536 $tribe = Tribe::load($userId, $saveId);
537
538 // Get kobolds with full stats, items and injuries
539 $kobolds = [];
540 foreach ($tribe->getKobolds() as $kobold) {
541 $kInjuries = $kobold->getInjuries() ?? [];
542 // enrich injuries with required medicine mapping
543 foreach ($kInjuries as &$inj) {
544 $req = null;
545 if (class_exists('Injury')) {
546 $req = Injury::getCureForCategory($inj['category'] ?? null);
547 }
548 $inj['required_medicine'] = $req;
549 }
550
551 $kobolds[] = [
552 'id' => $kobold->getId(),
553 'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
554 'age' => $kobold->getAge(),
555 'ageCategory' => $kobold->getAgeCategory(),
556 'stats' => [
557 'vitality' => $kobold->getStat('vitality'),
558 'intelligence' => $kobold->getStat('intelligence'),
559 'medicine' => $kobold->getStat('medicine'),
560 'crafting' => $kobold->getStat('crafting'),
561 'personality' => $kobold->getStat('personality'),
562 'will' => $kobold->getStat('will'),
563 'fighting' => $kobold->getStat('fighting')
564 ],
565 'fatigue' => $kobold->getFatigue(),
566 'fatigue_label' => $kobold->getFatigueLabel(),
567 'items' => $kobold->getItems() ?? [],
568 'injuries' => $kInjuries,
569 'male' => $kobold->getMale()
570 ];
571 }
572
573 // Get storage items
574 $storage = $tribe->getStorage();
575
576 echo json_encode([
577 'success' => true,
578 'save' => [
579 'id' => $tribe->getSaveId(),
580 'name' => $tribe->getName(),
581 'current_month' => $tribe->getCurrentMonth(),
582 'current_season' => $tribe->getCurrentSeason(),
583 'food_count' => $tribe->getFoodCount(),
584 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
585 'created_at' => $tribe->getCreatedAt(),
586 'last_played' => $tribe->getLastPlayed()
587 ],
588 'tribe' => [
589 'kobolds' => $kobolds,
590 'storage' => $storage
591 ]
592 ]);
593 } catch (\Exception $e) {
594 http_response_code(400);
595 echo json_encode([
596 'success' => false,
597 'error' => $e->getMessage()
598 ]);
599 }
600 } elseif (strpos($apiPath, 'events') !== false) {
601 // List available events and their costs
602 try {
603 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
604 $saveId = $_GET['saveId'] ?? null;
605
606 if (!$userId || !$saveId) {
607 throw new \Exception('User ID and Save ID required');
608 }
609
610 $tribe = Tribe::load($userId, $saveId);
611
612 $events = [];
613 foreach (get_declared_classes() as $className) {
614 if (!is_subclass_of($className, 'Event')) {
615 continue;
616 }
617
618 $event = new $className($tribe);
619 $type = preg_replace('/Event$/', '', $className);
620
621 $events[] = [
622 'type' => $type,
623 'name' => $type,
624 'cost' => $event->getCost(),
625 'available' => $event->isAvailable(),
626 'min_participants' => $event->getMinParticipants(),
627 'max_participants' => $event->getMaxParticipants()
628 ];
629 }
630
631 echo json_encode([
632 'success' => true,
633 'events' => $events
634 ]);
635 } catch (\Exception $e) {
636 http_response_code(400);
637 echo json_encode([
638 'success' => false,
639 'error' => $e->getMessage()
640 ]);
641 }
642 }
643}
644