BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

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