BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

basic elect leader
timfa Tim Falken · pushed by timfa · 9 months ago
a2efb08a History
Tribe.php 37.3 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 foreach ($this->kobolds as $kobold) {
833 $kobold->resetFatigue();
834 }
835
836 $seasons = ['spring', 'summer', 'autumn', 'winter'];
837
838 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
839 $index = intdiv($monthOfYear - 1, 3);
840 $pIndex = ($index + 3) % 4;
841
842 $previousSeason = $seasons[$pIndex];
843 $this->currentSeason = $seasons[$index];
844
845 if ($previousSeason == 'spring' && $this->currentSeason == 'summer') {
846 if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) {
847 $noHarvestVariations = [
848 "No seeds were sown in spring, so there can be no harvest come autumn.\n",
849 "With spring left untilled, there can be no harvest in autumn.\n",
850 "Spring passed without sowing; there can be no harvest this autumn.\n",
851 "The tribe never sowed in spring, so there can be no harvest later.\n",
852 "Nothing was planted in spring—there can be no harvest in autumn.\n",
853 "Spring's fields lay empty, and there can be no harvest ahead.\n",
854 "No planting happened in spring, so there can be no harvest when autumn arrives.\n"
855 ];
856 $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)];
857 }
858 }
859
860 if (
861 isset($this->dataStore->wasSowedInSpring)
862 && $this->dataStore->wasSowedInSpring
863 && $previousSeason == 'summer'
864 && $this->currentSeason == 'autumn'
865 ) {
866 if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever
867 $cropLossVariations = [
868 "The fields were not tended in summer, and all of the crops are lost.\n",
869 "Neglected through summer, all of the crops are lost.\n",
870 "With no summer care, all of the crops are lost to blight and pests.\n",
871 "Summer passed without tending the fields, and all of the crops are lost.\n",
872 "The fields were left to wild growth; all of the crops are lost.\n",
873 "No hands worked the fields in summer, so all of the crops are lost.\n",
874 "Left untended through summer, all of the crops are lost.\n"
875 ];
876 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
877 }
878 }
879
880 if (
881 isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened
882 && $this->dataStore->wasTendedInSummer
883 && $previousSeason == 'summer'
884 && $this->currentSeason == 'autumn'
885 ) {
886 $cropLossVariations = [
887 "The crops stood too long, and winter's cold ruined what should have been gathered.\n",
888 "Harvest came too late; the first hard freezes destroyed the crops.\n",
889 "No harvest was taken in time, and the winter cold ruined the fields.\n",
890 "The fields were left unharvested, and winter's chill destroyed the crops.\n",
891 "The tribe missed the harvest window, and the cold of winter claimed the crops.\n",
892 "By the time harvest was attempted, winter had already destroyed the crops.\n",
893 "The crops were left in the fields until winter, and the cold destroyed them.\n"
894 ];
895 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
896 }
897
898 // Execute end-of-month events
899 $monthEventStory = '';
900 $endOfMonthEvents = $this->getEndOfMonthEvents();
901
902 foreach ($endOfMonthEvents as $event) {
903 // Select eligible participants
904 $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) {
905 return $kobold->getAge() >= $event->getMinAge();
906 });
907
908 if (count($eligible) < $event->getMinParticipants()) {
909 continue;
910 }
911
912 // Randomly select participants (between min and max)
913 $eligible = array_values($eligible);
914 shuffle($eligible);
915 $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible)));
916 $participants = array_slice($eligible, 0, $participantCount);
917 $participantIds = array_map(fn($k) => $k->getId(), $participants);
918
919 // Set participants and execute event
920 $event->setParticipants($participantIds);
921 $event->execute();
922
923 // Add fatigue to participants
924 foreach ($participants as $participant) {
925 $participant->addFatigue($event->getCost());
926 if ($participant->isDead()) {
927 $monthEventStory .= $participant->getName() . " has died.\n";
928 }
929 $participant->save();
930 }
931
932 // Add event story
933 if ($event->getStory()) {
934 $monthEventStory .= $event->getStory() . "\n";
935 }
936 }
937
938 // After events, consume food
939
940 // age eggs
941 $foodStory = "A month passes...\n" . $this->consumeFood();
942 if ($monthEventStory) {
943 $foodStory = $monthEventStory . "\n" . $foodStory;
944 }
945
946 foreach ($this->kobolds as $kobold) {
947 if ($kobold->getAge() < 0) {
948 $kobold->incrementAge();
949
950 if ($kobold->getAge() >= 0) {
951 $kobold->setName(Kobold::generateRandomName());
952 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
953 }
954
955 $kobold->save();
956 }
957 }
958
959 // Age all kobolds
960 if ($this->currentMonth % 12 === 0) {
961 $foodStory .= "A new year begins.\n";
962
963 foreach ($this->kobolds as $kobold) {
964 $foodStory .= $this->ageKobold($kobold);
965 }
966
967 foreach ($this->rivals as $kobold) {
968 $this->ageKobold($kobold); //we don't log these
969 }
970 }
971 $foodStory .= "\n" . $this->tryMate();
972 $foodStory .= "\nIt's {$this->currentSeason}.\n";
973
974 foreach ($this->kobolds as $kobold) {
975 if ($kobold->isDead()) {
976 $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried.";
977 }
978 }
979
980 $hasLeader = false;
981 foreach ($this->getKobolds() as $kobold) {
982 if ($kobold->isLeader()) {
983 $hasLeader = true;
984 break;
985 }
986 }
987
988 if (!$hasLeader) {
989 $adultCandidates = array_filter($this->getKobolds(), function ($kobold) {
990 return $kobold->getAgeCategory() === 'adult';
991 });
992
993 if (!empty($adultCandidates)) {
994 usort($adultCandidates, function ($a, $b) {
995 return $b->getAge() <=> $a->getAge();
996 });
997
998 $newLeader = $adultCandidates[0];
999 $newLeader->setLeader();
1000
1001 $leaderName = $newLeader->getName();
1002 $leaderStories = [
1003 "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.",
1004 "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.",
1005 "Without a chieftain, the camp felt adrift. The oldest adults met in counsel and agreed that {$leaderName} should lead. The tribe marked the choice with a solemn vow and returned to their work with purpose.",
1006 "A leaderless tribe called for order, so the elders gathered the adults 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.",
1007 "As the month closed, the tribe turned to its oldest adults for direction. The council placed the burden of leadership on {$leaderName}. The camp steadied as the new chieftain promised to protect the tribe.",
1008 "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.",
1009 "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.",
1010 "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.",
1011 "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.",
1012 "Leadership was needed, and the tribe did not delay. The oldest adults 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."
1013 ];
1014
1015 $foodStory .= "\n" . $leaderStories[array_rand($leaderStories)] . "\n";
1016 }
1017 }
1018
1019 $this->save();
1020
1021 return $foodStory;
1022 }
1023
1024 function ageKobold($kobold)
1025 {
1026 $foodStory = "";
1027 if ($kobold->getAge() >= 0) {
1028 $kobold->incrementAge();
1029
1030 // Check for old-age injuries
1031 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
1032 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
1033 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
1034 $kobold->addInjury($injury);
1035 }
1036
1037 // Old-age death roll: if roll < (age + total injury severity), kobold dies
1038 if ($kobold->getAge() >= 35) {
1039 $roll = rand(1, 100);
1040 $totalSeverity = $kobold->getTotalInjurySeverity();
1041 if ($roll < ($kobold->getAge() + $totalSeverity)) {
1042 $foodStory .= $kobold->getName() . " dies of old age.\n";
1043 $this->cleanupDeadKoboldLikes($kobold->getId());
1044 $kobold->die();
1045 }
1046 }
1047
1048 $kobold->save();
1049 }
1050 return $foodStory;
1051 }
1052
1053 private function shouldAddOldAgeInjury(Kobold $kobold)
1054 {
1055 // 1d100 roll under age starting at 35
1056 $roll = rand(1, 100);
1057 return $roll <= $kobold->getAge();
1058 }
1059
1060 /**
1061 * Clean up all likes references to a kobold when they die
1062 * Removes the kobold's ID from all other kobolds' likes arrays
1063 * and from rival records
1064 */
1065 private function cleanupDeadKoboldLikes($koboldId)
1066 {
1067 // Remove from all other kobolds' likes
1068 foreach ($this->kobolds as $other) {
1069 if ($other->getId() !== $koboldId) {
1070 if (!isset($other->dataStore)) {
1071 $other->dataStore = new stdClass();
1072 }
1073 if (!isset($other->dataStore->likes)) {
1074 $other->dataStore->likes = [];
1075 }
1076
1077 // Remove the dead kobold from this kobold's likes
1078 if (is_array($other->dataStore->likes)) {
1079 unset($other->dataStore->likes[$koboldId]);
1080 }
1081 }
1082 }
1083
1084 // Remove from rivals' likes if they exist
1085 if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) {
1086 foreach ($this->dataStore->rivals as &$rival) {
1087 if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) {
1088 unset($rival['data']['likes'][$koboldId]);
1089 }
1090 }
1091 }
1092 }
1093}