BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

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