BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

title data
timfa Tim Falken · pushed by timfa · 9 months ago
1ff1ef25 History
Tribe.php 32.9 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4require_once __DIR__ . '/../../src/Classes/Kobold.php';
5
6class Tribe
7{
8 private $userId;
9 private $saveId;
10 private $name;
11 public $kobolds = [];
12 public $rivals = [];
13 private $storage = [];
14 private $currentMonth = 0;
15 private $currentSeason = 'spring';
16 private $foodCount = 0;
17 private $environmentId = null;
18 private $createdAt;
19 private $lastPlayed;
20 private $saveManager;
21 public $dataStore;
22
23 // Food requirement by age tier (portion units)
24 public $foodRequirements = [
25 'egg' => 0,
26 'baby' => 1,
27 'young' => 2,
28 'adult' => 3,
29 'old' => 2
30 ];
31
32 public function __construct($userId, $saveId, $name = '')
33 {
34 $this->userId = $userId;
35 $this->saveId = $saveId;
36 $this->name = $name;
37 $this->saveManager = new SaveManager();
38 $this->loadFromFile();
39 }
40
41 public static function create($userId, $saveName)
42 {
43 $saveManager = new SaveManager();
44 $saveId = $saveManager->generateSaveId($userId);
45
46 $tribe = new self($userId, $saveId, $saveName);
47 $tribe->createdAt = date('Y-m-d H:i:s');
48 $tribe->lastPlayed = date('Y-m-d H:i:s');
49 $tribe->save();
50
51 return $tribe;
52 }
53
54 public static function load($userId, $saveId)
55 {
56 return new self($userId, $saveId);
57 }
58
59 private function loadFromFile()
60 {
61 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
62 $saveFile = $savePath . '/save.json';
63
64 if (file_exists($saveFile)) {
65 $data = $this->saveManager->loadJson($saveFile);
66
67 if ($data) {
68 $this->name = $data['name'] ?? '';
69 $this->currentMonth = $data['current_month'] ?? 0;
70 $this->currentSeason = $data['current_season'] ?? 'spring';
71 $this->foodCount = $data['food_count'] ?? 0;
72 $this->environmentId = $data['environment_id'] ?? null;
73 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
74 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
75 $this->dataStore = $data['data_store'] ?? new stdClass();
76 }
77
78 if (is_array($this->dataStore)) {
79 $this->dataStore = (object) $this->dataStore;
80 }
81 }
82
83 $this->loadKobolds();
84 $this->loadStorage();
85 }
86
87 private function loadKobolds()
88 {
89 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
90 $koboldsFile = $savePath . '/kobolds.json';
91
92 $this->kobolds = [];
93
94 if (file_exists($koboldsFile)) {
95 $data = $this->saveManager->loadJson($koboldsFile);
96
97 if ($data && is_array($data)) {
98 foreach ($data as $koboldData) {
99 $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId);
100 if ($kobold) {
101 if ($kobold->isRival)
102 $this->rivals[$kobold->getId()] = $kobold;
103 else
104 $this->kobolds[$kobold->getId()] = $kobold;
105 }
106 }
107 }
108 }
109 }
110
111 public function isBestInTribeForStat($kobold, $statName)
112 {
113 if (!$kobold instanceof Kobold) {
114 return false;
115 }
116
117 $targetStat = $kobold->getStat($statName);
118 if ($targetStat === null) {
119 return false;
120 }
121
122 $bestStat = $targetStat;
123 foreach ($this->getKobolds() as $otherKobold) {
124 if ($otherKobold->getId() === $kobold->getId()) {
125 continue;
126 }
127
128 $otherStat = $otherKobold->getStat($statName);
129 if ($otherStat !== null && $otherStat > $bestStat) {
130 return false;
131 }
132 }
133
134 return true;
135 }
136
137 public function getKoboldTitle($kobold)
138 {
139 if (!$kobold instanceof Kobold) {
140 return false;
141 }
142
143 if ($this->isBestInTribeForStat($kobold, $kobold->getHighestStatName())) {
144 return "Chief " . $kobold->getTitle(false);
145 }
146
147 return $kobold->getTitle();
148 }
149
150 private function loadStorage()
151 {
152 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
153 $itemsFile = $savePath . '/items.json';
154
155 $this->storage = [];
156
157 if (file_exists($itemsFile)) {
158 $this->storage = $this->saveManager->loadJson($itemsFile) ?? [];
159 }
160 }
161
162 public function save()
163 {
164 $this->lastPlayed = date('Y-m-d H:i:s');
165
166 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
167
168 // Save tribe metadata
169 $tribeData = [
170 'name' => $this->name,
171 'current_month' => $this->currentMonth,
172 'current_season' => $this->currentSeason,
173 'food_count' => $this->foodCount,
174 'food_time_left' => $this->foodTimeStr($this->foodCount),
175 'environment_id' => $this->environmentId,
176 'created_at' => $this->createdAt,
177 'last_played' => $this->lastPlayed,
178 'data_store' => $this->dataStore ?? new stdClass()
179 ];
180
181 $this->saveManager->saveJson($savePath . '/save.json', $tribeData);
182
183 // Save kobolds
184 $koboldsData = [];
185 foreach ($this->kobolds as $kobold) {
186 if (!$kobold->isDead()) {
187 $kobold->save();
188 $koboldsData[] = $kobold->toArray();
189 }
190 }
191 foreach ($this->rivals as $kobold) {
192 if (!$kobold->isDead()) {
193 $kobold->save();
194 $koboldsData[] = $kobold->toArray();
195 }
196 }
197
198 $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData);
199
200 // Save items
201 $this->saveManager->saveJson($savePath . '/items.json', $this->storage);
202
203 GameHelper::cleanupUnusedKoboldSprites($this->userId);
204 }
205
206 // Getters and Setters
207 public function getName()
208 {
209 return $this->name;
210 }
211
212 public function setName($name)
213 {
214 $this->name = $name;
215 }
216
217 public function getSaveId()
218 {
219 return $this->saveId;
220 }
221
222 public function getUserId()
223 {
224 return $this->userId;
225 }
226
227 public function getCreatedAt()
228 {
229 return $this->createdAt;
230 }
231
232 public function getLastPlayed()
233 {
234 return $this->lastPlayed;
235 }
236
237 public function getCurrentMonth()
238 {
239 return $this->currentMonth;
240 }
241
242 public function setCurrentMonth($month)
243 {
244 $this->currentMonth = max(0, $month);
245 }
246
247 public function getCurrentSeason()
248 {
249 return $this->currentSeason;
250 }
251
252 public function setCurrentSeason($season)
253 {
254 $this->currentSeason = $season;
255 }
256
257 public function getEnvironmentId()
258 {
259 return $this->environmentId;
260 }
261
262 public function setEnvironmentId($environmentId)
263 {
264 $this->environmentId = $environmentId;
265 }
266
267 // Kobold management
268 public function getKobolds($rivals = false)
269 {
270 if ($rivals) {
271 return array_filter($this->rivals, function (Kobold $k) {
272 return !$k->isDead() && !$k->isExpelled();
273 });
274 }
275
276 return array_filter($this->kobolds, function (Kobold $k) {
277 return !$k->isDead() && !$k->isExpelled();
278 });
279 }
280
281 public function getKobold($id)
282 {
283 return $this->kobolds[$id] ?? $this->rivals[$id] ?? null;
284 }
285
286 public function addKobold(Kobold $kobold, $rival = false)
287 {
288 if ($rival) {
289 $this->rivals[$kobold->getId()] = $kobold;
290 return $kobold;
291 }
292
293 $this->kobolds[$kobold->getId()] = $kobold;
294 return $kobold;
295 }
296
297 public function removeKobold($id)
298 {
299 if (isset($this->kobolds[$id]))
300 unset($this->kobolds[$id]);
301
302 if (isset($this->rivals[$id]))
303 unset($this->rivals[$id]);
304 }
305
306 public function getAliveKobolds($rivals = false)
307 {
308 if ($rivals) {
309 return array_filter($this->rivals, fn($k) => !$k->isDead());
310 }
311
312 return array_filter($this->kobolds, fn($k) => !$k->isDead());
313 }
314
315 // Storage management
316 public function addToStorage(Item $item, int $count = 1): array
317 {
318 // Accept either Item object or array
319 if (is_object($item) && method_exists($item, 'toArray')) {
320 $this->storage[] = $item->toArray();
321 } elseif (is_array($item)) {
322 // Ensure it has an id
323 if (!isset($item['id'])) {
324 $item['id'] = uniqid('itm_');
325 }
326 for ($i = 0; $i < $count; $i++)
327 $this->storage[] = $item;
328 }
329 return $this->storage;
330 }
331
332 public function getStorage()
333 {
334 return $this->storage;
335 }
336
337 // Food system methods
338 public function getFoodCount()
339 {
340 return $this->foodCount;
341 }
342
343 public function addFood($amount)
344 {
345 $this->foodCount += $amount;
346 return $this->foodCount;
347 }
348
349 public function removeFood($amount)
350 {
351 $this->foodCount = max(0, $this->foodCount - $amount);
352 return $this->foodCount;
353 }
354
355 /**
356 * Calculate total food needed for all alive kobolds for one month
357 */
358 public function calculateFoodNeeded()
359 {
360 $needed = 0;
361
362 foreach ($this->getAliveKobolds() as $kobold) {
363 $ageCategory = $kobold->getAgeCategory();
364 $requirement = $this->foodRequirements[$ageCategory] ?? 1.0;
365 $needed += $requirement;
366 }
367
368 return $needed;
369 }
370
371 /**
372 * Calculate how many full months the current kobolds can be fed
373 * with the provided amount of food.
374 */
375 public function foodMonthsLeft($amount)
376 {
377 $foodPerMonth = $this->calculateFoodNeeded();
378 if ($foodPerMonth <= 0) {
379 return 0;
380 }
381
382 $available = max(0, (float) $amount);
383 return (int) floor($available / $foodPerMonth);
384 }
385
386 public function foodTimeStr($amount)
387 {
388 $months = $this->foodMonthsLeft($amount);
389 if ($months > 0) {
390 if ($months == 1)
391 return "1 month";
392 else
393 return "{$months} months";
394 }
395
396 $foodPerMonth = $this->calculateFoodNeeded();
397 if ($foodPerMonth <= 0) {
398 return "years";
399 }
400
401 $available = max(0, (float) $amount);
402 $days = (int) floor(($available / $foodPerMonth) * 30);
403 $weeks = intdiv($days, 7);
404
405 if ($weeks >= 1) {
406 return $weeks . " week" . ($weeks === 1 ? "" : "s");
407 }
408
409 return $days . " day" . ($days === 1 ? "" : "s");
410 }
411
412 /**
413 * Get food requirement for a specific kobold
414 */
415 public function getFoodRequirement(Kobold $kobold)
416 {
417 $ageCategory = $kobold->getAgeCategory();
418 return $this->foodRequirements[$ageCategory] ?? 1.0;
419 }
420
421 /**
422 * Consume food at end of month after events
423 * Prioritizes: malnourished kobolds first, then younger before older
424 * Returns story of food consumption and any starvations
425 */
426 public function consumeFood()
427 {
428 $story = "";
429 $aliveKobolds = $this->getAliveKobolds();
430
431 if (empty($aliveKobolds)) {
432 return $story;
433 }
434
435 // Sort kobolds: malnourished first, then by age (younger first)
436 usort($aliveKobolds, function ($a, $b) {
437 // Check for malnourished injury
438 $aMalnourished = $this->hasInjuryCategory($a, 'malnourished');
439 $bMalnourished = $this->hasInjuryCategory($b, 'malnourished');
440
441 if ($aMalnourished && !$bMalnourished)
442 return -1;
443 if (!$aMalnourished && $bMalnourished)
444 return 1;
445
446 // Both have or both don't have malnourished
447 // Younger first (lower age = higher priority)
448 return $a->getAge() - $b->getAge();
449 });
450
451 $fedKobolds = [];
452 $starvedKobolds = [];
453
454 foreach ($aliveKobolds as $kobold) {
455 $needed = $this->getFoodRequirement($kobold);
456
457 if ($this->foodCount >= $needed) {
458 // Fed this kobold
459 $this->foodCount -= $needed;
460 $fedKobolds[$kobold->getId()] = $kobold;
461
462 // If malnourished, cure it
463 if ($this->hasInjuryCategory($kobold, 'malnourished')) {
464 $this->removeMalnourishedInjury($kobold);
465 $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n";
466 }
467 } else {
468 // Not enough food - starve this kobold
469 $starvedKobolds[$kobold->getId()] = $kobold;
470 $this->foodCount = 0; // Use remaining food
471
472
473 $malnourishedId = $this->getMalnourishedInjuryId($kobold);
474 if (!$malnourishedId) {
475 $kobold->addInjury('malnourished-slight');
476 $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
477 } else {
478 if ($malnourishedId === 'malnourished-slight') {
479 $kobold->removeInjury($malnourishedId);
480 $kobold->addInjury('malnourished-mild');
481 $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
482 } elseif ($malnourishedId === 'malnourished-mild') {
483 $kobold->removeInjury($malnourishedId);
484 $kobold->addInjury('malnourished-severe');
485 $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
486 } elseif ($malnourishedId === 'malnourished-severe') {
487 $kobold->removeInjury($malnourishedId);
488 $kobold->addInjury('malnourished-brink');
489 $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
490 } elseif ($malnourishedId === 'malnourished-brink') {
491 $this->cleanupDeadKoboldLikes($kobold->getId());
492 $kobold->die();
493 $story .= "{$kobold->getName()} succumbed to starvation.\n";
494 }
495 }
496 }
497 }
498
499 // Save updated kobolds
500 foreach ($aliveKobolds as $kobold) {
501 $kobold->save();
502 }
503
504 return $story;
505 }
506
507 /**
508 * Check if a kobold has an injury in a specific category
509 */
510 private function hasInjuryCategory(Kobold $kobold, $category)
511 {
512 $injuries = $kobold->getInjuries();
513 foreach ($injuries as $injury) {
514 if ($injury['category'] === $category) {
515 return true;
516 }
517 }
518 return false;
519 }
520
521 /**
522 * Remove all malnourished injuries from a kobold
523 */
524 private function removeMalnourishedInjury(Kobold $kobold)
525 {
526 $injuries = $kobold->getInjuries();
527 foreach ($injuries as $injury) {
528 if ($injury['category'] === 'malnourished') {
529 $kobold->removeInjury($injury['id']);
530 }
531 }
532 }
533
534 /**
535 * Get current malnourished injury id if present
536 */
537 private function getMalnourishedInjuryId(Kobold $kobold)
538 {
539 $injuries = $kobold->getInjuries();
540 foreach ($injuries as $injury) {
541 if (($injury['category'] ?? null) === 'malnourished') {
542 return $injury['id'] ?? null;
543 }
544 }
545 return null;
546 }
547
548 public function tryMate()
549 {
550 $kobolds = array_values($this->getKobolds());
551 $count = count($kobolds);
552
553 if ($count === 0) {
554 return '';
555 }
556
557 $roll = rand(1, 30);
558 if ($roll <= $count) {
559 return '';
560 }
561
562 $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
563 $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));
564
565 if (empty($males) || empty($females)) {
566 return '';
567 }
568
569 $pair = null;
570 $attempts = 20;
571 while ($attempts-- > 0) {
572 $male = $males[array_rand($males)];
573 $female = $females[array_rand($females)];
574
575 $maleParents = $male->getParents();
576 $femaleParents = $female->getParents();
577
578 $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
579 $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
580 $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
581 $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);
582
583 if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
584 continue;
585 }
586
587 $pair = [$male, $female];
588 break;
589 }
590
591 if (!$pair) {
592 return '';
593 }
594
595 [$male, $female] = $pair;
596
597 if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) {
598 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
599 }
600
601 $child = Kobold::generate($this->userId, $this->saveId, -6);
602
603 if (!isset($child->dataStore)) {
604 $child->dataStore = new stdClass();
605 }
606 if (!isset($child->dataStore->likes)) {
607 $child->dataStore->likes = [];
608 }
609
610 // Child likes parents by default
611 $child->dataStore->likes[$male->getId()] = 10;
612 $child->dataStore->likes[$female->getId()] = 10;
613
614 // Initialize parents' dataStore if needed
615 if (!isset($male->dataStore)) {
616 $male->dataStore = new stdClass();
617 }
618 if (!isset($male->dataStore->likes)) {
619 $male->dataStore->likes = [];
620 }
621
622 if (!isset($female->dataStore)) {
623 $female->dataStore = new stdClass();
624 }
625 if (!isset($female->dataStore->likes)) {
626 $female->dataStore->likes = [];
627 }
628
629 // Parents like the child by default
630 $male->dataStore->likes[$child->getId()] = 20;
631 $female->dataStore->likes[$child->getId()] = 20;
632
633 $inheritRoll = rand(1, 100);
634 if ($inheritRoll <= 40) {
635 $child->setSpriteMorph($male->getSpriteMorph());
636 } elseif ($inheritRoll <= 80) {
637 $child->setSpriteMorph($female->getSpriteMorph());
638 }
639
640 $blendHex = function ($a, $b) {
641 $hexToRgb = function ($hex) {
642 $hex = ltrim($hex, '#');
643 return [
644 'r' => hexdec(substr($hex, 0, 2)),
645 'g' => hexdec(substr($hex, 2, 2)),
646 'b' => hexdec(substr($hex, 4, 2))
647 ];
648 };
649
650 $rgbToHex = function ($rgb) {
651 return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
652 };
653
654 $ra = $hexToRgb($a);
655 $rb = $hexToRgb($b);
656 $ratio = rand(0, 100) / 100;
657
658 $offset = function () {
659 return rand(-20, 20);
660 };
661
662 $mix = function ($c1, $c2) use ($ratio, $offset) {
663 $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
664 return max(0, min(255, $val));
665 };
666
667 $mixed = [
668 'r' => $mix($ra['r'], $rb['r']),
669 'g' => $mix($ra['g'], $rb['g']),
670 'b' => $mix($ra['b'], $rb['b'])
671 ];
672
673 return $rgbToHex($mixed);
674 };
675
676 $maleColours = $male->getColours();
677 $femaleColours = $female->getColours();
678
679 $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
680 $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
681 $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);
682
683 $child->setColours($childPrimary, $childSecondary, $childTertiary);
684 $child->setParents($male->getId(), $female->getId());
685 $child->regenerateSprite();
686
687 $this->addKobold($child);
688
689 $pairName = $female->getName() . " and " . $male->getName();
690 $momName = $female->getName();
691 $variations = [
692 "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
693 "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
694 "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
695 "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
696 "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
697 "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
698 "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
699 "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
700 "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
701 "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
702 ];
703
704 return $variations[array_rand($variations)];
705 }
706
707 public function getEndOfMonthEvents(): array
708 {
709 $maxCost = 250;
710 $selectedEvents = [];
711 $totalCost = 0;
712
713 // Scan src/Events directory for event classes
714 $eventsDir = __DIR__ . '/../../src/Events/';
715 $eventFiles = glob($eventsDir . '*.php');
716 $availableEventClasses = [];
717
718 foreach ($eventFiles as $file) {
719 $className = basename($file, '.php');
720
721 // Skip base classes
722 if ($className === 'Event' || $className === 'MonthEndEvent') {
723 continue;
724 }
725
726 require_once $file;
727
728 // Check if class exists and extends MonthEndEvent
729 if (!class_exists($className)) {
730 continue;
731 }
732
733 // Create temporary instance to check conditions
734 $tempEvent = new $className($this);
735
736 // Check if it's an end-of-month event
737 if (!$tempEvent->isEndOfMonth()) {
738 continue;
739 }
740
741 // Check if event is available
742 if (!$tempEvent->isAvailable()) {
743 continue;
744 }
745
746 // Check if tribe has enough eligible kobolds
747 $minAge = $tempEvent->getMinAge();
748 $minParticipants = $tempEvent->getMinParticipants();
749
750 $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) {
751 return $kobold->getAge() >= $minAge;
752 });
753
754 if (count($eligibleKobolds) < $minParticipants) {
755 continue;
756 }
757
758 // This event is available
759 $availableEventClasses[] = $className;
760 }
761
762 // If no events available, return empty array
763 if (empty($availableEventClasses)) {
764 return [];
765 }
766
767 // Select events randomly until cost exceeds maxCost
768 while ($totalCost <= $maxCost && !empty($availableEventClasses)) {
769 // Pick a random event class
770 $randomClass = $availableEventClasses[array_rand($availableEventClasses)];
771
772 // Create new instance
773 $event = new $randomClass($this);
774 $eventCost = $event->getCost();
775
776 // Add to selection
777 $selectedEvents[] = $event;
778 $totalCost += $eventCost;
779 }
780
781 return $selectedEvents;
782 }
783
784 public function endMonth()
785 {
786 $this->currentMonth++;
787
788 foreach ($this->kobolds as $kobold) {
789 $kobold->resetFatigue();
790 }
791
792 $seasons = ['spring', 'summer', 'autumn', 'winter'];
793
794 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
795 $index = intdiv($monthOfYear - 1, 3);
796 $pIndex = ($index + 3) % 4;
797
798 $previousSeason = $seasons[$pIndex];
799 $this->currentSeason = $seasons[$index];
800
801 if ($previousSeason == 'spring' && $this->currentSeason == 'summer') {
802 if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) {
803 $noHarvestVariations = [
804 "No seeds were sown in spring, so there can be no harvest come autumn.\n",
805 "With spring left untilled, there can be no harvest in autumn.\n",
806 "Spring passed without sowing; there can be no harvest this autumn.\n",
807 "The tribe never sowed in spring, so there can be no harvest later.\n",
808 "Nothing was planted in spring—there can be no harvest in autumn.\n",
809 "Spring's fields lay empty, and there can be no harvest ahead.\n",
810 "No planting happened in spring, so there can be no harvest when autumn arrives.\n"
811 ];
812 $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)];
813 }
814 }
815
816 if (
817 isset($this->dataStore->wasSowedInSpring)
818 && $this->dataStore->wasSowedInSpring
819 && $previousSeason == 'summer'
820 && $this->currentSeason == 'autumn'
821 ) {
822 if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever
823 $cropLossVariations = [
824 "The fields were not tended in summer, and all of the crops are lost.\n",
825 "Neglected through summer, all of the crops are lost.\n",
826 "With no summer care, all of the crops are lost to blight and pests.\n",
827 "Summer passed without tending the fields, and all of the crops are lost.\n",
828 "The fields were left to wild growth; all of the crops are lost.\n",
829 "No hands worked the fields in summer, so all of the crops are lost.\n",
830 "Left untended through summer, all of the crops are lost.\n"
831 ];
832 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
833 }
834 }
835
836 if (
837 isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened
838 && $this->dataStore->wasTendedInSummer
839 && $previousSeason == 'summer'
840 && $this->currentSeason == 'autumn'
841 ) {
842 $cropLossVariations = [
843 "The crops stood too long, and winter's cold ruined what should have been gathered.\n",
844 "Harvest came too late; the first hard freezes destroyed the crops.\n",
845 "No harvest was taken in time, and the winter cold ruined the fields.\n",
846 "The fields were left unharvested, and winter's chill destroyed the crops.\n",
847 "The tribe missed the harvest window, and the cold of winter claimed the crops.\n",
848 "By the time harvest was attempted, winter had already destroyed the crops.\n",
849 "The crops were left in the fields until winter, and the cold destroyed them.\n"
850 ];
851 $foodStory = $cropLossVariations[array_rand($cropLossVariations)];
852 }
853
854 // Execute end-of-month events
855 $monthEventStory = '';
856 $endOfMonthEvents = $this->getEndOfMonthEvents();
857
858 foreach ($endOfMonthEvents as $event) {
859 // Select eligible participants
860 $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) {
861 return $kobold->getAge() >= $event->getMinAge();
862 });
863
864 if (count($eligible) < $event->getMinParticipants()) {
865 continue;
866 }
867
868 // Randomly select participants (between min and max)
869 $eligible = array_values($eligible);
870 shuffle($eligible);
871 $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible)));
872 $participants = array_slice($eligible, 0, $participantCount);
873 $participantIds = array_map(fn($k) => $k->getId(), $participants);
874
875 // Set participants and execute event
876 $event->setParticipants($participantIds);
877 $event->execute();
878
879 // Add fatigue to participants
880 foreach ($participants as $participant) {
881 $participant->addFatigue($event->getCost());
882 if ($participant->isDead()) {
883 $monthEventStory .= $participant->getName() . " has died.\n";
884 }
885 $participant->save();
886 }
887
888 // Add event story
889 if ($event->getStory()) {
890 $monthEventStory .= $event->getStory() . "\n";
891 }
892 }
893
894 // After events, consume food
895
896 // age eggs
897 $foodStory = "A month passes...\n" . $this->consumeFood();
898 if ($monthEventStory) {
899 $foodStory = $monthEventStory . "\n" . $foodStory;
900 }
901
902 foreach ($this->kobolds as $kobold) {
903 if ($kobold->getAge() < 0) {
904 $kobold->incrementAge();
905
906 if ($kobold->getAge() >= 0) {
907 $kobold->setName(Kobold::generateRandomName());
908 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
909 }
910
911 $kobold->save();
912 }
913 }
914
915 // Age all kobolds
916 if ($this->currentMonth % 12 === 0) {
917 $foodStory .= "A new year begins.\n";
918
919 foreach ($this->kobolds as $kobold) {
920 $foodStory .= $this->ageKobold($kobold);
921 }
922
923 foreach ($this->rivals as $kobold) {
924 $this->ageKobold($kobold); //we don't log these
925 }
926 }
927 $foodStory .= "\n" . $this->tryMate();
928 $foodStory .= "\nIt's {$this->currentSeason}.\n";
929
930 foreach ($this->kobolds as $kobold) {
931 if ($kobold->isDead()) {
932 $foodStory = $foodStory . "\n" . $kobold->getName() . " has been buried.";
933 }
934 }
935
936 $this->save();
937
938 return $foodStory;
939 }
940
941 function ageKobold($kobold)
942 {
943 $foodStory = "";
944 if ($kobold->getAge() >= 0) {
945 $kobold->incrementAge();
946
947 // Check for old-age injuries
948 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
949 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
950 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
951 $kobold->addInjury($injury);
952 }
953
954 // Old-age death roll: if roll < (age + total injury severity), kobold dies
955 if ($kobold->getAge() >= 35) {
956 $roll = rand(1, 100);
957 $totalSeverity = $kobold->getTotalInjurySeverity();
958 if ($roll < ($kobold->getAge() + $totalSeverity)) {
959 $foodStory .= $kobold->getName() . " dies of old age.\n";
960 $this->cleanupDeadKoboldLikes($kobold->getId());
961 $kobold->die();
962 }
963 }
964
965 $kobold->save();
966 }
967 return $foodStory;
968 }
969
970 private function shouldAddOldAgeInjury(Kobold $kobold)
971 {
972 // 1d100 roll under age starting at 35
973 $roll = rand(1, 100);
974 return $roll <= $kobold->getAge();
975 }
976
977 /**
978 * Clean up all likes references to a kobold when they die
979 * Removes the kobold's ID from all other kobolds' likes arrays
980 * and from rival records
981 */
982 private function cleanupDeadKoboldLikes($koboldId)
983 {
984 // Remove from all other kobolds' likes
985 foreach ($this->kobolds as $other) {
986 if ($other->getId() !== $koboldId) {
987 if (!isset($other->dataStore)) {
988 $other->dataStore = new stdClass();
989 }
990 if (!isset($other->dataStore->likes)) {
991 $other->dataStore->likes = [];
992 }
993
994 // Remove the dead kobold from this kobold's likes
995 if (is_array($other->dataStore->likes)) {
996 unset($other->dataStore->likes[$koboldId]);
997 }
998 }
999 }
1000
1001 // Remove from rivals' likes if they exist
1002 if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) {
1003 foreach ($this->dataStore->rivals as &$rival) {
1004 if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) {
1005 unset($rival['data']['likes'][$koboldId]);
1006 }
1007 }
1008 }
1009 }
1010}