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