BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

Tribe.php 40.7 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4require_once __DIR__ . '/../../src/Classes/Kobold.php';
5
6class 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 /**
400 * Calculate total food needed for all alive kobolds for one month
401 */
402 public function calculateFoodNeeded()
403 {
404 $needed = 0;
405
406 foreach ($this->getAliveKobolds() as $kobold) {
407 $ageCategory = $kobold->getAgeCategory();
408 $requirement = $this->foodRequirements[$ageCategory] ?? 1.0;
409 $needed += $requirement;
410 }
411
412 return $needed;
413 }
414
415 /**
416 * Calculate how many full months the current kobolds can be fed
417 * with the provided amount of food.
418 */
419 public function foodMonthsLeft($amount)
420 {
421 $foodPerMonth = $this->calculateFoodNeeded();
422 if ($foodPerMonth <= 0) {
423 return 0;
424 }
425
426 $available = max(0, (float) $amount);
427 return (int) floor($available / $foodPerMonth);
428 }
429
430 public function foodTimeStr($amount)
431 {
432 $months = $this->foodMonthsLeft($amount);
433 if ($months > 0) {
434 if ($months == 1)
435 return "1 month";
436 else
437 return "{$months} months";
438 }
439
440 $foodPerMonth = $this->calculateFoodNeeded();
441 if ($foodPerMonth <= 0) {
442 return "years";
443 }
444
445 $available = max(0, (float) $amount);
446 $days = (int) floor(($available / $foodPerMonth) * 30);
447 $weeks = intdiv($days, 7);
448
449 if ($weeks >= 1) {
450 return $weeks . " week" . ($weeks === 1 ? "" : "s");
451 }
452
453 return $days . " day" . ($days === 1 ? "" : "s");
454 }
455
456 /**
457 * Get food requirement for a specific kobold
458 */
459 public function getFoodRequirement(Kobold $kobold)
460 {
461 $ageCategory = $kobold->getAgeCategory();
462 return $this->foodRequirements[$ageCategory] ?? 1.0;
463 }
464
465 /**
466 * Consume food at end of month after events
467 * Prioritizes: malnourished kobolds first, then younger before older
468 * Returns story of food consumption and any starvations
469 */
470 public function consumeFood()
471 {
472 $story = "";
473 $aliveKobolds = $this->getAliveKobolds();
474
475 if (empty($aliveKobolds)) {
476 return $story;
477 }
478
479 // Sort kobolds: malnourished first, then by age (younger first)
480 usort($aliveKobolds, function ($a, $b) {
481 // Check for malnourished injury
482 $aMalnourished = $this->hasInjuryCategory($a, 'malnourished');
483 $bMalnourished = $this->hasInjuryCategory($b, 'malnourished');
484
485 if ($aMalnourished && !$bMalnourished)
486 return -1;
487 if (!$aMalnourished && $bMalnourished)
488 return 1;
489
490 // Both have or both don't have malnourished
491 // Younger first (lower age = higher priority)
492 return $a->getAge() - $b->getAge();
493 });
494
495 $fedKobolds = [];
496 $starvedKobolds = [];
497
498 foreach ($aliveKobolds as $kobold) {
499 $needed = $this->getFoodRequirement($kobold);
500
501 if ($this->foodCount >= $needed) {
502 // Fed this kobold
503 $this->foodCount -= $needed;
504 $fedKobolds[$kobold->getId()] = $kobold;
505
506 // If malnourished, cure it
507 if ($this->hasInjuryCategory($kobold, 'malnourished')) {
508 $this->removeMalnourishedInjury($kobold);
509 $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n";
510 }
511 } else {
512 // Not enough food - starve this kobold
513 $starvedKobolds[$kobold->getId()] = $kobold;
514 $this->foodCount = 0; // Use remaining food
515
516
517 $malnourishedId = $this->getMalnourishedInjuryId($kobold);
518 if (!$malnourishedId) {
519 $kobold->addInjury('malnourished-slight');
520 $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
521 } else {
522 if ($malnourishedId === 'malnourished-slight') {
523 $kobold->removeInjury($malnourishedId);
524 $kobold->addInjury('malnourished-mild');
525 $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
526 } elseif ($malnourishedId === 'malnourished-mild') {
527 $kobold->removeInjury($malnourishedId);
528 $kobold->addInjury('malnourished-severe');
529 $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
530 } elseif ($malnourishedId === 'malnourished-severe') {
531 $kobold->removeInjury($malnourishedId);
532 $kobold->addInjury('malnourished-brink');
533 $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
534 } elseif ($malnourishedId === 'malnourished-brink') {
535 $this->cleanupDeadKoboldLikes($kobold->getId());
536 $kobold->die();
537 $story .= "{$kobold->getName()} succumbed to starvation.\n";
538 }
539 }
540 }
541 }
542
543 // Save updated kobolds
544 foreach ($aliveKobolds as $kobold) {
545 $kobold->save();
546 }
547
548 return $story;
549 }
550
551 /**
552 * Check if a kobold has an injury in a specific category
553 */
554 private function hasInjuryCategory(Kobold $kobold, $category)
555 {
556 $injuries = $kobold->getInjuries();
557 foreach ($injuries as $injury) {
558 if ($injury['category'] === $category) {
559 return true;
560 }
561 }
562 return false;
563 }
564
565 /**
566 * Remove all malnourished injuries from a kobold
567 */
568 private function removeMalnourishedInjury(Kobold $kobold)
569 {
570 $injuries = $kobold->getInjuries();
571 foreach ($injuries as $injury) {
572 if ($injury['category'] === 'malnourished') {
573 $kobold->removeInjury($injury['id']);
574 }
575 }
576 }
577
578 /**
579 * Get current malnourished injury id if present
580 */
581 private function getMalnourishedInjuryId(Kobold $kobold)
582 {
583 $injuries = $kobold->getInjuries();
584 foreach ($injuries as $injury) {
585 if (($injury['category'] ?? null) === 'malnourished') {
586 return $injury['id'] ?? null;
587 }
588 }
589 return null;
590 }
591
592 public function tryMate()
593 {
594 $kobolds = array_values($this->getKobolds());
595 $count = count($kobolds);
596
597 if ($count === 0) {
598 return '';
599 }
600
601 $roll = rand(1, 30);
602 if ($roll <= $count) {
603 return '';
604 }
605
606 $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
607 $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));
608
609 if (empty($males) || empty($females)) {
610 return '';
611 }
612
613 $pair = null;
614 $attempts = 20;
615 while ($attempts-- > 0) {
616 $male = $males[array_rand($males)];
617 $female = $females[array_rand($females)];
618
619 $maleParents = $male->getParents();
620 $femaleParents = $female->getParents();
621
622 $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
623 $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
624 $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
625 $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);
626
627 if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
628 continue;
629 }
630
631 $pair = [$male, $female];
632 break;
633 }
634
635 if (!$pair) {
636 return '';
637 }
638
639 [$male, $female] = $pair;
640
641 if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) {
642 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
643 }
644
645 $child = Kobold::generate($this->userId, $this->saveId, -6);
646
647 if (!isset($child->dataStore)) {
648 $child->dataStore = new stdClass();
649 }
650 if (!isset($child->dataStore->likes)) {
651 $child->dataStore->likes = [];
652 }
653
654 // Child likes parents by default
655 $child->dataStore->likes[$male->getId()] = 10;
656 $child->dataStore->likes[$female->getId()] = 10;
657
658 // Initialize parents' dataStore if needed
659 if (!isset($male->dataStore)) {
660 $male->dataStore = new stdClass();
661 }
662 if (!isset($male->dataStore->likes)) {
663 $male->dataStore->likes = [];
664 }
665
666 if (!isset($female->dataStore)) {
667 $female->dataStore = new stdClass();
668 }
669 if (!isset($female->dataStore->likes)) {
670 $female->dataStore->likes = [];
671 }
672
673 // Parents like the child by default
674 $male->dataStore->likes[$child->getId()] = 20;
675 $female->dataStore->likes[$child->getId()] = 20;
676
677 $inheritRoll = rand(1, 100);
678 if ($inheritRoll <= 40) {
679 $child->setSpriteMorph($male->getSpriteMorph());
680 } elseif ($inheritRoll <= 80) {
681 $child->setSpriteMorph($female->getSpriteMorph());
682 }
683
684 $blendHex = function ($a, $b) {
685 $hexToRgb = function ($hex) {
686 $hex = ltrim($hex, '#');
687 return [
688 'r' => hexdec(substr($hex, 0, 2)),
689 'g' => hexdec(substr($hex, 2, 2)),
690 'b' => hexdec(substr($hex, 4, 2))
691 ];
692 };
693
694 $rgbToHex = function ($rgb) {
695 return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
696 };
697
698 $ra = $hexToRgb($a);
699 $rb = $hexToRgb($b);
700 $ratio = rand(0, 100) / 100;
701
702 $offset = function () {
703 return rand(-20, 20);
704 };
705
706 $mix = function ($c1, $c2) use ($ratio, $offset) {
707 $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
708 return max(0, min(255, $val));
709 };
710
711 $mixed = [
712 'r' => $mix($ra['r'], $rb['r']),
713 'g' => $mix($ra['g'], $rb['g']),
714 'b' => $mix($ra['b'], $rb['b'])
715 ];
716
717 return $rgbToHex($mixed);
718 };
719
720 $maleColours = $male->getColours();
721 $femaleColours = $female->getColours();
722
723 $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
724 $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
725 $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);
726
727 $child->setColours($childPrimary, $childSecondary, $childTertiary);
728 $child->setParents($male->getId(), $female->getId());
729 $child->regenerateSprite();
730
731 $this->addKobold($child);
732
733 $pairName = $female->getName() . " and " . $male->getName();
734 $momName = $female->getName();
735 $variations = [
736 "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
737 "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
738 "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
739 "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
740 "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
741 "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
742 "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
743 "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
744 "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
745 "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
746 ];
747
748 return $variations[array_rand($variations)];
749 }
750
751 public function getEndOfMonthEvents(): array
752 {
753 $maxCost = 250;
754 $selectedEvents = [];
755 $totalCost = 0;
756
757 // Scan src/Events directory for event classes
758 $eventsDir = __DIR__ . '/../../src/Events/';
759 $eventFiles = glob($eventsDir . '*.php');
760 $availableEventClasses = [];
761
762 foreach ($eventFiles as $file) {
763 $className = basename($file, '.php');
764
765 // Skip base classes
766 if ($className === 'Event' || $className === 'MonthEndEvent') {
767 continue;
768 }
769
770 require_once $file;
771
772 // Check if class exists and extends MonthEndEvent
773 if (!class_exists($className)) {
774 continue;
775 }
776
777 // Create temporary instance to check conditions
778 $tempEvent = new $className($this);
779
780 // Check if it's an end-of-month event
781 if (!$tempEvent->isEndOfMonth()) {
782 continue;
783 }
784
785 // Check if event is available
786 if (!$tempEvent->isAvailable()) {
787 continue;
788 }
789
790 // Check if tribe has enough eligible kobolds
791 $minAge = $tempEvent->getMinAge();
792 $minParticipants = $tempEvent->getMinParticipants();
793
794 $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) {
795 return $kobold->getAge() >= $minAge;
796 });
797
798 if (count($eligibleKobolds) < $minParticipants) {
799 continue;
800 }
801
802 // This event is available
803 $availableEventClasses[] = $className;
804 }
805
806 // If no events available, return empty array
807 if (empty($availableEventClasses)) {
808 return [];
809 }
810
811 // Select events randomly until cost exceeds maxCost
812 while ($totalCost <= $maxCost && !empty($availableEventClasses)) {
813 // Pick a random event class
814 $randomClass = $availableEventClasses[array_rand($availableEventClasses)];
815
816 // Create new instance
817 $event = new $randomClass($this);
818 $eventCost = $event->getCost();
819
820 // Add to selection
821 $selectedEvents[] = $event;
822 $totalCost += $eventCost;
823 }
824
825 return $selectedEvents;
826 }
827
828 public function endMonth()
829 {
830 $this->currentMonth++;
831
832 if (!isset($this->dataStore)) {
833 $this->dataStore = new stdClass();
834 }
835 $this->dataStore->heatWaveActive = false;
836 $this->dataStore->floodedThisMonth = false;
837 $this->dataStore->draught = false;
838
839 foreach ($this->kobolds as $kobold) {
840 $kobold->resetFatigue();
841 }
842
843 $seasons = ['spring', 'summer', 'autumn', 'winter'];
844
845 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
846 $index = intdiv($monthOfYear - 1, 3);
847 $pIndex = ($index + 3) % 4;
848
849 $previousSeason = $seasons[$pIndex];
850 $this->currentSeason = $seasons[$index];
851
852 if ($previousSeason == 'spring' && $this->currentSeason == 'summer') {
853 if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) {
854 $noHarvestVariations = [
855 "No seeds were sown in spring, so there can be no harvest come autumn.\n",
856 "With spring left untilled, there can be no harvest in autumn.\n",
857 "Spring passed without sowing; there can be no harvest this autumn.\n",
858 "The tribe never sowed in spring, so there can be no harvest later.\n",
859 "Nothing was planted in spring—there can be no harvest in autumn.\n",
860 "Spring's fields lay empty, and there can be no harvest ahead.\n",
861 "No planting happened in spring, so there can be no harvest when autumn arrives.\n"
862 ];
863 $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)];
864 }
865 }
866
867 if (
868 isset($this->dataStore->wasSowedInSpring)
869 && $this->dataStore->wasSowedInSpring
870 && $previousSeason == 'summer'
871 && $this->currentSeason == 'autumn'
872 ) {
873 if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever
874 $cropLossVariations = [
875 "The fields were not tended in summer, and all of the crops are lost.\n",
876 "Neglected through summer, all of the crops are lost.\n",
877 "With no summer care, all of the crops are lost to blight and pests.\n",
878 "Summer passed without tending the fields, and all of the crops are lost.\n",
879 "The fields were left to wild growth; all of the crops are lost.\n",
880 "No hands worked the fields in summer, so all of the crops are lost.\n",
881 "Left untended through summer, all of the crops are lost.\n"
882 ];
883 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
884 }
885 }
886
887 if (
888 isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened
889 && $this->dataStore->wasTendedInSummer
890 && $previousSeason == 'summer'
891 && $this->currentSeason == 'autumn'
892 ) {
893 $cropLossVariations = [
894 "The crops stood too long, and winter's cold ruined what should have been gathered.\n",
895 "Harvest came too late; the first hard freezes destroyed the crops.\n",
896 "No harvest was taken in time, and the winter cold ruined the fields.\n",
897 "The fields were left unharvested, and winter's chill destroyed the crops.\n",
898 "The tribe missed the harvest window, and the cold of winter claimed the crops.\n",
899 "By the time harvest was attempted, winter had already destroyed the crops.\n",
900 "The crops were left in the fields until winter, and the cold destroyed them.\n"
901 ];
902 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
903 }
904
905 // Execute end-of-month events
906 $monthEventStory = '';
907 $endOfMonthEvents = $this->getEndOfMonthEvents();
908
909 $hasFloodEvent = false;
910 $hasHeatWaveEvent = false;
911 foreach ($endOfMonthEvents as $event) {
912 $className = get_class($event);
913 if ($className === 'SmallFloodEvent' || $className === 'LargeFloodEvent') {
914 $hasFloodEvent = true;
915 }
916 if ($className === 'HeatWaveEvent') {
917 $hasHeatWaveEvent = true;
918 }
919 }
920
921 if ($hasHeatWaveEvent) {
922 $this->dataStore->heatWaveActive = true;
923 }
924
925 if ($hasFloodEvent) {
926 $this->dataStore->floodedThisMonth = true;
927 $endOfMonthEvents = array_values(array_filter($endOfMonthEvents, function ($event) {
928 return get_class($event) !== 'DroughtEvent';
929 }));
930 }
931
932 foreach ($endOfMonthEvents as $event) {
933 // Select eligible participants
934 $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) {
935 return $kobold->getAge() >= $event->getMinAge();
936 });
937
938 if (count($eligible) < $event->getMinParticipants()) {
939 continue;
940 }
941
942 // Randomly select participants (between min and max)
943 $eligible = array_values($eligible);
944 shuffle($eligible);
945 $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible)));
946 $participants = array_slice($eligible, 0, $participantCount);
947 $participantIds = array_map(fn($k) => $k->getId(), $participants);
948
949 // Set participants and execute event
950 $event->setParticipants($participantIds);
951 $event->execute();
952
953 // Add fatigue to participants
954 foreach ($participants as $participant) {
955 $participant->addFatigue($event->getCost());
956 if ($participant->isDead()) {
957 $monthEventStory .= $participant->getName() . " has died.\n";
958 }
959 $participant->save();
960 }
961
962 // Add event story
963 if ($event->getStory()) {
964 $monthEventStory .= $event->getStory() . "\n";
965 }
966 }
967
968 // After events, consume food
969
970 // age eggs
971 $foodStory = "A month passes...\n" . $this->consumeFood();
972 if ($monthEventStory) {
973 $foodStory = $monthEventStory . "\n" . $foodStory;
974 }
975
976 foreach ($this->kobolds as $kobold) {
977 if ($kobold->getAge() < 0) {
978 $kobold->incrementAge();
979
980 if ($kobold->getAge() >= 0) {
981 $kobold->setName(Kobold::generateRandomName());
982 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
983 }
984
985 $kobold->save();
986 }
987 }
988
989 // Age all kobolds
990 if ($this->currentMonth % 12 === 0) {
991 $foodStory .= "A new year begins.\n";
992
993 foreach ($this->kobolds as $kobold) {
994 $foodStory .= $this->ageKobold($kobold);
995 }
996
997 foreach ($this->rivals as $kobold) {
998 $this->ageKobold($kobold); //we don't log these
999 }
1000 }
1001 $foodStory .= "\n" . $this->tryMate();
1002 $foodStory .= "\nIt's {$this->currentSeason}.\n";
1003
1004 foreach ($this->kobolds as $kobold) {
1005 if ($kobold->isDead()) {
1006 $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried.";
1007 }
1008 }
1009
1010 $hasLeader = false;
1011 foreach ($this->getKobolds() as $kobold) {
1012 if ($kobold->isLeader()) {
1013 $hasLeader = true;
1014 break;
1015 }
1016 }
1017
1018 if (!$hasLeader) {
1019 $eligibleKobolds = array_filter($this->getKobolds(), function ($kobold) {
1020 return $kobold->getAgeCategory() !== 'egg';
1021 });
1022
1023 if (count($eligibleKobolds) >= 3) {
1024 $pickFromTier = function ($tier) {
1025 return array_values(array_filter($this->getKobolds(), function ($kobold) use ($tier) {
1026 return $kobold->getAgeCategory() === $tier;
1027 }));
1028 };
1029
1030 $candidatePools = [
1031 $pickFromTier('adult'),
1032 $pickFromTier('old'),
1033 $pickFromTier('young')
1034 ];
1035
1036 $candidates = [];
1037 foreach ($candidatePools as $pool) {
1038 if (!empty($pool)) {
1039 $candidates = $pool;
1040 break;
1041 }
1042 }
1043
1044 if (!empty($candidates)) {
1045 $scores = [];
1046 foreach ($candidates as $candidate) {
1047 $score = 0;
1048 foreach ($this->getKobolds() as $other) {
1049 if ($other->getId() === $candidate->getId()) {
1050 continue;
1051 }
1052
1053 $likes = 0;
1054 if (isset($other->dataStore) && $other->dataStore instanceof stdClass) {
1055 if (isset($other->dataStore->likes) && is_array($other->dataStore->likes)) {
1056 $likes = (int) ($other->dataStore->likes[$candidate->getId()] ?? 0);
1057 }
1058 }
1059 $score += $likes;
1060 }
1061 $scores[$candidate->getId()] = $score;
1062 }
1063
1064 $maxScore = max($scores);
1065 $topCandidates = array_values(array_filter($candidates, function ($candidate) use ($scores, $maxScore) {
1066 return $scores[$candidate->getId()] === $maxScore;
1067 }));
1068
1069 if (count($topCandidates) > 1) {
1070 usort($topCandidates, function ($a, $b) {
1071 return $b->getAge() <=> $a->getAge();
1072 });
1073
1074 $oldestAge = $topCandidates[0]->getAge();
1075 $topCandidates = array_values(array_filter($topCandidates, function ($candidate) use ($oldestAge) {
1076 return $candidate->getAge() === $oldestAge;
1077 }));
1078 }
1079
1080 $newLeader = $topCandidates[array_rand($topCandidates)];
1081 $newLeader->setLeader();
1082
1083 $leaderName = $newLeader->getName();
1084 $leaderStories = [
1085 "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.",
1086 "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.",
1087 "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.",
1088 "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.",
1089 "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.",
1090 "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.",
1091 "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.",
1092 "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.",
1093 "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.",
1094 "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."
1095 ];
1096
1097 $foodStory .= "\n" . $leaderStories[array_rand($leaderStories)] . "\n";
1098 }
1099 }
1100 }
1101
1102 $this->save();
1103
1104 return $foodStory;
1105 }
1106
1107 function ageKobold($kobold)
1108 {
1109 $foodStory = "";
1110 if ($kobold->getAge() >= 0) {
1111 $kobold->incrementAge();
1112
1113 // Check for old-age injuries
1114 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
1115 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
1116 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
1117 $kobold->addInjury($injury);
1118 }
1119
1120 // Old-age death roll: if roll < (age + total injury severity), kobold dies
1121 if ($kobold->getAge() >= 35) {
1122 $roll = rand(1, 100);
1123 $totalSeverity = $kobold->getTotalInjurySeverity();
1124 if ($roll < ($kobold->getAge() + $totalSeverity)) {
1125 $foodStory .= $kobold->getName() . " dies of old age.\n";
1126 $this->cleanupDeadKoboldLikes($kobold->getId());
1127 $kobold->die();
1128 }
1129 }
1130
1131 $kobold->save();
1132 }
1133 return $foodStory;
1134 }
1135
1136 private function shouldAddOldAgeInjury(Kobold $kobold)
1137 {
1138 // 1d100 roll under age starting at 35
1139 $roll = rand(1, 100);
1140 return $roll <= $kobold->getAge();
1141 }
1142
1143 /**
1144 * Clean up all likes references to a kobold when they die
1145 * Removes the kobold's ID from all other kobolds' likes arrays
1146 * and from rival records
1147 */
1148 private function cleanupDeadKoboldLikes($koboldId)
1149 {
1150 // Remove from all other kobolds' likes
1151 foreach ($this->kobolds as $other) {
1152 if ($other->getId() !== $koboldId) {
1153 if (!isset($other->dataStore)) {
1154 $other->dataStore = new stdClass();
1155 }
1156 if (!isset($other->dataStore->likes)) {
1157 $other->dataStore->likes = [];
1158 }
1159
1160 // Remove the dead kobold from this kobold's likes
1161 if (is_array($other->dataStore->likes)) {
1162 unset($other->dataStore->likes[$koboldId]);
1163 }
1164 }
1165 }
1166
1167 // Remove from rivals' likes if they exist
1168 if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) {
1169 foreach ($this->dataStore->rivals as &$rival) {
1170 if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) {
1171 unset($rival['data']['likes'][$koboldId]);
1172 }
1173 }
1174 }
1175 }
1176}