BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

upd
timfa Tim Falken · pushed by timfa · 9 months ago
3298ef22 History
Tribe.php 42.5 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4require_once __DIR__ . '/../../src/Classes/Kobold.php';
5
6class Tribe
7{
8 private $userId;
9 private $saveId;
10 private $name;
11 public $kobolds = [];
12 public $rivals = [];
13 private $storage = [];
14 private $currentMonth = 0;
15 private $currentSeason = 'spring';
16 private $foodCount = 0;
17 private $environmentId = null;
18 private $createdAt;
19 private $lastPlayed;
20 private $saveManager;
21 public $dataStore;
22
23 // Food requirement by age tier (portion units)
24 public $foodRequirements = [
25 'egg' => 0,
26 'baby' => 1,
27 'young' => 2,
28 'adult' => 3,
29 'old' => 2
30 ];
31
32 public function __construct($userId, $saveId, $name = '')
33 {
34 $this->userId = $userId;
35 $this->saveId = $saveId;
36 $this->name = $name;
37 $this->saveManager = new SaveManager();
38 $this->loadFromFile();
39 }
40
41 public static function create($userId, $saveName)
42 {
43 $saveManager = new SaveManager();
44 $saveId = $saveManager->generateSaveId($userId);
45
46 $tribe = new self($userId, $saveId, $saveName);
47 $tribe->createdAt = date('Y-m-d H:i:s');
48 $tribe->lastPlayed = date('Y-m-d H:i:s');
49 $tribe->save();
50
51 return $tribe;
52 }
53
54 public static function load($userId, $saveId)
55 {
56 return new self($userId, $saveId);
57 }
58
59 private function loadFromFile()
60 {
61 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
62 $saveFile = $savePath . '/save.json';
63
64 if (file_exists($saveFile)) {
65 $data = $this->saveManager->loadJson($saveFile);
66
67 if ($data) {
68 $this->name = $data['name'] ?? '';
69 $this->currentMonth = $data['current_month'] ?? 0;
70 $this->currentSeason = $data['current_season'] ?? 'spring';
71 $this->foodCount = $data['food_count'] ?? 0;
72 $this->environmentId = $data['environment_id'] ?? null;
73 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
74 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
75 $this->dataStore = $data['data_store'] ?? new stdClass();
76 }
77
78 if (is_array($this->dataStore)) {
79 $this->dataStore = (object) $this->dataStore;
80 }
81 }
82
83 $this->loadKobolds();
84 $this->loadStorage();
85 }
86
87 private function loadKobolds()
88 {
89 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
90 $koboldsFile = $savePath . '/kobolds.json';
91
92 $this->kobolds = [];
93
94 if (file_exists($koboldsFile)) {
95 $data = $this->saveManager->loadJson($koboldsFile);
96
97 if ($data && is_array($data)) {
98 foreach ($data as $koboldData) {
99 $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId);
100 if ($kobold) {
101 if ($kobold->isRival)
102 $this->rivals[$kobold->getId()] = $kobold;
103 else
104 $this->kobolds[$kobold->getId()] = $kobold;
105 }
106 }
107 }
108 }
109 }
110
111 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 if (!isset($this->dataStore)) {
833 $this->dataStore = new stdClass();
834 }
835 $this->dataStore->heatWaveActive = max(0, (int) ($this->dataStore->heatWaveActive ?? 0) - 1);
836 $this->dataStore->draught = max(0, (int) ($this->dataStore->draught ?? 0) - 1);
837 $this->dataStore->floodedThisMonth = false;
838
839 $ongoingWeatherStory = '';
840 if ($this->dataStore->draught > 0) {
841 $droughtLines = [
842 "The drought continues, and the land remains cracked and dry.\n",
843 "No rain comes yet; the drought persists across the camp.\n",
844 "The drought has not broken, and the tribe endures another dry month.\n"
845 ];
846 $ongoingWeatherStory .= $droughtLines[array_rand($droughtLines)];
847 }
848 if ($this->dataStore->heatWaveActive > 0) {
849 $heatLines = [
850 "The heat wave continues, and the camp moves slowly under the oppressive sun.\n",
851 "The heat wave has not faded; the tribe bears another sweltering month.\n",
852 "Relief does not come, and the heat wave presses on.\n"
853 ];
854 $ongoingWeatherStory .= $heatLines[array_rand($heatLines)];
855 }
856
857 if ($this->dataStore->draught <= 0) {
858 foreach ($this->getKobolds() as $kobold) {
859 $injuries = $kobold->getInjuries();
860 foreach ($injuries as $injury) {
861 if (($injury['id'] ?? null) === 'dehydrated') {
862 $kobold->removeInjury('dehydrated');
863 }
864 }
865 }
866 }
867
868 foreach ($this->getKobolds() as $kobold) {
869 $injuries = $kobold->getInjuries();
870 $hasHeatstroke = false;
871 foreach ($injuries as $injury) {
872 if (($injury['id'] ?? null) === 'heatstroke') {
873 $hasHeatstroke = true;
874 break;
875 }
876 }
877
878 if ($hasHeatstroke) {
879 $vitality = (int) ($kobold->getStat('vitality') ?? 0);
880 $baselineFatigue = (int) ceil($vitality * 0.75);
881 if ($this->dataStore->heatWaveActive <= 0 || $kobold->getFatigue() <= $baselineFatigue) {
882 $kobold->removeInjury('heatstroke');
883 }
884 }
885 }
886
887 foreach ($this->kobolds as $kobold) {
888 $kobold->resetFatigue();
889 }
890
891 $seasons = ['spring', 'summer', 'autumn', 'winter'];
892
893 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
894 $index = intdiv($monthOfYear - 1, 3);
895 $pIndex = ($index + 3) % 4;
896
897 $previousSeason = $seasons[$pIndex];
898 $this->currentSeason = $seasons[$index];
899
900 if ($previousSeason == 'spring' && $this->currentSeason == 'summer') {
901 if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) {
902 $noHarvestVariations = [
903 "No seeds were sown in spring, so there can be no harvest come autumn.\n",
904 "With spring left untilled, there can be no harvest in autumn.\n",
905 "Spring passed without sowing; there can be no harvest this autumn.\n",
906 "The tribe never sowed in spring, so there can be no harvest later.\n",
907 "Nothing was planted in spring—there can be no harvest in autumn.\n",
908 "Spring's fields lay empty, and there can be no harvest ahead.\n",
909 "No planting happened in spring, so there can be no harvest when autumn arrives.\n"
910 ];
911 $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)];
912 }
913 }
914
915 if (
916 isset($this->dataStore->wasSowedInSpring)
917 && $this->dataStore->wasSowedInSpring
918 && $previousSeason == 'summer'
919 && $this->currentSeason == 'autumn'
920 ) {
921 if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever
922 $cropLossVariations = [
923 "The fields were not tended in summer, and all of the crops are lost.\n",
924 "Neglected through summer, all of the crops are lost.\n",
925 "With no summer care, all of the crops are lost to blight and pests.\n",
926 "Summer passed without tending the fields, and all of the crops are lost.\n",
927 "The fields were left to wild growth; all of the crops are lost.\n",
928 "No hands worked the fields in summer, so all of the crops are lost.\n",
929 "Left untended through summer, all of the crops are lost.\n"
930 ];
931 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
932 }
933 }
934
935 if (
936 isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened
937 && $this->dataStore->wasTendedInSummer
938 && $previousSeason == 'summer'
939 && $this->currentSeason == 'autumn'
940 ) {
941 $cropLossVariations = [
942 "The crops stood too long, and winter's cold ruined what should have been gathered.\n",
943 "Harvest came too late; the first hard freezes destroyed the crops.\n",
944 "No harvest was taken in time, and the winter cold ruined the fields.\n",
945 "The fields were left unharvested, and winter's chill destroyed the crops.\n",
946 "The tribe missed the harvest window, and the cold of winter claimed the crops.\n",
947 "By the time harvest was attempted, winter had already destroyed the crops.\n",
948 "The crops were left in the fields until winter, and the cold destroyed them.\n"
949 ];
950 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
951 }
952
953 // Execute end-of-month events
954 $monthEventStory = $ongoingWeatherStory;
955 $endOfMonthEvents = $this->getEndOfMonthEvents();
956
957 $hasFloodEvent = false;
958 foreach ($endOfMonthEvents as $event) {
959 $className = get_class($event);
960 if ($className === 'SmallFloodEvent' || $className === 'LargeFloodEvent') {
961 $hasFloodEvent = true;
962 }
963 }
964
965 if ($hasFloodEvent) {
966 $this->dataStore->floodedThisMonth = true;
967 $endOfMonthEvents = array_values(array_filter($endOfMonthEvents, function ($event) {
968 return get_class($event) !== 'DroughtEvent';
969 }));
970 }
971
972 foreach ($endOfMonthEvents as $event) {
973 // Select eligible participants
974 $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) {
975 return $kobold->getAge() >= $event->getMinAge();
976 });
977
978 if (count($eligible) < $event->getMinParticipants()) {
979 continue;
980 }
981
982 // Randomly select participants (between min and max)
983 $eligible = array_values($eligible);
984 shuffle($eligible);
985 $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible)));
986 $participants = array_slice($eligible, 0, $participantCount);
987 $participantIds = array_map(fn($k) => $k->getId(), $participants);
988
989 // Set participants and execute event
990 $event->setParticipants($participantIds);
991 $event->execute();
992
993 // Add fatigue to participants
994 foreach ($participants as $participant) {
995 $participant->addFatigue($event->getCost());
996 if ($participant->isDead()) {
997 $monthEventStory .= $participant->getName() . " has died.\n";
998 }
999 $participant->save();
1000 }
1001
1002 // Add event story
1003 if ($event->getStory()) {
1004 $monthEventStory .= $event->getStory() . "\n";
1005 }
1006 }
1007
1008 // After events, consume food
1009
1010 // age eggs
1011 $foodStory = "A month passes...\n" . $this->consumeFood();
1012 if ($monthEventStory) {
1013 $foodStory = $monthEventStory . "\n" . $foodStory;
1014 }
1015
1016 foreach ($this->kobolds as $kobold) {
1017 if ($kobold->getAge() < 0) {
1018 $kobold->incrementAge();
1019
1020 if ($kobold->getAge() >= 0) {
1021 $kobold->setName(Kobold::generateRandomName());
1022 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
1023 }
1024
1025 $kobold->save();
1026 }
1027 }
1028
1029 // Age all kobolds
1030 if ($this->currentMonth % 12 === 0) {
1031 $foodStory .= "A new year begins.\n";
1032
1033 foreach ($this->kobolds as $kobold) {
1034 $foodStory .= $this->ageKobold($kobold);
1035 }
1036
1037 foreach ($this->rivals as $kobold) {
1038 $this->ageKobold($kobold); //we don't log these
1039 }
1040 }
1041 $foodStory .= "\n" . $this->tryMate();
1042 $foodStory .= "\nIt's {$this->currentSeason}.\n";
1043
1044 foreach ($this->kobolds as $kobold) {
1045 if ($kobold->isDead()) {
1046 $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried.";
1047 }
1048 }
1049
1050 $hasLeader = false;
1051 foreach ($this->getKobolds() as $kobold) {
1052 if ($kobold->isLeader()) {
1053 $hasLeader = true;
1054 break;
1055 }
1056 }
1057
1058 if (!$hasLeader) {
1059 $eligibleKobolds = array_filter($this->getKobolds(), function ($kobold) {
1060 return $kobold->getAgeCategory() !== 'egg';
1061 });
1062
1063 if (count($eligibleKobolds) >= 3) {
1064 $pickFromTier = function ($tier) {
1065 return array_values(array_filter($this->getKobolds(), function ($kobold) use ($tier) {
1066 return $kobold->getAgeCategory() === $tier;
1067 }));
1068 };
1069
1070 $candidatePools = [
1071 $pickFromTier('adult'),
1072 $pickFromTier('old'),
1073 $pickFromTier('young')
1074 ];
1075
1076 $candidates = [];
1077 foreach ($candidatePools as $pool) {
1078 if (!empty($pool)) {
1079 $candidates = $pool;
1080 break;
1081 }
1082 }
1083
1084 if (!empty($candidates)) {
1085 $scores = [];
1086 foreach ($candidates as $candidate) {
1087 $score = 0;
1088 foreach ($this->getKobolds() as $other) {
1089 if ($other->getId() === $candidate->getId()) {
1090 continue;
1091 }
1092
1093 $likes = 0;
1094 if (isset($other->dataStore) && $other->dataStore instanceof stdClass) {
1095 if (isset($other->dataStore->likes) && is_array($other->dataStore->likes)) {
1096 $likes = (int) ($other->dataStore->likes[$candidate->getId()] ?? 0);
1097 }
1098 }
1099 $score += $likes;
1100 }
1101 $scores[$candidate->getId()] = $score;
1102 }
1103
1104 $maxScore = max($scores);
1105 $topCandidates = array_values(array_filter($candidates, function ($candidate) use ($scores, $maxScore) {
1106 return $scores[$candidate->getId()] === $maxScore;
1107 }));
1108
1109 if (count($topCandidates) > 1) {
1110 usort($topCandidates, function ($a, $b) {
1111 return $b->getAge() <=> $a->getAge();
1112 });
1113
1114 $oldestAge = $topCandidates[0]->getAge();
1115 $topCandidates = array_values(array_filter($topCandidates, function ($candidate) use ($oldestAge) {
1116 return $candidate->getAge() === $oldestAge;
1117 }));
1118 }
1119
1120 $newLeader = $topCandidates[array_rand($topCandidates)];
1121 $newLeader->setLeader();
1122
1123 $leaderName = $newLeader->getName();
1124 $leaderStories = [
1125 "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.",
1126 "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.",
1127 "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.",
1128 "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.",
1129 "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.",
1130 "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.",
1131 "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.",
1132 "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.",
1133 "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.",
1134 "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."
1135 ];
1136
1137 $foodStory .= "\n" . $leaderStories[array_rand($leaderStories)] . "\n";
1138 }
1139 }
1140 }
1141
1142 $this->save();
1143
1144 return $foodStory;
1145 }
1146
1147 function ageKobold($kobold)
1148 {
1149 $foodStory = "";
1150 if ($kobold->getAge() >= 0) {
1151 $kobold->incrementAge();
1152
1153 // Check for old-age injuries
1154 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
1155 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
1156 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
1157 $kobold->addInjury($injury);
1158 }
1159
1160 // Old-age death roll: if roll < (age + total injury severity), kobold dies
1161 if ($kobold->getAge() >= 35) {
1162 $roll = rand(1, 100);
1163 $totalSeverity = $kobold->getTotalInjurySeverity();
1164 if ($roll < ($kobold->getAge() + $totalSeverity)) {
1165 $foodStory .= $kobold->getName() . " dies of old age.\n";
1166 $this->cleanupDeadKoboldLikes($kobold->getId());
1167 $kobold->die();
1168 }
1169 }
1170
1171 $kobold->save();
1172 }
1173 return $foodStory;
1174 }
1175
1176 private function shouldAddOldAgeInjury(Kobold $kobold)
1177 {
1178 // 1d100 roll under age starting at 35
1179 $roll = rand(1, 100);
1180 return $roll <= $kobold->getAge();
1181 }
1182
1183 /**
1184 * Clean up all likes references to a kobold when they die
1185 * Removes the kobold's ID from all other kobolds' likes arrays
1186 * and from rival records
1187 */
1188 private function cleanupDeadKoboldLikes($koboldId)
1189 {
1190 // Remove from all other kobolds' likes
1191 foreach ($this->kobolds as $other) {
1192 if ($other->getId() !== $koboldId) {
1193 if (!isset($other->dataStore)) {
1194 $other->dataStore = new stdClass();
1195 }
1196 if (!isset($other->dataStore->likes)) {
1197 $other->dataStore->likes = [];
1198 }
1199
1200 // Remove the dead kobold from this kobold's likes
1201 if (is_array($other->dataStore->likes)) {
1202 unset($other->dataStore->likes[$koboldId]);
1203 }
1204 }
1205 }
1206
1207 // Remove from rivals' likes if they exist
1208 if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) {
1209 foreach ($this->dataStore->rivals as &$rival) {
1210 if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) {
1211 unset($rival['data']['likes'][$koboldId]);
1212 }
1213 }
1214 }
1215 }
1216}