BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

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