| 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 | private function loadStorage() |
| 112 | { |
| 113 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 114 | $itemsFile = $savePath . '/items.json'; |
| 115 | |
| 116 | $this->storage = []; |
| 117 | |
| 118 | if (file_exists($itemsFile)) { |
| 119 | $this->storage = $this->saveManager->loadJson($itemsFile) ?? []; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | public function save() |
| 124 | { |
| 125 | $this->lastPlayed = date('Y-m-d H:i:s'); |
| 126 | |
| 127 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 128 | |
| 129 | // Save tribe metadata |
| 130 | $tribeData = [ |
| 131 | 'name' => $this->name, |
| 132 | 'current_month' => $this->currentMonth, |
| 133 | 'current_season' => $this->currentSeason, |
| 134 | 'food_count' => $this->foodCount, |
| 135 | 'food_time_left' => $this->foodTimeStr($this->foodCount), |
| 136 | 'environment_id' => $this->environmentId, |
| 137 | 'created_at' => $this->createdAt, |
| 138 | 'last_played' => $this->lastPlayed, |
| 139 | 'data_store' => $this->dataStore ?? new stdClass() |
| 140 | ]; |
| 141 | |
| 142 | $this->saveManager->saveJson($savePath . '/save.json', $tribeData); |
| 143 | |
| 144 | // Save kobolds |
| 145 | $koboldsData = []; |
| 146 | foreach ($this->kobolds as $kobold) { |
| 147 | if (!$kobold->isDead()) { |
| 148 | $kobold->save(); |
| 149 | $koboldsData[] = $kobold->toArray(); |
| 150 | } |
| 151 | } |
| 152 | foreach ($this->rivals as $kobold) { |
| 153 | if (!$kobold->isDead()) { |
| 154 | $kobold->save(); |
| 155 | $koboldsData[] = $kobold->toArray(); |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData); |
| 160 | |
| 161 | // Save items |
| 162 | $this->saveManager->saveJson($savePath . '/items.json', $this->storage); |
| 163 | |
| 164 | GameHelper::cleanupUnusedKoboldSprites($this->userId); |
| 165 | } |
| 166 | |
| 167 | // Getters and Setters |
| 168 | public function getName() |
| 169 | { |
| 170 | return $this->name; |
| 171 | } |
| 172 | |
| 173 | public function setName($name) |
| 174 | { |
| 175 | $this->name = $name; |
| 176 | } |
| 177 | |
| 178 | public function getSaveId() |
| 179 | { |
| 180 | return $this->saveId; |
| 181 | } |
| 182 | |
| 183 | public function getUserId() |
| 184 | { |
| 185 | return $this->userId; |
| 186 | } |
| 187 | |
| 188 | public function getCreatedAt() |
| 189 | { |
| 190 | return $this->createdAt; |
| 191 | } |
| 192 | |
| 193 | public function getLastPlayed() |
| 194 | { |
| 195 | return $this->lastPlayed; |
| 196 | } |
| 197 | |
| 198 | public function getCurrentMonth() |
| 199 | { |
| 200 | return $this->currentMonth; |
| 201 | } |
| 202 | |
| 203 | public function setCurrentMonth($month) |
| 204 | { |
| 205 | $this->currentMonth = max(0, $month); |
| 206 | } |
| 207 | |
| 208 | public function getCurrentSeason() |
| 209 | { |
| 210 | return $this->currentSeason; |
| 211 | } |
| 212 | |
| 213 | public function setCurrentSeason($season) |
| 214 | { |
| 215 | $this->currentSeason = $season; |
| 216 | } |
| 217 | |
| 218 | public function getEnvironmentId() |
| 219 | { |
| 220 | return $this->environmentId; |
| 221 | } |
| 222 | |
| 223 | public function setEnvironmentId($environmentId) |
| 224 | { |
| 225 | $this->environmentId = $environmentId; |
| 226 | } |
| 227 | |
| 228 | // Kobold management |
| 229 | public function getKobolds($includeDeadAndExpelled = false) |
| 230 | { |
| 231 | if ($includeDeadAndExpelled) { |
| 232 | return $this->kobolds; |
| 233 | } |
| 234 | |
| 235 | return array_filter($this->kobolds, function (Kobold $k) { |
| 236 | return !$k->isDead() && !$k->isExpelled(); |
| 237 | }); |
| 238 | } |
| 239 | |
| 240 | public function getKobold($id) |
| 241 | { |
| 242 | return $this->kobolds[$id] ?? null; |
| 243 | } |
| 244 | |
| 245 | public function addKobold(Kobold $kobold) |
| 246 | { |
| 247 | $this->kobolds[$kobold->getId()] = $kobold; |
| 248 | return $kobold; |
| 249 | } |
| 250 | |
| 251 | public function removeKobold($id) |
| 252 | { |
| 253 | unset($this->kobolds[$id]); |
| 254 | } |
| 255 | |
| 256 | public function getAliveKobolds() |
| 257 | { |
| 258 | return array_filter($this->kobolds, fn($k) => !$k->isDead()); |
| 259 | } |
| 260 | |
| 261 | // Storage management |
| 262 | public function addToStorage(Item $item, int $count = 1): array |
| 263 | { |
| 264 | // Accept either Item object or array |
| 265 | if (is_object($item) && method_exists($item, 'toArray')) { |
| 266 | $this->storage[] = $item->toArray(); |
| 267 | } elseif (is_array($item)) { |
| 268 | // Ensure it has an id |
| 269 | if (!isset($item['id'])) { |
| 270 | $item['id'] = uniqid('itm_'); |
| 271 | } |
| 272 | for ($i = 0; $i < $count; $i++) |
| 273 | $this->storage[] = $item; |
| 274 | } |
| 275 | return $this->storage; |
| 276 | } |
| 277 | |
| 278 | public function getStorage() |
| 279 | { |
| 280 | return $this->storage; |
| 281 | } |
| 282 | |
| 283 | // Food system methods |
| 284 | public function getFoodCount() |
| 285 | { |
| 286 | return $this->foodCount; |
| 287 | } |
| 288 | |
| 289 | public function addFood($amount) |
| 290 | { |
| 291 | $this->foodCount += $amount; |
| 292 | return $this->foodCount; |
| 293 | } |
| 294 | |
| 295 | public function removeFood($amount) |
| 296 | { |
| 297 | $this->foodCount = max(0, $this->foodCount - $amount); |
| 298 | return $this->foodCount; |
| 299 | } |
| 300 | |
| 301 | /** |
| 302 | * Calculate total food needed for all alive kobolds for one month |
| 303 | */ |
| 304 | public function calculateFoodNeeded() |
| 305 | { |
| 306 | $needed = 0; |
| 307 | |
| 308 | foreach ($this->getAliveKobolds() as $kobold) { |
| 309 | $ageCategory = $kobold->getAgeCategory(); |
| 310 | $requirement = $this->foodRequirements[$ageCategory] ?? 1.0; |
| 311 | $needed += $requirement; |
| 312 | } |
| 313 | |
| 314 | return $needed; |
| 315 | } |
| 316 | |
| 317 | /** |
| 318 | * Calculate how many full months the current kobolds can be fed |
| 319 | * with the provided amount of food. |
| 320 | */ |
| 321 | public function foodMonthsLeft($amount) |
| 322 | { |
| 323 | $foodPerMonth = $this->calculateFoodNeeded(); |
| 324 | if ($foodPerMonth <= 0) { |
| 325 | return 0; |
| 326 | } |
| 327 | |
| 328 | $available = max(0, (float) $amount); |
| 329 | return (int) floor($available / $foodPerMonth); |
| 330 | } |
| 331 | |
| 332 | public function foodTimeStr($amount) |
| 333 | { |
| 334 | $months = $this->foodMonthsLeft($amount); |
| 335 | if ($months > 0) { |
| 336 | if ($months == 1) |
| 337 | return "1 month"; |
| 338 | else |
| 339 | return "{$months} months"; |
| 340 | } |
| 341 | |
| 342 | $foodPerMonth = $this->calculateFoodNeeded(); |
| 343 | if ($foodPerMonth <= 0) { |
| 344 | return "years"; |
| 345 | } |
| 346 | |
| 347 | $available = max(0, (float) $amount); |
| 348 | $days = (int) floor(($available / $foodPerMonth) * 30); |
| 349 | $weeks = intdiv($days, 7); |
| 350 | |
| 351 | if ($weeks >= 1) { |
| 352 | return $weeks . " week" . ($weeks === 1 ? "" : "s"); |
| 353 | } |
| 354 | |
| 355 | return $days . " day" . ($days === 1 ? "" : "s"); |
| 356 | } |
| 357 | |
| 358 | /** |
| 359 | * Get food requirement for a specific kobold |
| 360 | */ |
| 361 | public function getFoodRequirement(Kobold $kobold) |
| 362 | { |
| 363 | $ageCategory = $kobold->getAgeCategory(); |
| 364 | return $this->foodRequirements[$ageCategory] ?? 1.0; |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Consume food at end of month after events |
| 369 | * Prioritizes: malnourished kobolds first, then younger before older |
| 370 | * Returns story of food consumption and any starvations |
| 371 | */ |
| 372 | public function consumeFood() |
| 373 | { |
| 374 | $story = ""; |
| 375 | $aliveKobolds = $this->getAliveKobolds(); |
| 376 | |
| 377 | if (empty($aliveKobolds)) { |
| 378 | return $story; |
| 379 | } |
| 380 | |
| 381 | // Sort kobolds: malnourished first, then by age (younger first) |
| 382 | usort($aliveKobolds, function ($a, $b) { |
| 383 | // Check for malnourished injury |
| 384 | $aMalnourished = $this->hasInjuryCategory($a, 'malnourished'); |
| 385 | $bMalnourished = $this->hasInjuryCategory($b, 'malnourished'); |
| 386 | |
| 387 | if ($aMalnourished && !$bMalnourished) |
| 388 | return -1; |
| 389 | if (!$aMalnourished && $bMalnourished) |
| 390 | return 1; |
| 391 | |
| 392 | // Both have or both don't have malnourished |
| 393 | // Younger first (lower age = higher priority) |
| 394 | return $a->getAge() - $b->getAge(); |
| 395 | }); |
| 396 | |
| 397 | $fedKobolds = []; |
| 398 | $starvedKobolds = []; |
| 399 | |
| 400 | foreach ($aliveKobolds as $kobold) { |
| 401 | $needed = $this->getFoodRequirement($kobold); |
| 402 | |
| 403 | if ($this->foodCount >= $needed) { |
| 404 | // Fed this kobold |
| 405 | $this->foodCount -= $needed; |
| 406 | $fedKobolds[$kobold->getId()] = $kobold; |
| 407 | |
| 408 | // If malnourished, cure it |
| 409 | if ($this->hasInjuryCategory($kobold, 'malnourished')) { |
| 410 | $this->removeMalnourishedInjury($kobold); |
| 411 | $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n"; |
| 412 | } |
| 413 | } else { |
| 414 | // Not enough food - starve this kobold |
| 415 | $starvedKobolds[$kobold->getId()] = $kobold; |
| 416 | $this->foodCount = 0; // Use remaining food |
| 417 | |
| 418 | |
| 419 | $malnourishedId = $this->getMalnourishedInjuryId($kobold); |
| 420 | if (!$malnourishedId) { |
| 421 | $kobold->addInjury('malnourished-slight'); |
| 422 | $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n"; |
| 423 | } else { |
| 424 | if ($malnourishedId === 'malnourished-slight') { |
| 425 | $kobold->removeInjury($malnourishedId); |
| 426 | $kobold->addInjury('malnourished-mild'); |
| 427 | $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n"; |
| 428 | } elseif ($malnourishedId === 'malnourished-mild') { |
| 429 | $kobold->removeInjury($malnourishedId); |
| 430 | $kobold->addInjury('malnourished-severe'); |
| 431 | $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n"; |
| 432 | } elseif ($malnourishedId === 'malnourished-severe') { |
| 433 | $kobold->removeInjury($malnourishedId); |
| 434 | $kobold->addInjury('malnourished-brink'); |
| 435 | $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n"; |
| 436 | } elseif ($malnourishedId === 'malnourished-brink') { |
| 437 | $kobold->die(); |
| 438 | $story .= "{$kobold->getName()} succumbed to starvation.\n"; |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // Save updated kobolds |
| 445 | foreach ($aliveKobolds as $kobold) { |
| 446 | $kobold->save(); |
| 447 | } |
| 448 | |
| 449 | return $story; |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Check if a kobold has an injury in a specific category |
| 454 | */ |
| 455 | private function hasInjuryCategory(Kobold $kobold, $category) |
| 456 | { |
| 457 | $injuries = $kobold->getInjuries(); |
| 458 | foreach ($injuries as $injury) { |
| 459 | if ($injury['category'] === $category) { |
| 460 | return true; |
| 461 | } |
| 462 | } |
| 463 | return false; |
| 464 | } |
| 465 | |
| 466 | /** |
| 467 | * Remove all malnourished injuries from a kobold |
| 468 | */ |
| 469 | private function removeMalnourishedInjury(Kobold $kobold) |
| 470 | { |
| 471 | $injuries = $kobold->getInjuries(); |
| 472 | foreach ($injuries as $injury) { |
| 473 | if ($injury['category'] === 'malnourished') { |
| 474 | $kobold->removeInjury($injury['id']); |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | /** |
| 480 | * Get current malnourished injury id if present |
| 481 | */ |
| 482 | private function getMalnourishedInjuryId(Kobold $kobold) |
| 483 | { |
| 484 | $injuries = $kobold->getInjuries(); |
| 485 | foreach ($injuries as $injury) { |
| 486 | if (($injury['category'] ?? null) === 'malnourished') { |
| 487 | return $injury['id'] ?? null; |
| 488 | } |
| 489 | } |
| 490 | return null; |
| 491 | } |
| 492 | |
| 493 | public function tryMate() |
| 494 | { |
| 495 | $kobolds = array_values($this->getKobolds()); |
| 496 | $count = count($kobolds); |
| 497 | |
| 498 | if ($count === 0) { |
| 499 | return ''; |
| 500 | } |
| 501 | |
| 502 | $roll = rand(1, 30); |
| 503 | if ($roll <= $count) { |
| 504 | return ''; |
| 505 | } |
| 506 | |
| 507 | $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult')); |
| 508 | $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult')); |
| 509 | |
| 510 | if (empty($males) || empty($females)) { |
| 511 | return ''; |
| 512 | } |
| 513 | |
| 514 | $pair = null; |
| 515 | $attempts = 20; |
| 516 | while ($attempts-- > 0) { |
| 517 | $male = $males[array_rand($males)]; |
| 518 | $female = $females[array_rand($females)]; |
| 519 | |
| 520 | $maleParents = $male->getParents(); |
| 521 | $femaleParents = $female->getParents(); |
| 522 | |
| 523 | $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null); |
| 524 | $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null); |
| 525 | $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null); |
| 526 | $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null); |
| 527 | |
| 528 | if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) { |
| 529 | continue; |
| 530 | } |
| 531 | |
| 532 | $pair = [$male, $female]; |
| 533 | break; |
| 534 | } |
| 535 | |
| 536 | if (!$pair) { |
| 537 | return ''; |
| 538 | } |
| 539 | |
| 540 | [$male, $female] = $pair; |
| 541 | |
| 542 | if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) { |
| 543 | return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off."; |
| 544 | } |
| 545 | |
| 546 | $child = Kobold::generate($this->userId, $this->saveId, -6); |
| 547 | |
| 548 | if (!isset($child->dataStore)) { |
| 549 | $child->dataStore = new stdClass(); |
| 550 | } |
| 551 | if (!isset($child->dataStore->likes)) { |
| 552 | $child->dataStore->likes = []; |
| 553 | } |
| 554 | |
| 555 | // Child likes parents by default |
| 556 | $child->dataStore->likes[$male->getId()] = 10; |
| 557 | $child->dataStore->likes[$female->getId()] = 10; |
| 558 | |
| 559 | // Initialize parents' dataStore if needed |
| 560 | if (!isset($male->dataStore)) { |
| 561 | $male->dataStore = new stdClass(); |
| 562 | } |
| 563 | if (!isset($male->dataStore->likes)) { |
| 564 | $male->dataStore->likes = []; |
| 565 | } |
| 566 | |
| 567 | if (!isset($female->dataStore)) { |
| 568 | $female->dataStore = new stdClass(); |
| 569 | } |
| 570 | if (!isset($female->dataStore->likes)) { |
| 571 | $female->dataStore->likes = []; |
| 572 | } |
| 573 | |
| 574 | // Parents like the child by default |
| 575 | $male->dataStore->likes[$child->getId()] = 20; |
| 576 | $female->dataStore->likes[$child->getId()] = 20; |
| 577 | |
| 578 | $inheritRoll = rand(1, 100); |
| 579 | if ($inheritRoll <= 40) { |
| 580 | $child->setSpriteMorph($male->getSpriteMorph()); |
| 581 | } elseif ($inheritRoll <= 80) { |
| 582 | $child->setSpriteMorph($female->getSpriteMorph()); |
| 583 | } |
| 584 | |
| 585 | $blendHex = function ($a, $b) { |
| 586 | $hexToRgb = function ($hex) { |
| 587 | $hex = ltrim($hex, '#'); |
| 588 | return [ |
| 589 | 'r' => hexdec(substr($hex, 0, 2)), |
| 590 | 'g' => hexdec(substr($hex, 2, 2)), |
| 591 | 'b' => hexdec(substr($hex, 4, 2)) |
| 592 | ]; |
| 593 | }; |
| 594 | |
| 595 | $rgbToHex = function ($rgb) { |
| 596 | return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']); |
| 597 | }; |
| 598 | |
| 599 | $ra = $hexToRgb($a); |
| 600 | $rb = $hexToRgb($b); |
| 601 | $ratio = rand(0, 100) / 100; |
| 602 | |
| 603 | $offset = function () { |
| 604 | return rand(-20, 20); |
| 605 | }; |
| 606 | |
| 607 | $mix = function ($c1, $c2) use ($ratio, $offset) { |
| 608 | $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset()); |
| 609 | return max(0, min(255, $val)); |
| 610 | }; |
| 611 | |
| 612 | $mixed = [ |
| 613 | 'r' => $mix($ra['r'], $rb['r']), |
| 614 | 'g' => $mix($ra['g'], $rb['g']), |
| 615 | 'b' => $mix($ra['b'], $rb['b']) |
| 616 | ]; |
| 617 | |
| 618 | return $rgbToHex($mixed); |
| 619 | }; |
| 620 | |
| 621 | $maleColours = $male->getColours(); |
| 622 | $femaleColours = $female->getColours(); |
| 623 | |
| 624 | $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']); |
| 625 | $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']); |
| 626 | $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']); |
| 627 | |
| 628 | $child->setColours($childPrimary, $childSecondary, $childTertiary); |
| 629 | $child->setParents($male->getId(), $female->getId()); |
| 630 | $child->regenerateSprite(); |
| 631 | |
| 632 | $this->addKobold($child); |
| 633 | |
| 634 | $pairName = $female->getName() . " and " . $male->getName(); |
| 635 | $momName = $female->getName(); |
| 636 | $variations = [ |
| 637 | "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!", |
| 638 | "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.", |
| 639 | "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.", |
| 640 | "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.", |
| 641 | "After many shared moments, {$pairName} welcomed a new egg from {$momName}.", |
| 642 | "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.", |
| 643 | "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.", |
| 644 | "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.", |
| 645 | "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.", |
| 646 | "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg." |
| 647 | ]; |
| 648 | |
| 649 | return $variations[array_rand($variations)]; |
| 650 | } |
| 651 | |
| 652 | public function getEndOfMonthEvents(): array |
| 653 | { |
| 654 | $maxCost = 500; |
| 655 | $selectedEvents = []; |
| 656 | $totalCost = 0; |
| 657 | |
| 658 | // Scan src/Events directory for event classes |
| 659 | $eventsDir = __DIR__ . '/../../src/Events/'; |
| 660 | $eventFiles = glob($eventsDir . '*.php'); |
| 661 | $availableEventClasses = []; |
| 662 | |
| 663 | foreach ($eventFiles as $file) { |
| 664 | $className = basename($file, '.php'); |
| 665 | |
| 666 | // Skip base classes |
| 667 | if ($className === 'Event' || $className === 'MonthEndEvent') { |
| 668 | continue; |
| 669 | } |
| 670 | |
| 671 | require_once $file; |
| 672 | |
| 673 | // Check if class exists and extends MonthEndEvent |
| 674 | if (!class_exists($className)) { |
| 675 | continue; |
| 676 | } |
| 677 | |
| 678 | // Create temporary instance to check conditions |
| 679 | $tempEvent = new $className($this); |
| 680 | |
| 681 | // Check if it's an end-of-month event |
| 682 | if (!$tempEvent->isEndOfMonth()) { |
| 683 | continue; |
| 684 | } |
| 685 | |
| 686 | // Check if event is available |
| 687 | if (!$tempEvent->isAvailable()) { |
| 688 | continue; |
| 689 | } |
| 690 | |
| 691 | // Check if tribe has enough eligible kobolds |
| 692 | $minAge = $tempEvent->getMinAge(); |
| 693 | $minParticipants = $tempEvent->getMinParticipants(); |
| 694 | |
| 695 | $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) { |
| 696 | return $kobold->getAge() >= $minAge; |
| 697 | }); |
| 698 | |
| 699 | if (count($eligibleKobolds) < $minParticipants) { |
| 700 | continue; |
| 701 | } |
| 702 | |
| 703 | // This event is available |
| 704 | $availableEventClasses[] = $className; |
| 705 | } |
| 706 | |
| 707 | // If no events available, return empty array |
| 708 | if (empty($availableEventClasses)) { |
| 709 | return []; |
| 710 | } |
| 711 | |
| 712 | // Select events randomly until cost exceeds maxCost |
| 713 | while ($totalCost <= $maxCost && !empty($availableEventClasses)) { |
| 714 | // Pick a random event class |
| 715 | $randomClass = $availableEventClasses[array_rand($availableEventClasses)]; |
| 716 | |
| 717 | // Create new instance |
| 718 | $event = new $randomClass($this); |
| 719 | $eventCost = $event->getCost(); |
| 720 | |
| 721 | // Add to selection |
| 722 | $selectedEvents[] = $event; |
| 723 | $totalCost += $eventCost; |
| 724 | } |
| 725 | |
| 726 | return $selectedEvents; |
| 727 | } |
| 728 | |
| 729 | public function endMonth() |
| 730 | { |
| 731 | $this->currentMonth++; |
| 732 | |
| 733 | foreach ($this->kobolds as $kobold) { |
| 734 | $kobold->resetFatigue(); |
| 735 | } |
| 736 | |
| 737 | $seasons = ['spring', 'summer', 'autumn', 'winter']; |
| 738 | |
| 739 | $monthOfYear = (($this->currentMonth - 1) % 12) + 1; |
| 740 | $index = intdiv($monthOfYear - 1, 3); |
| 741 | $pIndex = ($index + 3) % 4; |
| 742 | |
| 743 | $previousSeason = $seasons[$pIndex]; |
| 744 | $this->currentSeason = $seasons[$index]; |
| 745 | |
| 746 | if ($previousSeason == 'spring' && $this->currentSeason == 'summer') { |
| 747 | if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) { |
| 748 | $noHarvestVariations = [ |
| 749 | "No seeds were sown in spring, so there can be no harvest come autumn.\n", |
| 750 | "With spring left untilled, there can be no harvest in autumn.\n", |
| 751 | "Spring passed without sowing; there can be no harvest this autumn.\n", |
| 752 | "The tribe never sowed in spring, so there can be no harvest later.\n", |
| 753 | "Nothing was planted in spring—there can be no harvest in autumn.\n", |
| 754 | "Spring's fields lay empty, and there can be no harvest ahead.\n", |
| 755 | "No planting happened in spring, so there can be no harvest when autumn arrives.\n" |
| 756 | ]; |
| 757 | $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)]; |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | if ( |
| 762 | isset($this->dataStore->wasSowedInSpring) |
| 763 | && $this->dataStore->wasSowedInSpring |
| 764 | && $previousSeason == 'summer' |
| 765 | && $this->currentSeason == 'autumn' |
| 766 | ) { |
| 767 | if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever |
| 768 | $cropLossVariations = [ |
| 769 | "The fields were not tended in summer, and all of the crops are lost.\n", |
| 770 | "Neglected through summer, all of the crops are lost.\n", |
| 771 | "With no summer care, all of the crops are lost to blight and pests.\n", |
| 772 | "Summer passed without tending the fields, and all of the crops are lost.\n", |
| 773 | "The fields were left to wild growth; all of the crops are lost.\n", |
| 774 | "No hands worked the fields in summer, so all of the crops are lost.\n", |
| 775 | "Left untended through summer, all of the crops are lost.\n" |
| 776 | ]; |
| 777 | $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | if ( |
| 782 | isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened |
| 783 | && $this->dataStore->wasTendedInSummer |
| 784 | && $previousSeason == 'summer' |
| 785 | && $this->currentSeason == 'autumn' |
| 786 | ) { |
| 787 | $cropLossVariations = [ |
| 788 | "The crops stood too long, and winter's cold ruined what should have been gathered.\n", |
| 789 | "Harvest came too late; the first hard freezes destroyed the crops.\n", |
| 790 | "No harvest was taken in time, and the winter cold ruined the fields.\n", |
| 791 | "The fields were left unharvested, and winter's chill destroyed the crops.\n", |
| 792 | "The tribe missed the harvest window, and the cold of winter claimed the crops.\n", |
| 793 | "By the time harvest was attempted, winter had already destroyed the crops.\n", |
| 794 | "The crops were left in the fields until winter, and the cold destroyed them.\n" |
| 795 | ]; |
| 796 | $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; |
| 797 | } |
| 798 | |
| 799 | // Execute end-of-month events |
| 800 | $monthEventStory = ''; |
| 801 | $endOfMonthEvents = $this->getEndOfMonthEvents(); |
| 802 | |
| 803 | foreach ($endOfMonthEvents as $event) { |
| 804 | // Select eligible participants |
| 805 | $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) { |
| 806 | return $kobold->getAge() >= $event->getMinAge(); |
| 807 | }); |
| 808 | |
| 809 | if (count($eligible) < $event->getMinParticipants()) { |
| 810 | continue; |
| 811 | } |
| 812 | |
| 813 | // Randomly select participants (between min and max) |
| 814 | $eligible = array_values($eligible); |
| 815 | shuffle($eligible); |
| 816 | $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible))); |
| 817 | $participants = array_slice($eligible, 0, $participantCount); |
| 818 | $participantIds = array_map(fn($k) => $k->getId(), $participants); |
| 819 | |
| 820 | // Set participants and execute event |
| 821 | $event->setParticipants($participantIds); |
| 822 | $event->execute(); |
| 823 | |
| 824 | // Add fatigue to participants |
| 825 | foreach ($participants as $participant) { |
| 826 | $participant->addFatigue($event->getCost()); |
| 827 | if ($participant->isDead()) { |
| 828 | $monthEventStory .= $participant->getName() . " has died.\n"; |
| 829 | } |
| 830 | $participant->save(); |
| 831 | } |
| 832 | |
| 833 | // Add event story |
| 834 | if ($event->getStory()) { |
| 835 | $monthEventStory .= $event->getStory() . "\n"; |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | // After events, consume food |
| 840 | |
| 841 | // age eggs |
| 842 | $foodStory = "A month passes...\n" . $this->consumeFood(); |
| 843 | if ($monthEventStory) { |
| 844 | $foodStory = $monthEventStory . "\n" . $foodStory; |
| 845 | } |
| 846 | $foodStory .= "\n"; |
| 847 | |
| 848 | foreach ($this->kobolds as $kobold) { |
| 849 | if ($kobold->getAge() < 0) { |
| 850 | $kobold->incrementAge(); |
| 851 | |
| 852 | if ($kobold->getAge() >= 0) { |
| 853 | $kobold->setName(Kobold::generateRandomName()); |
| 854 | $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n"; |
| 855 | } |
| 856 | |
| 857 | $kobold->save(); |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | // Age all kobolds |
| 862 | if ($this->currentMonth % 12 === 0) { |
| 863 | $foodStory .= "\nA new year begins.\n"; |
| 864 | |
| 865 | foreach ($this->kobolds as $kobold) { |
| 866 | $foodStory .= $this->ageKobold($kobold); |
| 867 | } |
| 868 | |
| 869 | foreach ($this->rivals as $kobold) { |
| 870 | $this->ageKobold($kobold); //we don't log these |
| 871 | } |
| 872 | } |
| 873 | $foodStory .= "\n" . $this->tryMate(); |
| 874 | $foodStory .= "\nIt's {$this->currentSeason}.\n"; |
| 875 | |
| 876 | foreach ($this->kobolds as $kobold) { |
| 877 | if ($kobold->isDead()) { |
| 878 | $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried."; |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | $this->save(); |
| 883 | |
| 884 | return $foodStory; |
| 885 | } |
| 886 | |
| 887 | function ageKobold($kobold) |
| 888 | { |
| 889 | $foodStory = ""; |
| 890 | if ($kobold->getAge() >= 0) { |
| 891 | $kobold->incrementAge(); |
| 892 | |
| 893 | // Check for old-age injuries |
| 894 | if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) { |
| 895 | $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue']; |
| 896 | $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)]; |
| 897 | $kobold->addInjury($injury); |
| 898 | } |
| 899 | |
| 900 | // Old-age death roll: if roll < (age + total injury severity), kobold dies |
| 901 | if ($kobold->getAge() >= 35) { |
| 902 | $roll = rand(1, 100); |
| 903 | $totalSeverity = $kobold->getTotalInjurySeverity(); |
| 904 | if ($roll < ($kobold->getAge() + $totalSeverity)) { |
| 905 | $foodStory .= $kobold->getName() . " dies of old age.\n"; |
| 906 | $kobold->die(); |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | $kobold->save(); |
| 911 | } |
| 912 | return $foodStory; |
| 913 | } |
| 914 | |
| 915 | private function shouldAddOldAgeInjury(Kobold $kobold) |
| 916 | { |
| 917 | // 1d100 roll under age starting at 35 |
| 918 | $roll = rand(1, 100); |
| 919 | return $roll <= $kobold->getAge(); |
| 920 | } |
| 921 | } |