BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

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