| 1 | <?php |
| 2 | |
| 3 | require_once __DIR__ . '/../../src/System/SaveManager.php'; |
| 4 | require_once __DIR__ . '/../../src/Classes/Kobold.php'; |
| 5 | |
| 6 | class Tribe |
| 7 | { |
| 8 | private $userId; |
| 9 | private $saveId; |
| 10 | private $name; |
| 11 | public $kobolds = []; |
| 12 | public $rivals = []; |
| 13 | private $storage = []; |
| 14 | private $currentMonth = 0; |
| 15 | private $currentSeason = 'spring'; |
| 16 | private $foodCount = 0; |
| 17 | private $environmentId = null; |
| 18 | private $createdAt; |
| 19 | private $lastPlayed; |
| 20 | private $saveManager; |
| 21 | public $dataStore; |
| 22 | |
| 23 | // Food requirement by age tier (portion units) |
| 24 | public $foodRequirements = [ |
| 25 | 'egg' => 0, |
| 26 | 'baby' => 1, |
| 27 | 'young' => 2, |
| 28 | 'adult' => 3, |
| 29 | 'old' => 2 |
| 30 | ]; |
| 31 | |
| 32 | public function __construct($userId, $saveId, $name = '') |
| 33 | { |
| 34 | $this->userId = $userId; |
| 35 | $this->saveId = $saveId; |
| 36 | $this->name = $name; |
| 37 | $this->saveManager = new SaveManager(); |
| 38 | $this->loadFromFile(); |
| 39 | } |
| 40 | |
| 41 | public static function create($userId, $saveName) |
| 42 | { |
| 43 | $saveManager = new SaveManager(); |
| 44 | $saveId = $saveManager->generateSaveId($userId); |
| 45 | |
| 46 | $tribe = new self($userId, $saveId, $saveName); |
| 47 | $tribe->createdAt = date('Y-m-d H:i:s'); |
| 48 | $tribe->lastPlayed = date('Y-m-d H:i:s'); |
| 49 | $tribe->save(); |
| 50 | |
| 51 | return $tribe; |
| 52 | } |
| 53 | |
| 54 | public static function load($userId, $saveId) |
| 55 | { |
| 56 | return new self($userId, $saveId); |
| 57 | } |
| 58 | |
| 59 | private function loadFromFile() |
| 60 | { |
| 61 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 62 | $saveFile = $savePath . '/save.json'; |
| 63 | |
| 64 | if (file_exists($saveFile)) { |
| 65 | $data = $this->saveManager->loadJson($saveFile); |
| 66 | |
| 67 | if ($data) { |
| 68 | $this->name = $data['name'] ?? ''; |
| 69 | $this->currentMonth = $data['current_month'] ?? 0; |
| 70 | $this->currentSeason = $data['current_season'] ?? 'spring'; |
| 71 | $this->foodCount = $data['food_count'] ?? 0; |
| 72 | $this->environmentId = $data['environment_id'] ?? null; |
| 73 | $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s'); |
| 74 | $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s'); |
| 75 | $this->dataStore = $data['data_store'] ?? new stdClass(); |
| 76 | } |
| 77 | |
| 78 | if (is_array($this->dataStore)) { |
| 79 | $this->dataStore = (object) $this->dataStore; |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | $this->loadKobolds(); |
| 84 | $this->loadStorage(); |
| 85 | } |
| 86 | |
| 87 | private function loadKobolds() |
| 88 | { |
| 89 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 90 | $koboldsFile = $savePath . '/kobolds.json'; |
| 91 | |
| 92 | $this->kobolds = []; |
| 93 | |
| 94 | if (file_exists($koboldsFile)) { |
| 95 | $data = $this->saveManager->loadJson($koboldsFile); |
| 96 | |
| 97 | if ($data && is_array($data)) { |
| 98 | foreach ($data as $koboldData) { |
| 99 | $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId); |
| 100 | if ($kobold) { |
| 101 | if ($kobold->isRival) |
| 102 | $this->rivals[$kobold->getId()] = $kobold; |
| 103 | else |
| 104 | $this->kobolds[$kobold->getId()] = $kobold; |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | public function isBestInTribeForStat($kobold, $statName) |
| 112 | { |
| 113 | if (!$kobold instanceof Kobold) { |
| 114 | return false; |
| 115 | } |
| 116 | |
| 117 | if ($kobold->getAgeCategory() == "egg") |
| 118 | return false; |
| 119 | if ($kobold->getAgeCategory() == "baby") |
| 120 | return false; |
| 121 | if ($kobold->getAgeCategory() == "young") |
| 122 | return false; |
| 123 | |
| 124 | if ($kobold->getHighestStatName() !== $statName) { |
| 125 | return false; |
| 126 | } |
| 127 | |
| 128 | $targetStat = $kobold->getStat($statName); |
| 129 | if ($targetStat === null || $targetStat < 50) { |
| 130 | return false; |
| 131 | } |
| 132 | |
| 133 | $hasPeer = false; |
| 134 | foreach ($this->getKobolds() as $otherKobold) { |
| 135 | if ($otherKobold->getId() === $kobold->getId()) { |
| 136 | continue; |
| 137 | } |
| 138 | |
| 139 | if ($otherKobold->getHighestStatName() !== $statName) { |
| 140 | continue; |
| 141 | } |
| 142 | |
| 143 | if ($otherKobold->getAgeCategory() == "egg") |
| 144 | continue; |
| 145 | if ($otherKobold->getAgeCategory() == "baby") |
| 146 | continue; |
| 147 | if ($otherKobold->getAgeCategory() == "young") |
| 148 | continue; |
| 149 | |
| 150 | if ($otherKobold->isLeader()) |
| 151 | continue; |
| 152 | |
| 153 | $hasPeer = true; |
| 154 | |
| 155 | $otherStat = $otherKobold->getStat($statName); |
| 156 | if ($otherStat !== null && $otherStat > $targetStat) { |
| 157 | return false; |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | return $hasPeer; |
| 162 | } |
| 163 | |
| 164 | public function getKoboldTitle($kobold) |
| 165 | { |
| 166 | if (!$kobold instanceof Kobold) { |
| 167 | return false; |
| 168 | } |
| 169 | |
| 170 | $elder = $kobold->getAgeCategory() == "old" ? "Elder " : ""; |
| 171 | |
| 172 | if ($kobold->isLeader()) |
| 173 | return $elder . "Chieftain"; |
| 174 | |
| 175 | if ($kobold->getAgeCategory() == "egg") |
| 176 | return "Egg"; |
| 177 | if ($kobold->getAgeCategory() == "baby") |
| 178 | return "Baby"; |
| 179 | if ($kobold->getAgeCategory() == "young") |
| 180 | return "Youngling"; |
| 181 | |
| 182 | if ($this->isBestInTribeForStat($kobold, $kobold->getHighestStatName())) { |
| 183 | return $elder . "Chief " . $kobold->getTitle(false); |
| 184 | } |
| 185 | |
| 186 | return $elder . $kobold->getTitle(); |
| 187 | } |
| 188 | |
| 189 | public function getTitleForKobold($kobold) |
| 190 | { |
| 191 | return $this->getKoboldTitle($kobold); |
| 192 | } |
| 193 | |
| 194 | private function loadStorage() |
| 195 | { |
| 196 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 197 | $itemsFile = $savePath . '/items.json'; |
| 198 | |
| 199 | $this->storage = []; |
| 200 | |
| 201 | if (file_exists($itemsFile)) { |
| 202 | $this->storage = $this->saveManager->loadJson($itemsFile) ?? []; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | public function save() |
| 207 | { |
| 208 | $this->lastPlayed = date('Y-m-d H:i:s'); |
| 209 | |
| 210 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 211 | |
| 212 | // Save tribe metadata |
| 213 | $tribeData = [ |
| 214 | 'name' => $this->name, |
| 215 | 'current_month' => $this->currentMonth, |
| 216 | 'current_season' => $this->currentSeason, |
| 217 | 'food_count' => $this->foodCount, |
| 218 | 'food_time_left' => $this->foodTimeStr($this->foodCount), |
| 219 | 'environment_id' => $this->environmentId, |
| 220 | 'created_at' => $this->createdAt, |
| 221 | 'last_played' => $this->lastPlayed, |
| 222 | 'data_store' => $this->dataStore ?? new stdClass() |
| 223 | ]; |
| 224 | |
| 225 | $this->saveManager->saveJson($savePath . '/save.json', $tribeData); |
| 226 | |
| 227 | // Save kobolds |
| 228 | $koboldsData = []; |
| 229 | foreach ($this->kobolds as $kobold) { |
| 230 | if (!$kobold->isDead()) { |
| 231 | $kobold->save(); |
| 232 | $koboldsData[] = $kobold->toArray(); |
| 233 | } |
| 234 | } |
| 235 | foreach ($this->rivals as $kobold) { |
| 236 | if (!$kobold->isDead()) { |
| 237 | $kobold->save(); |
| 238 | $koboldsData[] = $kobold->toArray(); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData); |
| 243 | |
| 244 | // Save items |
| 245 | $this->saveManager->saveJson($savePath . '/items.json', $this->storage); |
| 246 | |
| 247 | GameHelper::cleanupUnusedKoboldSprites($this->userId); |
| 248 | } |
| 249 | |
| 250 | // Getters and Setters |
| 251 | public function getName() |
| 252 | { |
| 253 | return $this->name; |
| 254 | } |
| 255 | |
| 256 | public function setName($name) |
| 257 | { |
| 258 | $this->name = $name; |
| 259 | } |
| 260 | |
| 261 | public function getSaveId() |
| 262 | { |
| 263 | return $this->saveId; |
| 264 | } |
| 265 | |
| 266 | public function getUserId() |
| 267 | { |
| 268 | return $this->userId; |
| 269 | } |
| 270 | |
| 271 | public function getCreatedAt() |
| 272 | { |
| 273 | return $this->createdAt; |
| 274 | } |
| 275 | |
| 276 | public function getLastPlayed() |
| 277 | { |
| 278 | return $this->lastPlayed; |
| 279 | } |
| 280 | |
| 281 | public function getCurrentMonth() |
| 282 | { |
| 283 | return $this->currentMonth; |
| 284 | } |
| 285 | |
| 286 | public function setCurrentMonth($month) |
| 287 | { |
| 288 | $this->currentMonth = max(0, $month); |
| 289 | } |
| 290 | |
| 291 | public function getCurrentSeason() |
| 292 | { |
| 293 | return $this->currentSeason; |
| 294 | } |
| 295 | |
| 296 | public function setCurrentSeason($season) |
| 297 | { |
| 298 | $this->currentSeason = $season; |
| 299 | } |
| 300 | |
| 301 | public function getEnvironmentId() |
| 302 | { |
| 303 | return $this->environmentId; |
| 304 | } |
| 305 | |
| 306 | public function setEnvironmentId($environmentId) |
| 307 | { |
| 308 | $this->environmentId = $environmentId; |
| 309 | } |
| 310 | |
| 311 | // Kobold management |
| 312 | public function getKobolds($rivals = false) |
| 313 | { |
| 314 | if ($rivals) { |
| 315 | return array_filter($this->rivals, function (Kobold $k) { |
| 316 | return !$k->isDead() && !$k->isExpelled(); |
| 317 | }); |
| 318 | } |
| 319 | |
| 320 | return array_filter($this->kobolds, function (Kobold $k) { |
| 321 | return !$k->isDead() && !$k->isExpelled(); |
| 322 | }); |
| 323 | } |
| 324 | |
| 325 | public function getKobold($id) |
| 326 | { |
| 327 | return $this->kobolds[$id] ?? $this->rivals[$id] ?? null; |
| 328 | } |
| 329 | |
| 330 | public function addKobold(Kobold $kobold, $rival = false) |
| 331 | { |
| 332 | if ($rival) { |
| 333 | $this->rivals[$kobold->getId()] = $kobold; |
| 334 | return $kobold; |
| 335 | } |
| 336 | |
| 337 | $this->kobolds[$kobold->getId()] = $kobold; |
| 338 | return $kobold; |
| 339 | } |
| 340 | |
| 341 | public function removeKobold($id) |
| 342 | { |
| 343 | if (isset($this->kobolds[$id])) |
| 344 | unset($this->kobolds[$id]); |
| 345 | |
| 346 | if (isset($this->rivals[$id])) |
| 347 | unset($this->rivals[$id]); |
| 348 | } |
| 349 | |
| 350 | public function getAliveKobolds($rivals = false) |
| 351 | { |
| 352 | if ($rivals) { |
| 353 | return array_filter($this->rivals, fn($k) => !$k->isDead()); |
| 354 | } |
| 355 | |
| 356 | return array_filter($this->kobolds, fn($k) => !$k->isDead()); |
| 357 | } |
| 358 | |
| 359 | // Storage management |
| 360 | public function addToStorage(Item $item, int $count = 1): array |
| 361 | { |
| 362 | // Accept either Item object or array |
| 363 | if (is_object($item) && method_exists($item, 'toArray')) { |
| 364 | $this->storage[] = $item->toArray(); |
| 365 | } elseif (is_array($item)) { |
| 366 | // Ensure it has an id |
| 367 | if (!isset($item['id'])) { |
| 368 | $item['id'] = uniqid('itm_'); |
| 369 | } |
| 370 | for ($i = 0; $i < $count; $i++) |
| 371 | $this->storage[] = $item; |
| 372 | } |
| 373 | return $this->storage; |
| 374 | } |
| 375 | |
| 376 | public function getStorage() |
| 377 | { |
| 378 | return $this->storage; |
| 379 | } |
| 380 | |
| 381 | // Food system methods |
| 382 | public function getFoodCount() |
| 383 | { |
| 384 | return $this->foodCount; |
| 385 | } |
| 386 | |
| 387 | public function addFood($amount) |
| 388 | { |
| 389 | $this->foodCount += $amount; |
| 390 | return $this->foodCount; |
| 391 | } |
| 392 | |
| 393 | public function removeFood($amount) |
| 394 | { |
| 395 | $this->foodCount = max(0, $this->foodCount - $amount); |
| 396 | return $this->foodCount; |
| 397 | } |
| 398 | |
| 399 | public function modifyFoodGain(&$amount) |
| 400 | { |
| 401 | $reason = null; |
| 402 | |
| 403 | if ($amount <= 0) { |
| 404 | return $reason; |
| 405 | } |
| 406 | |
| 407 | if (!empty($this->dataStore->draught) && $this->dataStore->draught > 0) { |
| 408 | $amount = (int) floor($amount / 2); |
| 409 | $reason = 'draught'; |
| 410 | } |
| 411 | |
| 412 | return $reason; |
| 413 | } |
| 414 | |
| 415 | /** |
| 416 | * Calculate total food needed for all alive kobolds for one month |
| 417 | */ |
| 418 | public function calculateFoodNeeded() |
| 419 | { |
| 420 | $needed = 0; |
| 421 | |
| 422 | foreach ($this->getAliveKobolds() as $kobold) { |
| 423 | $ageCategory = $kobold->getAgeCategory(); |
| 424 | $requirement = $this->foodRequirements[$ageCategory] ?? 1.0; |
| 425 | $needed += $requirement; |
| 426 | } |
| 427 | |
| 428 | return $needed; |
| 429 | } |
| 430 | |
| 431 | /** |
| 432 | * Calculate how many full months the current kobolds can be fed |
| 433 | * with the provided amount of food. |
| 434 | */ |
| 435 | public function foodMonthsLeft($amount) |
| 436 | { |
| 437 | $foodPerMonth = $this->calculateFoodNeeded(); |
| 438 | if ($foodPerMonth <= 0) { |
| 439 | return 0; |
| 440 | } |
| 441 | |
| 442 | $available = max(0, (float) $amount); |
| 443 | return (int) floor($available / $foodPerMonth); |
| 444 | } |
| 445 | |
| 446 | public function foodTimeStr($amount) |
| 447 | { |
| 448 | $months = $this->foodMonthsLeft($amount); |
| 449 | if ($months > 0) { |
| 450 | if ($months == 1) |
| 451 | return "1 month"; |
| 452 | else |
| 453 | return "{$months} months"; |
| 454 | } |
| 455 | |
| 456 | $foodPerMonth = $this->calculateFoodNeeded(); |
| 457 | if ($foodPerMonth <= 0) { |
| 458 | return "years"; |
| 459 | } |
| 460 | |
| 461 | $available = max(0, (float) $amount); |
| 462 | $days = (int) floor(($available / $foodPerMonth) * 30); |
| 463 | $weeks = intdiv($days, 7); |
| 464 | |
| 465 | if ($weeks >= 1) { |
| 466 | return $weeks . " week" . ($weeks === 1 ? "" : "s"); |
| 467 | } |
| 468 | |
| 469 | return $days . " day" . ($days === 1 ? "" : "s"); |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * Get food requirement for a specific kobold |
| 474 | */ |
| 475 | public function getFoodRequirement(Kobold $kobold) |
| 476 | { |
| 477 | $ageCategory = $kobold->getAgeCategory(); |
| 478 | return $this->foodRequirements[$ageCategory] ?? 1.0; |
| 479 | } |
| 480 | |
| 481 | /** |
| 482 | * Consume food at end of month after events |
| 483 | * Prioritizes: malnourished kobolds first, then younger before older |
| 484 | * Returns story of food consumption and any starvations |
| 485 | */ |
| 486 | public function consumeFood() |
| 487 | { |
| 488 | $story = ""; |
| 489 | $aliveKobolds = $this->getAliveKobolds(); |
| 490 | |
| 491 | if (empty($aliveKobolds)) { |
| 492 | return $story; |
| 493 | } |
| 494 | |
| 495 | // Sort kobolds: malnourished first, then by age (younger first) |
| 496 | usort($aliveKobolds, function ($a, $b) { |
| 497 | // Check for malnourished injury |
| 498 | $aMalnourished = $this->hasInjuryCategory($a, 'malnourished'); |
| 499 | $bMalnourished = $this->hasInjuryCategory($b, 'malnourished'); |
| 500 | |
| 501 | if ($aMalnourished && !$bMalnourished) |
| 502 | return -1; |
| 503 | if (!$aMalnourished && $bMalnourished) |
| 504 | return 1; |
| 505 | |
| 506 | // Both have or both don't have malnourished |
| 507 | // Younger first (lower age = higher priority) |
| 508 | return $a->getAge() - $b->getAge(); |
| 509 | }); |
| 510 | |
| 511 | $fedKobolds = []; |
| 512 | $starvedKobolds = []; |
| 513 | |
| 514 | foreach ($aliveKobolds as $kobold) { |
| 515 | $needed = $this->getFoodRequirement($kobold); |
| 516 | |
| 517 | if ($this->foodCount >= $needed) { |
| 518 | // Fed this kobold |
| 519 | $this->foodCount -= $needed; |
| 520 | $fedKobolds[$kobold->getId()] = $kobold; |
| 521 | |
| 522 | // If malnourished, cure it |
| 523 | if ($this->hasInjuryCategory($kobold, 'malnourished')) { |
| 524 | $this->removeMalnourishedInjury($kobold); |
| 525 | $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n"; |
| 526 | } |
| 527 | } else { |
| 528 | // Not enough food - starve this kobold |
| 529 | $starvedKobolds[$kobold->getId()] = $kobold; |
| 530 | $this->foodCount = 0; // Use remaining food |
| 531 | |
| 532 | |
| 533 | $malnourishedId = $this->getMalnourishedInjuryId($kobold); |
| 534 | if (!$malnourishedId) { |
| 535 | $kobold->addInjury('malnourished-slight'); |
| 536 | $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n"; |
| 537 | } else { |
| 538 | if ($malnourishedId === 'malnourished-slight') { |
| 539 | $kobold->removeInjury($malnourishedId); |
| 540 | $kobold->addInjury('malnourished-mild'); |
| 541 | $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n"; |
| 542 | } elseif ($malnourishedId === 'malnourished-mild') { |
| 543 | $kobold->removeInjury($malnourishedId); |
| 544 | $kobold->addInjury('malnourished-severe'); |
| 545 | $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n"; |
| 546 | } elseif ($malnourishedId === 'malnourished-severe') { |
| 547 | $kobold->removeInjury($malnourishedId); |
| 548 | $kobold->addInjury('malnourished-brink'); |
| 549 | $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n"; |
| 550 | } elseif ($malnourishedId === 'malnourished-brink') { |
| 551 | $this->cleanupDeadKoboldLikes($kobold->getId()); |
| 552 | $kobold->die(); |
| 553 | $story .= "{$kobold->getName()} succumbed to starvation.\n"; |
| 554 | } |
| 555 | } |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // Save updated kobolds |
| 560 | foreach ($aliveKobolds as $kobold) { |
| 561 | $kobold->save(); |
| 562 | } |
| 563 | |
| 564 | return $story; |
| 565 | } |
| 566 | |
| 567 | /** |
| 568 | * Check if a kobold has an injury in a specific category |
| 569 | */ |
| 570 | private function hasInjuryCategory(Kobold $kobold, $category) |
| 571 | { |
| 572 | $injuries = $kobold->getInjuries(); |
| 573 | foreach ($injuries as $injury) { |
| 574 | if ($injury['category'] === $category) { |
| 575 | return true; |
| 576 | } |
| 577 | } |
| 578 | return false; |
| 579 | } |
| 580 | |
| 581 | /** |
| 582 | * Remove all malnourished injuries from a kobold |
| 583 | */ |
| 584 | private function removeMalnourishedInjury(Kobold $kobold) |
| 585 | { |
| 586 | $injuries = $kobold->getInjuries(); |
| 587 | foreach ($injuries as $injury) { |
| 588 | if ($injury['category'] === 'malnourished') { |
| 589 | $kobold->removeInjury($injury['id']); |
| 590 | } |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | /** |
| 595 | * Get current malnourished injury id if present |
| 596 | */ |
| 597 | private function getMalnourishedInjuryId(Kobold $kobold) |
| 598 | { |
| 599 | $injuries = $kobold->getInjuries(); |
| 600 | foreach ($injuries as $injury) { |
| 601 | if (($injury['category'] ?? null) === 'malnourished') { |
| 602 | return $injury['id'] ?? null; |
| 603 | } |
| 604 | } |
| 605 | return null; |
| 606 | } |
| 607 | |
| 608 | public function tryMate() |
| 609 | { |
| 610 | $kobolds = array_values($this->getKobolds()); |
| 611 | $count = count($kobolds); |
| 612 | |
| 613 | if ($count === 0) { |
| 614 | return ''; |
| 615 | } |
| 616 | |
| 617 | $roll = rand(1, 30); |
| 618 | if ($roll <= $count) { |
| 619 | return ''; |
| 620 | } |
| 621 | |
| 622 | $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult')); |
| 623 | $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult')); |
| 624 | |
| 625 | if (empty($males) || empty($females)) { |
| 626 | return ''; |
| 627 | } |
| 628 | |
| 629 | $pair = null; |
| 630 | $attempts = 20; |
| 631 | while ($attempts-- > 0) { |
| 632 | $male = $males[array_rand($males)]; |
| 633 | $female = $females[array_rand($females)]; |
| 634 | |
| 635 | $maleParents = $male->getParents(); |
| 636 | $femaleParents = $female->getParents(); |
| 637 | |
| 638 | $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null); |
| 639 | $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null); |
| 640 | $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null); |
| 641 | $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null); |
| 642 | |
| 643 | if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) { |
| 644 | continue; |
| 645 | } |
| 646 | |
| 647 | $pair = [$male, $female]; |
| 648 | break; |
| 649 | } |
| 650 | |
| 651 | if (!$pair) { |
| 652 | return ''; |
| 653 | } |
| 654 | |
| 655 | [$male, $female] = $pair; |
| 656 | |
| 657 | if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) { |
| 658 | return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off."; |
| 659 | } |
| 660 | |
| 661 | $child = Kobold::generate($this->userId, $this->saveId, -6); |
| 662 | |
| 663 | if (!isset($child->dataStore)) { |
| 664 | $child->dataStore = new stdClass(); |
| 665 | } |
| 666 | if (!isset($child->dataStore->likes)) { |
| 667 | $child->dataStore->likes = []; |
| 668 | } |
| 669 | |
| 670 | // Child likes parents by default |
| 671 | $child->dataStore->likes[$male->getId()] = 10; |
| 672 | $child->dataStore->likes[$female->getId()] = 10; |
| 673 | |
| 674 | // Initialize parents' dataStore if needed |
| 675 | if (!isset($male->dataStore)) { |
| 676 | $male->dataStore = new stdClass(); |
| 677 | } |
| 678 | if (!isset($male->dataStore->likes)) { |
| 679 | $male->dataStore->likes = []; |
| 680 | } |
| 681 | |
| 682 | if (!isset($female->dataStore)) { |
| 683 | $female->dataStore = new stdClass(); |
| 684 | } |
| 685 | if (!isset($female->dataStore->likes)) { |
| 686 | $female->dataStore->likes = []; |
| 687 | } |
| 688 | |
| 689 | // Parents like the child by default |
| 690 | $male->dataStore->likes[$child->getId()] = 20; |
| 691 | $female->dataStore->likes[$child->getId()] = 20; |
| 692 | |
| 693 | $inheritRoll = rand(1, 100); |
| 694 | if ($inheritRoll <= 40) { |
| 695 | $child->setSpriteMorph($male->getSpriteMorph()); |
| 696 | } elseif ($inheritRoll <= 80) { |
| 697 | $child->setSpriteMorph($female->getSpriteMorph()); |
| 698 | } |
| 699 | |
| 700 | $blendHex = function ($a, $b) { |
| 701 | $hexToRgb = function ($hex) { |
| 702 | $hex = ltrim($hex, '#'); |
| 703 | return [ |
| 704 | 'r' => hexdec(substr($hex, 0, 2)), |
| 705 | 'g' => hexdec(substr($hex, 2, 2)), |
| 706 | 'b' => hexdec(substr($hex, 4, 2)) |
| 707 | ]; |
| 708 | }; |
| 709 | |
| 710 | $rgbToHex = function ($rgb) { |
| 711 | return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']); |
| 712 | }; |
| 713 | |
| 714 | $ra = $hexToRgb($a); |
| 715 | $rb = $hexToRgb($b); |
| 716 | $ratio = rand(0, 100) / 100; |
| 717 | |
| 718 | $offset = function () { |
| 719 | return rand(-20, 20); |
| 720 | }; |
| 721 | |
| 722 | $mix = function ($c1, $c2) use ($ratio, $offset) { |
| 723 | $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset()); |
| 724 | return max(0, min(255, $val)); |
| 725 | }; |
| 726 | |
| 727 | $mixed = [ |
| 728 | 'r' => $mix($ra['r'], $rb['r']), |
| 729 | 'g' => $mix($ra['g'], $rb['g']), |
| 730 | 'b' => $mix($ra['b'], $rb['b']) |
| 731 | ]; |
| 732 | |
| 733 | return $rgbToHex($mixed); |
| 734 | }; |
| 735 | |
| 736 | $maleColours = $male->getColours(); |
| 737 | $femaleColours = $female->getColours(); |
| 738 | |
| 739 | $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']); |
| 740 | $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']); |
| 741 | $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']); |
| 742 | |
| 743 | $child->setColours($childPrimary, $childSecondary, $childTertiary); |
| 744 | $child->setParents($male->getId(), $female->getId()); |
| 745 | $child->regenerateSprite(); |
| 746 | |
| 747 | $this->addKobold($child); |
| 748 | |
| 749 | $pairName = $female->getName() . " and " . $male->getName(); |
| 750 | $momName = $female->getName(); |
| 751 | $variations = [ |
| 752 | "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!", |
| 753 | "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.", |
| 754 | "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.", |
| 755 | "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.", |
| 756 | "After many shared moments, {$pairName} welcomed a new egg from {$momName}.", |
| 757 | "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.", |
| 758 | "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.", |
| 759 | "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.", |
| 760 | "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.", |
| 761 | "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg." |
| 762 | ]; |
| 763 | |
| 764 | return $variations[array_rand($variations)]; |
| 765 | } |
| 766 | |
| 767 | public function getEndOfMonthEvents(): array |
| 768 | { |
| 769 | $maxCost = 250; |
| 770 | $selectedEvents = []; |
| 771 | $totalCost = 0; |
| 772 | |
| 773 | // Scan src/Events directory for event classes |
| 774 | $eventsDir = __DIR__ . '/../../src/Events/'; |
| 775 | $eventFiles = glob($eventsDir . '*.php'); |
| 776 | $availableEventClasses = []; |
| 777 | |
| 778 | foreach ($eventFiles as $file) { |
| 779 | $className = basename($file, '.php'); |
| 780 | |
| 781 | // Skip base classes |
| 782 | if ($className === 'Event' || $className === 'MonthEndEvent') { |
| 783 | continue; |
| 784 | } |
| 785 | |
| 786 | require_once $file; |
| 787 | |
| 788 | // Check if class exists and extends MonthEndEvent |
| 789 | if (!class_exists($className)) { |
| 790 | continue; |
| 791 | } |
| 792 | |
| 793 | // Create temporary instance to check conditions |
| 794 | $tempEvent = new $className($this); |
| 795 | |
| 796 | // Check if it's an end-of-month event |
| 797 | if (!$tempEvent->isEndOfMonth()) { |
| 798 | continue; |
| 799 | } |
| 800 | |
| 801 | // Check if event is available |
| 802 | if (!$tempEvent->isAvailable()) { |
| 803 | continue; |
| 804 | } |
| 805 | |
| 806 | // Check if tribe has enough eligible kobolds |
| 807 | $minAge = $tempEvent->getMinAge(); |
| 808 | $minParticipants = $tempEvent->getMinParticipants(); |
| 809 | |
| 810 | $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) { |
| 811 | return $kobold->getAge() >= $minAge; |
| 812 | }); |
| 813 | |
| 814 | if (count($eligibleKobolds) < $minParticipants) { |
| 815 | continue; |
| 816 | } |
| 817 | |
| 818 | // This event is available |
| 819 | $availableEventClasses[] = $className; |
| 820 | } |
| 821 | |
| 822 | // If no events available, return empty array |
| 823 | if (empty($availableEventClasses)) { |
| 824 | return []; |
| 825 | } |
| 826 | |
| 827 | // Select events randomly until cost exceeds maxCost |
| 828 | while ($totalCost <= $maxCost && !empty($availableEventClasses)) { |
| 829 | // Pick a weighted random event class (lower cost = higher weight) |
| 830 | $weights = []; |
| 831 | $weightTotal = 0; |
| 832 | foreach ($availableEventClasses as $className) { |
| 833 | $tempEvent = new $className($this); |
| 834 | $eventCost = max(1, (int) $tempEvent->getCost()); |
| 835 | $weight = 1 / $eventCost; |
| 836 | $weights[] = $weight; |
| 837 | $weightTotal += $weight; |
| 838 | } |
| 839 | |
| 840 | $roll = (mt_rand() / mt_getrandmax()) * $weightTotal; |
| 841 | $running = 0; |
| 842 | $randomClass = $availableEventClasses[0]; |
| 843 | foreach ($availableEventClasses as $index => $className) { |
| 844 | $running += $weights[$index]; |
| 845 | if ($roll <= $running) { |
| 846 | $randomClass = $className; |
| 847 | break; |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | // Create new instance |
| 852 | $event = new $randomClass($this); |
| 853 | $eventCost = $event->getCost(); |
| 854 | |
| 855 | // Add to selection |
| 856 | $selectedEvents[] = $event; |
| 857 | $totalCost += $eventCost; |
| 858 | } |
| 859 | |
| 860 | return $selectedEvents; |
| 861 | } |
| 862 | |
| 863 | public function endMonth() |
| 864 | { |
| 865 | $this->currentMonth++; |
| 866 | |
| 867 | if (!isset($this->dataStore)) { |
| 868 | $this->dataStore = new stdClass(); |
| 869 | } |
| 870 | $this->dataStore->heatWaveActive = max(0, (int) ($this->dataStore->heatWaveActive ?? 0) - 1); |
| 871 | $this->dataStore->draught = max(0, (int) ($this->dataStore->draught ?? 0) - 1); |
| 872 | $this->dataStore->floodedThisMonth = false; |
| 873 | |
| 874 | $reportedDeaths = []; |
| 875 | $aliveAtStart = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); |
| 876 | |
| 877 | $ongoingWeatherStory = ''; |
| 878 | if ($this->dataStore->draught > 0) { |
| 879 | $droughtLines = [ |
| 880 | "The drought continues, and the land remains cracked and dry.\n", |
| 881 | "No rain comes yet; the drought persists across the camp.\n", |
| 882 | "The drought has not broken, and the tribe endures another dry month.\n" |
| 883 | ]; |
| 884 | $ongoingWeatherStory .= $droughtLines[array_rand($droughtLines)]; |
| 885 | } |
| 886 | if ($this->dataStore->heatWaveActive > 0) { |
| 887 | $heatLines = [ |
| 888 | "The heat wave continues, and the camp moves slowly under the oppressive sun.\n", |
| 889 | "The heat wave has not faded; the tribe bears another sweltering month.\n", |
| 890 | "Relief does not come, and the heat wave presses on.\n" |
| 891 | ]; |
| 892 | $ongoingWeatherStory .= $heatLines[array_rand($heatLines)]; |
| 893 | } |
| 894 | |
| 895 | if ($this->dataStore->draught <= 0) { |
| 896 | foreach ($this->getKobolds() as $kobold) { |
| 897 | $injuries = $kobold->getInjuries(); |
| 898 | foreach ($injuries as $injury) { |
| 899 | if (($injury['id'] ?? null) === 'dehydrated') { |
| 900 | $kobold->removeInjury('dehydrated'); |
| 901 | } |
| 902 | } |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | foreach ($this->getKobolds() as $kobold) { |
| 907 | $injuries = $kobold->getInjuries(); |
| 908 | $hasHeatstroke = false; |
| 909 | foreach ($injuries as $injury) { |
| 910 | if (($injury['id'] ?? null) === 'heatstroke') { |
| 911 | $hasHeatstroke = true; |
| 912 | break; |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | if ($hasHeatstroke) { |
| 917 | $vitality = (int) ($kobold->getStat('vitality') ?? 0); |
| 918 | $baselineFatigue = (int) ceil($vitality * 0.75); |
| 919 | if ($this->dataStore->heatWaveActive <= 0 || $kobold->getFatigue() <= $baselineFatigue) { |
| 920 | $kobold->removeInjury('heatstroke'); |
| 921 | } |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | foreach ($this->kobolds as $kobold) { |
| 926 | $kobold->resetFatigue(); |
| 927 | } |
| 928 | |
| 929 | $seasons = ['spring', 'summer', 'autumn', 'winter']; |
| 930 | |
| 931 | $monthOfYear = (($this->currentMonth - 1) % 12) + 1; |
| 932 | $index = intdiv($monthOfYear - 1, 3); |
| 933 | $pIndex = ($index + 3) % 4; |
| 934 | |
| 935 | $previousSeason = $seasons[$pIndex]; |
| 936 | $this->currentSeason = $seasons[$index]; |
| 937 | |
| 938 | if ($previousSeason == 'spring' && $this->currentSeason == 'summer') { |
| 939 | if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) { |
| 940 | $noHarvestVariations = [ |
| 941 | "No seeds were sown in spring, so there can be no harvest come autumn.\n", |
| 942 | "With spring left untilled, there can be no harvest in autumn.\n", |
| 943 | "Spring passed without sowing; there can be no harvest this autumn.\n", |
| 944 | "The tribe never sowed in spring, so there can be no harvest later.\n", |
| 945 | "Nothing was planted in spring—there can be no harvest in autumn.\n", |
| 946 | "Spring's fields lay empty, and there can be no harvest ahead.\n", |
| 947 | "No planting happened in spring, so there can be no harvest when autumn arrives.\n" |
| 948 | ]; |
| 949 | $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)]; |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | if ( |
| 954 | isset($this->dataStore->wasSowedInSpring) |
| 955 | && $this->dataStore->wasSowedInSpring |
| 956 | && $previousSeason == 'summer' |
| 957 | && $this->currentSeason == 'autumn' |
| 958 | ) { |
| 959 | if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever |
| 960 | $cropLossVariations = [ |
| 961 | "The fields were not tended in summer, and all of the crops are lost.\n", |
| 962 | "Neglected through summer, all of the crops are lost.\n", |
| 963 | "With no summer care, all of the crops are lost to blight and pests.\n", |
| 964 | "Summer passed without tending the fields, and all of the crops are lost.\n", |
| 965 | "The fields were left to wild growth; all of the crops are lost.\n", |
| 966 | "No hands worked the fields in summer, so all of the crops are lost.\n", |
| 967 | "Left untended through summer, all of the crops are lost.\n" |
| 968 | ]; |
| 969 | $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | if ( |
| 974 | isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened |
| 975 | && $this->dataStore->wasTendedInSummer |
| 976 | && $previousSeason == 'summer' |
| 977 | && $this->currentSeason == 'autumn' |
| 978 | ) { |
| 979 | $cropLossVariations = [ |
| 980 | "The crops stood too long, and winter's cold ruined what should have been gathered.\n", |
| 981 | "Harvest came too late; the first hard freezes destroyed the crops.\n", |
| 982 | "No harvest was taken in time, and the winter cold ruined the fields.\n", |
| 983 | "The fields were left unharvested, and winter's chill destroyed the crops.\n", |
| 984 | "The tribe missed the harvest window, and the cold of winter claimed the crops.\n", |
| 985 | "By the time harvest was attempted, winter had already destroyed the crops.\n", |
| 986 | "The crops were left in the fields until winter, and the cold destroyed them.\n" |
| 987 | ]; |
| 988 | $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; |
| 989 | } |
| 990 | |
| 991 | // Execute end-of-month events |
| 992 | $monthEventStory = $ongoingWeatherStory; |
| 993 | $endOfMonthEvents = $this->getEndOfMonthEvents(); |
| 994 | |
| 995 | $hasFloodEvent = false; |
| 996 | foreach ($endOfMonthEvents as $event) { |
| 997 | $className = get_class($event); |
| 998 | if ($className === 'SmallFloodEvent' || $className === 'LargeFloodEvent') { |
| 999 | $hasFloodEvent = true; |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | if ($hasFloodEvent) { |
| 1004 | $this->dataStore->floodedThisMonth = true; |
| 1005 | $endOfMonthEvents = array_values(array_filter($endOfMonthEvents, function ($event) { |
| 1006 | return get_class($event) !== 'DroughtEvent'; |
| 1007 | })); |
| 1008 | } |
| 1009 | |
| 1010 | foreach ($endOfMonthEvents as $event) { |
| 1011 | $aliveBeforeEvent = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); |
| 1012 | $eventClass = get_class($event); |
| 1013 | $eventLabel = preg_replace('/Event$/', '', $eventClass); |
| 1014 | $eventLabel = strtolower(preg_replace('/([a-z])([A-Z])/', '$1 $2', $eventLabel)); |
| 1015 | |
| 1016 | // Select eligible participants |
| 1017 | $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) { |
| 1018 | return $kobold->getAge() >= $event->getMinAge(); |
| 1019 | }); |
| 1020 | |
| 1021 | if (count($eligible) < $event->getMinParticipants()) { |
| 1022 | continue; |
| 1023 | } |
| 1024 | |
| 1025 | // Randomly select participants (between min and max) |
| 1026 | $eligible = array_values($eligible); |
| 1027 | shuffle($eligible); |
| 1028 | $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible))); |
| 1029 | $participants = array_slice($eligible, 0, $participantCount); |
| 1030 | $participantIds = array_map(fn($k) => $k->getId(), $participants); |
| 1031 | |
| 1032 | // Set participants and execute event |
| 1033 | $event->setParticipants($participantIds); |
| 1034 | $event->execute(); |
| 1035 | |
| 1036 | foreach ($event->getReportedDeaths() as $deadId) { |
| 1037 | $reportedDeaths[$deadId] = true; |
| 1038 | } |
| 1039 | |
| 1040 | foreach ($aliveBeforeEvent as $deadId) { |
| 1041 | $kobold = $this->getKobold($deadId); |
| 1042 | if (!$kobold || !$kobold->isDead()) { |
| 1043 | continue; |
| 1044 | } |
| 1045 | |
| 1046 | if (!isset($reportedDeaths[$deadId])) { |
| 1047 | $deathMessage = null; |
| 1048 | if (isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass) { |
| 1049 | $deathMessage = $kobold->dataStore->lastDeathMessage ?? null; |
| 1050 | if ($deathMessage) { |
| 1051 | unset($kobold->dataStore->lastDeathMessage); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | if ($deathMessage) { |
| 1056 | $monthEventStory .= $deathMessage . "\n"; |
| 1057 | } else { |
| 1058 | $monthEventStory .= $kobold->getName() . " died during the {$eventLabel}.\n"; |
| 1059 | } |
| 1060 | $reportedDeaths[$deadId] = true; |
| 1061 | } |
| 1062 | } |
| 1063 | |
| 1064 | foreach ($participants as $participant) { |
| 1065 | if ($participant->isDead() && !isset($reportedDeaths[$participant->getId()])) { |
| 1066 | $deathMessage = null; |
| 1067 | if (isset($participant->dataStore) && $participant->dataStore instanceof stdClass) { |
| 1068 | $deathMessage = $participant->dataStore->lastDeathMessage ?? null; |
| 1069 | if ($deathMessage) { |
| 1070 | unset($participant->dataStore->lastDeathMessage); |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | if ($deathMessage) { |
| 1075 | $monthEventStory .= $deathMessage . "\n"; |
| 1076 | } else { |
| 1077 | $monthEventStory .= $participant->getName() . " has died.\n"; |
| 1078 | } |
| 1079 | $reportedDeaths[$participant->getId()] = true; |
| 1080 | } |
| 1081 | $participant->save(); |
| 1082 | } |
| 1083 | |
| 1084 | // Add event story |
| 1085 | if ($event->getStory()) { |
| 1086 | $monthEventStory .= $event->getStory() . "\n\n"; |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | // After events, consume food |
| 1091 | |
| 1092 | // age eggs |
| 1093 | $aliveBeforeFood = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); |
| 1094 | $foodStory = "A month passes...\n" . $this->consumeFood(); |
| 1095 | $aliveAfterFood = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); |
| 1096 | $foodDeaths = array_diff($aliveBeforeFood, $aliveAfterFood); |
| 1097 | foreach ($foodDeaths as $deadId) { |
| 1098 | $reportedDeaths[$deadId] = true; |
| 1099 | } |
| 1100 | if ($monthEventStory) { |
| 1101 | $foodStory = $monthEventStory . "\n" . $foodStory; |
| 1102 | } |
| 1103 | |
| 1104 | foreach ($this->kobolds as $kobold) { |
| 1105 | if ($kobold->getAge() < 0) { |
| 1106 | $kobold->incrementAge(); |
| 1107 | |
| 1108 | if ($kobold->getAge() >= 0) { |
| 1109 | $kobold->setName(Kobold::generateRandomName()); |
| 1110 | $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n"; |
| 1111 | } |
| 1112 | |
| 1113 | $kobold->save(); |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | // Age all kobolds |
| 1118 | if ($this->currentMonth % 12 === 0) { |
| 1119 | $foodStory .= "A new year begins.\n"; |
| 1120 | |
| 1121 | foreach ($this->kobolds as $kobold) { |
| 1122 | $wasAlive = !$kobold->isDead(); |
| 1123 | $foodStory .= $this->ageKobold($kobold); |
| 1124 | if ($wasAlive && $kobold->isDead()) { |
| 1125 | $reportedDeaths[$kobold->getId()] = true; |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | foreach ($this->rivals as $kobold) { |
| 1130 | $this->ageKobold($kobold); //we don't log these |
| 1131 | } |
| 1132 | } |
| 1133 | $foodStory .= "\n" . $this->tryMate(); |
| 1134 | $foodStory .= "\nIt's {$this->currentSeason}.\n"; |
| 1135 | |
| 1136 | $aliveAtEnd = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); |
| 1137 | $newDeaths = array_diff($aliveAtStart, $aliveAtEnd); |
| 1138 | foreach ($newDeaths as $deadId) { |
| 1139 | if (isset($reportedDeaths[$deadId])) { |
| 1140 | continue; |
| 1141 | } |
| 1142 | |
| 1143 | $kobold = $this->getKobold($deadId); |
| 1144 | if (!$kobold) { |
| 1145 | continue; |
| 1146 | } |
| 1147 | |
| 1148 | $deathMessage = null; |
| 1149 | if (isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass) { |
| 1150 | $deathMessage = $kobold->dataStore->lastDeathMessage ?? null; |
| 1151 | if ($deathMessage) { |
| 1152 | unset($kobold->dataStore->lastDeathMessage); |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | if ($deathMessage) { |
| 1157 | $foodStory .= "\n" . $deathMessage; |
| 1158 | } else { |
| 1159 | $injuryDeath = $kobold->getTotalInjurySeverity() >= (int) ($kobold->getStat('vitality') ?? 0); |
| 1160 | if ($injuryDeath) { |
| 1161 | $foodStory .= "\n" . $kobold->getName() . " succumbed to injuries."; |
| 1162 | } else { |
| 1163 | $foodStory .= "\n" . $kobold->getName() . " died."; |
| 1164 | } |
| 1165 | } |
| 1166 | $reportedDeaths[$deadId] = true; |
| 1167 | } |
| 1168 | |
| 1169 | $hasLeader = false; |
| 1170 | foreach ($this->getKobolds() as $kobold) { |
| 1171 | if ($kobold->isLeader()) { |
| 1172 | $hasLeader = true; |
| 1173 | break; |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | if (!$hasLeader) { |
| 1178 | $eligibleKobolds = array_filter($this->getKobolds(), function ($kobold) { |
| 1179 | return $kobold->getAgeCategory() !== 'egg'; |
| 1180 | }); |
| 1181 | |
| 1182 | if (count($eligibleKobolds) >= 3) { |
| 1183 | $pickFromTier = function ($tier) { |
| 1184 | return array_values(array_filter($this->getKobolds(), function ($kobold) use ($tier) { |
| 1185 | return $kobold->getAgeCategory() === $tier; |
| 1186 | })); |
| 1187 | }; |
| 1188 | |
| 1189 | $candidatePools = [ |
| 1190 | $pickFromTier('adult'), |
| 1191 | $pickFromTier('old'), |
| 1192 | $pickFromTier('young') |
| 1193 | ]; |
| 1194 | |
| 1195 | $candidates = []; |
| 1196 | foreach ($candidatePools as $pool) { |
| 1197 | if (!empty($pool)) { |
| 1198 | $candidates = $pool; |
| 1199 | break; |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | if (!empty($candidates)) { |
| 1204 | $scores = []; |
| 1205 | foreach ($candidates as $candidate) { |
| 1206 | $score = 0; |
| 1207 | foreach ($this->getKobolds() as $other) { |
| 1208 | if ($other->getId() === $candidate->getId()) { |
| 1209 | continue; |
| 1210 | } |
| 1211 | |
| 1212 | $likes = 0; |
| 1213 | if (isset($other->dataStore) && $other->dataStore instanceof stdClass) { |
| 1214 | if (isset($other->dataStore->likes) && is_array($other->dataStore->likes)) { |
| 1215 | $likes = (int) ($other->dataStore->likes[$candidate->getId()] ?? 0); |
| 1216 | } |
| 1217 | } |
| 1218 | $score += $likes; |
| 1219 | } |
| 1220 | $scores[$candidate->getId()] = $score; |
| 1221 | } |
| 1222 | |
| 1223 | $maxScore = max($scores); |
| 1224 | $topCandidates = array_values(array_filter($candidates, function ($candidate) use ($scores, $maxScore) { |
| 1225 | return $scores[$candidate->getId()] === $maxScore; |
| 1226 | })); |
| 1227 | |
| 1228 | if (count($topCandidates) > 1) { |
| 1229 | usort($topCandidates, function ($a, $b) { |
| 1230 | return $b->getAge() <=> $a->getAge(); |
| 1231 | }); |
| 1232 | |
| 1233 | $oldestAge = $topCandidates[0]->getAge(); |
| 1234 | $topCandidates = array_values(array_filter($topCandidates, function ($candidate) use ($oldestAge) { |
| 1235 | return $candidate->getAge() === $oldestAge; |
| 1236 | })); |
| 1237 | } |
| 1238 | |
| 1239 | $newLeader = $topCandidates[array_rand($topCandidates)]; |
| 1240 | $newLeader->setLeader(); |
| 1241 | |
| 1242 | $leaderName = $newLeader->getName(); |
| 1243 | $leaderStories = [ |
| 1244 | "With no chieftain to guide the camp, the elders called a gathering. Voices rose and fell until a clear choice emerged, and {$leaderName} was named to lead. The tribe settled as the new chieftain accepted the duty.", |
| 1245 | "The tribe woke to a quiet worry with no leader among them. By sundown the council had met, and {$leaderName} was chosen to carry the tribe's future. The fires burned steady as the new chieftain took the mantle.", |
| 1246 | "Without a chieftain, the camp felt adrift. The elders weighed the tribe's voices and set their trust in {$leaderName}. The tribe marked the choice with a solemn vow and returned to their work with purpose.", |
| 1247 | "A leaderless tribe called for order, so the elders gathered to decide. After careful words and long thought, {$leaderName} was raised as chieftain. A quiet cheer moved through the dens as the tribe accepted the new guide.", |
| 1248 | "As the month closed, the tribe turned to its oldest voices for direction. The council placed the burden of leadership on {$leaderName}. The camp steadied as the new chieftain promised to protect the tribe.", |
| 1249 | "The fires crackled while the elders spoke of who should lead. In the end, {$leaderName} stood before the tribe as the chosen chieftain. The tribe nodded as one, and a new season of leadership began.", |
| 1250 | "A tribe without a leader cannot last, so the adults met to decide. They chose {$leaderName} to take the chieftain's role. The camp settled into a calm rhythm as the new leader's voice carried.", |
| 1251 | "With no chieftain among them, the tribe held a council beneath the evening sky. The decision came in favor of {$leaderName}, who accepted the weight of leadership. The tribe returned to their huts with renewed confidence.", |
| 1252 | "The tribe convened an elders' circle to fill the empty seat of leadership. After debate and silence, {$leaderName} was named chieftain. The camp honored the choice and moved forward together.", |
| 1253 | "Leadership was needed, and the tribe did not delay. The elders agreed that {$leaderName} should guide them, and the tribe affirmed the decision. The new chieftain's first night ended with a calm and steady watch." |
| 1254 | ]; |
| 1255 | |
| 1256 | $foodStory .= "\n" . $leaderStories[array_rand($leaderStories)] . "\n"; |
| 1257 | } |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | $this->save(); |
| 1262 | |
| 1263 | return $foodStory; |
| 1264 | } |
| 1265 | |
| 1266 | function ageKobold($kobold) |
| 1267 | { |
| 1268 | $foodStory = ""; |
| 1269 | if ($kobold->getAge() >= 0) { |
| 1270 | $kobold->incrementAge(); |
| 1271 | |
| 1272 | // Check for old-age injuries |
| 1273 | if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) { |
| 1274 | $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue']; |
| 1275 | $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)]; |
| 1276 | $kobold->addInjury($injury); |
| 1277 | } |
| 1278 | |
| 1279 | // Old-age death roll: if roll < (age + total injury severity), kobold dies |
| 1280 | if ($kobold->getAge() >= 35) { |
| 1281 | $roll = rand(1, 100); |
| 1282 | $totalSeverity = $kobold->getTotalInjurySeverity(); |
| 1283 | if ($roll < ($kobold->getAge() + $totalSeverity)) { |
| 1284 | $foodStory .= $kobold->getName() . " dies of old age.\n"; |
| 1285 | $this->cleanupDeadKoboldLikes($kobold->getId()); |
| 1286 | $kobold->die(); |
| 1287 | } |
| 1288 | } |
| 1289 | |
| 1290 | $kobold->save(); |
| 1291 | } |
| 1292 | return $foodStory; |
| 1293 | } |
| 1294 | |
| 1295 | private function shouldAddOldAgeInjury(Kobold $kobold) |
| 1296 | { |
| 1297 | // 1d100 roll under age starting at 35 |
| 1298 | $roll = rand(1, 100); |
| 1299 | return $roll <= $kobold->getAge(); |
| 1300 | } |
| 1301 | |
| 1302 | /** |
| 1303 | * Clean up all likes references to a kobold when they die |
| 1304 | * Removes the kobold's ID from all other kobolds' likes arrays |
| 1305 | * and from rival records |
| 1306 | */ |
| 1307 | private function cleanupDeadKoboldLikes($koboldId) |
| 1308 | { |
| 1309 | // Remove from all other kobolds' likes |
| 1310 | foreach ($this->kobolds as $other) { |
| 1311 | if ($other->getId() !== $koboldId) { |
| 1312 | if (!isset($other->dataStore)) { |
| 1313 | $other->dataStore = new stdClass(); |
| 1314 | } |
| 1315 | if (!isset($other->dataStore->likes)) { |
| 1316 | $other->dataStore->likes = []; |
| 1317 | } |
| 1318 | |
| 1319 | // Remove the dead kobold from this kobold's likes |
| 1320 | if (is_array($other->dataStore->likes)) { |
| 1321 | unset($other->dataStore->likes[$koboldId]); |
| 1322 | } |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | // Remove from rivals' likes if they exist |
| 1327 | if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) { |
| 1328 | foreach ($this->dataStore->rivals as &$rival) { |
| 1329 | if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) { |
| 1330 | unset($rival['data']['likes'][$koboldId]); |
| 1331 | } |
| 1332 | } |
| 1333 | } |
| 1334 | } |
| 1335 | } |