BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

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