BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

attempt at relationships tab
timfa Tim Falken · pushed by timfa · 9 months ago
960ca7e4 History
Tribe.php 31.5 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 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 $this->cleanupDeadKoboldLikes($kobold->getId());
438 $kobold->die();
439 $story .= "{$kobold->getName()} succumbed to starvation.\n";
440 }
441 }
442 }
443 }
444
445 // Save updated kobolds
446 foreach ($aliveKobolds as $kobold) {
447 $kobold->save();
448 }
449
450 return $story;
451 }
452
453 /**
454 * Check if a kobold has an injury in a specific category
455 */
456 private function hasInjuryCategory(Kobold $kobold, $category)
457 {
458 $injuries = $kobold->getInjuries();
459 foreach ($injuries as $injury) {
460 if ($injury['category'] === $category) {
461 return true;
462 }
463 }
464 return false;
465 }
466
467 /**
468 * Remove all malnourished injuries from a kobold
469 */
470 private function removeMalnourishedInjury(Kobold $kobold)
471 {
472 $injuries = $kobold->getInjuries();
473 foreach ($injuries as $injury) {
474 if ($injury['category'] === 'malnourished') {
475 $kobold->removeInjury($injury['id']);
476 }
477 }
478 }
479
480 /**
481 * Get current malnourished injury id if present
482 */
483 private function getMalnourishedInjuryId(Kobold $kobold)
484 {
485 $injuries = $kobold->getInjuries();
486 foreach ($injuries as $injury) {
487 if (($injury['category'] ?? null) === 'malnourished') {
488 return $injury['id'] ?? null;
489 }
490 }
491 return null;
492 }
493
494 public function tryMate()
495 {
496 $kobolds = array_values($this->getKobolds());
497 $count = count($kobolds);
498
499 if ($count === 0) {
500 return '';
501 }
502
503 $roll = rand(1, 30);
504 if ($roll <= $count) {
505 return '';
506 }
507
508 $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
509 $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));
510
511 if (empty($males) || empty($females)) {
512 return '';
513 }
514
515 $pair = null;
516 $attempts = 20;
517 while ($attempts-- > 0) {
518 $male = $males[array_rand($males)];
519 $female = $females[array_rand($females)];
520
521 $maleParents = $male->getParents();
522 $femaleParents = $female->getParents();
523
524 $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
525 $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
526 $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
527 $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);
528
529 if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
530 continue;
531 }
532
533 $pair = [$male, $female];
534 break;
535 }
536
537 if (!$pair) {
538 return '';
539 }
540
541 [$male, $female] = $pair;
542
543 if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) {
544 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
545 }
546
547 $child = Kobold::generate($this->userId, $this->saveId, -6);
548
549 if (!isset($child->dataStore)) {
550 $child->dataStore = new stdClass();
551 }
552 if (!isset($child->dataStore->likes)) {
553 $child->dataStore->likes = [];
554 }
555
556 // Child likes parents by default
557 $child->dataStore->likes[$male->getId()] = 10;
558 $child->dataStore->likes[$female->getId()] = 10;
559
560 // Initialize parents' dataStore if needed
561 if (!isset($male->dataStore)) {
562 $male->dataStore = new stdClass();
563 }
564 if (!isset($male->dataStore->likes)) {
565 $male->dataStore->likes = [];
566 }
567
568 if (!isset($female->dataStore)) {
569 $female->dataStore = new stdClass();
570 }
571 if (!isset($female->dataStore->likes)) {
572 $female->dataStore->likes = [];
573 }
574
575 // Parents like the child by default
576 $male->dataStore->likes[$child->getId()] = 20;
577 $female->dataStore->likes[$child->getId()] = 20;
578
579 $inheritRoll = rand(1, 100);
580 if ($inheritRoll <= 40) {
581 $child->setSpriteMorph($male->getSpriteMorph());
582 } elseif ($inheritRoll <= 80) {
583 $child->setSpriteMorph($female->getSpriteMorph());
584 }
585
586 $blendHex = function ($a, $b) {
587 $hexToRgb = function ($hex) {
588 $hex = ltrim($hex, '#');
589 return [
590 'r' => hexdec(substr($hex, 0, 2)),
591 'g' => hexdec(substr($hex, 2, 2)),
592 'b' => hexdec(substr($hex, 4, 2))
593 ];
594 };
595
596 $rgbToHex = function ($rgb) {
597 return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
598 };
599
600 $ra = $hexToRgb($a);
601 $rb = $hexToRgb($b);
602 $ratio = rand(0, 100) / 100;
603
604 $offset = function () {
605 return rand(-20, 20);
606 };
607
608 $mix = function ($c1, $c2) use ($ratio, $offset) {
609 $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
610 return max(0, min(255, $val));
611 };
612
613 $mixed = [
614 'r' => $mix($ra['r'], $rb['r']),
615 'g' => $mix($ra['g'], $rb['g']),
616 'b' => $mix($ra['b'], $rb['b'])
617 ];
618
619 return $rgbToHex($mixed);
620 };
621
622 $maleColours = $male->getColours();
623 $femaleColours = $female->getColours();
624
625 $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
626 $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
627 $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);
628
629 $child->setColours($childPrimary, $childSecondary, $childTertiary);
630 $child->setParents($male->getId(), $female->getId());
631 $child->regenerateSprite();
632
633 $this->addKobold($child);
634
635 $pairName = $female->getName() . " and " . $male->getName();
636 $momName = $female->getName();
637 $variations = [
638 "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
639 "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
640 "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
641 "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
642 "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
643 "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
644 "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
645 "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
646 "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
647 "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
648 ];
649
650 return $variations[array_rand($variations)];
651 }
652
653 public function getEndOfMonthEvents(): array
654 {
655 $maxCost = 500;
656 $selectedEvents = [];
657 $totalCost = 0;
658
659 // Scan src/Events directory for event classes
660 $eventsDir = __DIR__ . '/../../src/Events/';
661 $eventFiles = glob($eventsDir . '*.php');
662 $availableEventClasses = [];
663
664 foreach ($eventFiles as $file) {
665 $className = basename($file, '.php');
666
667 // Skip base classes
668 if ($className === 'Event' || $className === 'MonthEndEvent') {
669 continue;
670 }
671
672 require_once $file;
673
674 // Check if class exists and extends MonthEndEvent
675 if (!class_exists($className)) {
676 continue;
677 }
678
679 // Create temporary instance to check conditions
680 $tempEvent = new $className($this);
681
682 // Check if it's an end-of-month event
683 if (!$tempEvent->isEndOfMonth()) {
684 continue;
685 }
686
687 // Check if event is available
688 if (!$tempEvent->isAvailable()) {
689 continue;
690 }
691
692 // Check if tribe has enough eligible kobolds
693 $minAge = $tempEvent->getMinAge();
694 $minParticipants = $tempEvent->getMinParticipants();
695
696 $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) {
697 return $kobold->getAge() >= $minAge;
698 });
699
700 if (count($eligibleKobolds) < $minParticipants) {
701 continue;
702 }
703
704 // This event is available
705 $availableEventClasses[] = $className;
706 }
707
708 // If no events available, return empty array
709 if (empty($availableEventClasses)) {
710 return [];
711 }
712
713 // Select events randomly until cost exceeds maxCost
714 while ($totalCost <= $maxCost && !empty($availableEventClasses)) {
715 // Pick a random event class
716 $randomClass = $availableEventClasses[array_rand($availableEventClasses)];
717
718 // Create new instance
719 $event = new $randomClass($this);
720 $eventCost = $event->getCost();
721
722 // Add to selection
723 $selectedEvents[] = $event;
724 $totalCost += $eventCost;
725 }
726
727 return $selectedEvents;
728 }
729
730 public function endMonth()
731 {
732 $this->currentMonth++;
733
734 foreach ($this->kobolds as $kobold) {
735 $kobold->resetFatigue();
736 }
737
738 $seasons = ['spring', 'summer', 'autumn', 'winter'];
739
740 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
741 $index = intdiv($monthOfYear - 1, 3);
742 $pIndex = ($index + 3) % 4;
743
744 $previousSeason = $seasons[$pIndex];
745 $this->currentSeason = $seasons[$index];
746
747 if ($previousSeason == 'spring' && $this->currentSeason == 'summer') {
748 if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) {
749 $noHarvestVariations = [
750 "No seeds were sown in spring, so there can be no harvest come autumn.\n",
751 "With spring left untilled, there can be no harvest in autumn.\n",
752 "Spring passed without sowing; there can be no harvest this autumn.\n",
753 "The tribe never sowed in spring, so there can be no harvest later.\n",
754 "Nothing was planted in spring—there can be no harvest in autumn.\n",
755 "Spring's fields lay empty, and there can be no harvest ahead.\n",
756 "No planting happened in spring, so there can be no harvest when autumn arrives.\n"
757 ];
758 $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)];
759 }
760 }
761
762 if (
763 isset($this->dataStore->wasSowedInSpring)
764 && $this->dataStore->wasSowedInSpring
765 && $previousSeason == 'summer'
766 && $this->currentSeason == 'autumn'
767 ) {
768 if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever
769 $cropLossVariations = [
770 "The fields were not tended in summer, and all of the crops are lost.\n",
771 "Neglected through summer, all of the crops are lost.\n",
772 "With no summer care, all of the crops are lost to blight and pests.\n",
773 "Summer passed without tending the fields, and all of the crops are lost.\n",
774 "The fields were left to wild growth; all of the crops are lost.\n",
775 "No hands worked the fields in summer, so all of the crops are lost.\n",
776 "Left untended through summer, all of the crops are lost.\n"
777 ];
778 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
779 }
780 }
781
782 if (
783 isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened
784 && $this->dataStore->wasTendedInSummer
785 && $previousSeason == 'summer'
786 && $this->currentSeason == 'autumn'
787 ) {
788 $cropLossVariations = [
789 "The crops stood too long, and winter's cold ruined what should have been gathered.\n",
790 "Harvest came too late; the first hard freezes destroyed the crops.\n",
791 "No harvest was taken in time, and the winter cold ruined the fields.\n",
792 "The fields were left unharvested, and winter's chill destroyed the crops.\n",
793 "The tribe missed the harvest window, and the cold of winter claimed the crops.\n",
794 "By the time harvest was attempted, winter had already destroyed the crops.\n",
795 "The crops were left in the fields until winter, and the cold destroyed them.\n"
796 ];
797 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
798 }
799
800 // Execute end-of-month events
801 $monthEventStory = '';
802 $endOfMonthEvents = $this->getEndOfMonthEvents();
803
804 foreach ($endOfMonthEvents as $event) {
805 // Select eligible participants
806 $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) {
807 return $kobold->getAge() >= $event->getMinAge();
808 });
809
810 if (count($eligible) < $event->getMinParticipants()) {
811 continue;
812 }
813
814 // Randomly select participants (between min and max)
815 $eligible = array_values($eligible);
816 shuffle($eligible);
817 $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible)));
818 $participants = array_slice($eligible, 0, $participantCount);
819 $participantIds = array_map(fn($k) => $k->getId(), $participants);
820
821 // Set participants and execute event
822 $event->setParticipants($participantIds);
823 $event->execute();
824
825 // Add fatigue to participants
826 foreach ($participants as $participant) {
827 $participant->addFatigue($event->getCost());
828 if ($participant->isDead()) {
829 $monthEventStory .= $participant->getName() . " has died.\n";
830 }
831 $participant->save();
832 }
833
834 // Add event story
835 if ($event->getStory()) {
836 $monthEventStory .= $event->getStory() . "\n";
837 }
838 }
839
840 // After events, consume food
841
842 // age eggs
843 $foodStory = "A month passes...\n" . $this->consumeFood();
844 if ($monthEventStory) {
845 $foodStory = $monthEventStory . "\n" . $foodStory;
846 }
847 $foodStory .= "\n";
848
849 foreach ($this->kobolds as $kobold) {
850 if ($kobold->getAge() < 0) {
851 $kobold->incrementAge();
852
853 if ($kobold->getAge() >= 0) {
854 $kobold->setName(Kobold::generateRandomName());
855 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
856 }
857
858 $kobold->save();
859 }
860 }
861
862 // Age all kobolds
863 if ($this->currentMonth % 12 === 0) {
864 $foodStory .= "\nA new year begins.\n";
865
866 foreach ($this->kobolds as $kobold) {
867 $foodStory .= $this->ageKobold($kobold);
868 }
869
870 foreach ($this->rivals as $kobold) {
871 $this->ageKobold($kobold); //we don't log these
872 }
873 }
874 $foodStory .= "\n" . $this->tryMate();
875 $foodStory .= "\nIt's {$this->currentSeason}.\n";
876
877 foreach ($this->kobolds as $kobold) {
878 if ($kobold->isDead()) {
879 $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried.";
880 }
881 }
882
883 $this->save();
884
885 return $foodStory;
886 }
887
888 function ageKobold($kobold)
889 {
890 $foodStory = "";
891 if ($kobold->getAge() >= 0) {
892 $kobold->incrementAge();
893
894 // Check for old-age injuries
895 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
896 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
897 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
898 $kobold->addInjury($injury);
899 }
900
901 // Old-age death roll: if roll < (age + total injury severity), kobold dies
902 if ($kobold->getAge() >= 35) {
903 $roll = rand(1, 100);
904 $totalSeverity = $kobold->getTotalInjurySeverity();
905 if ($roll < ($kobold->getAge() + $totalSeverity)) {
906 $foodStory .= $kobold->getName() . " dies of old age.\n";
907 $this->cleanupDeadKoboldLikes($kobold->getId());
908 $kobold->die();
909 }
910 }
911
912 $kobold->save();
913 }
914 return $foodStory;
915 }
916
917 private function shouldAddOldAgeInjury(Kobold $kobold)
918 {
919 // 1d100 roll under age starting at 35
920 $roll = rand(1, 100);
921 return $roll <= $kobold->getAge();
922 }
923
924 /**
925 * Clean up all likes references to a kobold when they die
926 * Removes the kobold's ID from all other kobolds' likes arrays
927 * and from rival records
928 */
929 private function cleanupDeadKoboldLikes($koboldId)
930 {
931 // Remove from all other kobolds' likes
932 foreach ($this->kobolds as $other) {
933 if ($other->getId() !== $koboldId) {
934 if (!isset($other->dataStore)) {
935 $other->dataStore = new stdClass();
936 }
937 if (!isset($other->dataStore->likes)) {
938 $other->dataStore->likes = [];
939 }
940
941 // Remove the dead kobold from this kobold's likes
942 if (is_array($other->dataStore->likes)) {
943 unset($other->dataStore->likes[$koboldId]);
944 }
945 }
946 }
947
948 // Remove from rivals' likes if they exist
949 if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) {
950 foreach ($this->dataStore->rivals as &$rival) {
951 if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) {
952 unset($rival['data']['likes'][$koboldId]);
953 }
954 }
955 }
956 }
957}