0, 'baby' => 1, 'young' => 2, 'adult' => 3, 'old' => 2 ]; public function __construct($userId, $saveId, $name = '') { $this->userId = $userId; $this->saveId = $saveId; $this->name = $name; $this->saveManager = new SaveManager(); $this->loadFromFile(); } public static function create($userId, $saveName) { $saveManager = new SaveManager(); $saveId = $saveManager->generateSaveId($userId); $tribe = new self($userId, $saveId, $saveName); $tribe->createdAt = date('Y-m-d H:i:s'); $tribe->lastPlayed = date('Y-m-d H:i:s'); $tribe->save(); return $tribe; } public static function load($userId, $saveId) { return new self($userId, $saveId); } private function loadFromFile() { $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); $saveFile = $savePath . '/save.json'; if (file_exists($saveFile)) { $data = $this->saveManager->loadJson($saveFile); if ($data) { $this->name = $data['name'] ?? ''; $this->currentMonth = $data['current_month'] ?? 0; $this->currentSeason = $data['current_season'] ?? 'spring'; $this->foodCount = $data['food_count'] ?? 0; $this->environmentId = $data['environment_id'] ?? null; $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s'); $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s'); $this->dataStore = $data['data_store'] ?? new stdClass(); } if (is_array($this->dataStore)) { $this->dataStore = (object) $this->dataStore; } } $this->loadKobolds(); $this->loadStorage(); } private function loadKobolds() { $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); $koboldsFile = $savePath . '/kobolds.json'; $this->kobolds = []; if (file_exists($koboldsFile)) { $data = $this->saveManager->loadJson($koboldsFile); if ($data && is_array($data)) { foreach ($data as $koboldData) { $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId); if ($kobold) { if ($kobold->isRival) $this->rivals[$kobold->getId()] = $kobold; else $this->kobolds[$kobold->getId()] = $kobold; } } } } } public function isBestInTribeForStat($kobold, $statName) { if (!$kobold instanceof Kobold) { return false; } if ($kobold->getAgeCategory() == "egg") return false; if ($kobold->getAgeCategory() == "baby") return false; if ($kobold->getAgeCategory() == "young") return false; if ($kobold->getHighestStatName() !== $statName) { return false; } $targetStat = $kobold->getStat($statName); if ($targetStat === null || $targetStat < 50) { return false; } $hasPeer = false; foreach ($this->getKobolds() as $otherKobold) { if ($otherKobold->getId() === $kobold->getId()) { continue; } if ($otherKobold->getHighestStatName() !== $statName) { continue; } if ($otherKobold->getAgeCategory() == "egg") continue; if ($otherKobold->getAgeCategory() == "baby") continue; if ($otherKobold->getAgeCategory() == "young") continue; if ($otherKobold->isLeader()) continue; $hasPeer = true; $otherStat = $otherKobold->getStat($statName); if ($otherStat !== null && $otherStat > $targetStat) { return false; } } return $hasPeer; } public function getKoboldTitle($kobold) { if (!$kobold instanceof Kobold) { return false; } $elder = $kobold->getAgeCategory() == "old" ? "Elder " : ""; if ($kobold->isLeader()) return $elder . "Chieftain"; if ($kobold->getAgeCategory() == "egg") return "Egg"; if ($kobold->getAgeCategory() == "baby") return "Baby"; if ($kobold->getAgeCategory() == "young") return "Youngling"; if ($this->isBestInTribeForStat($kobold, $kobold->getHighestStatName())) { return $elder . "Chief " . $kobold->getTitle(false); } return $elder . $kobold->getTitle(); } public function getTitleForKobold($kobold) { return $this->getKoboldTitle($kobold); } private function loadStorage() { $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); $itemsFile = $savePath . '/items.json'; $this->storage = []; if (file_exists($itemsFile)) { $this->storage = $this->saveManager->loadJson($itemsFile) ?? []; } } public function save() { $this->lastPlayed = date('Y-m-d H:i:s'); $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); // Save tribe metadata $tribeData = [ 'name' => $this->name, 'current_month' => $this->currentMonth, 'current_season' => $this->currentSeason, 'food_count' => $this->foodCount, 'food_time_left' => $this->foodTimeStr($this->foodCount), 'environment_id' => $this->environmentId, 'created_at' => $this->createdAt, 'last_played' => $this->lastPlayed, 'data_store' => $this->dataStore ?? new stdClass() ]; $this->saveManager->saveJson($savePath . '/save.json', $tribeData); // Save kobolds $koboldsData = []; foreach ($this->kobolds as $kobold) { if (!$kobold->isDead()) { $kobold->save(); $koboldsData[] = $kobold->toArray(); } } foreach ($this->rivals as $kobold) { if (!$kobold->isDead()) { $kobold->save(); $koboldsData[] = $kobold->toArray(); } } $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData); // Save items $this->saveManager->saveJson($savePath . '/items.json', $this->storage); GameHelper::cleanupUnusedKoboldSprites($this->userId); } // Getters and Setters public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getSaveId() { return $this->saveId; } public function getUserId() { return $this->userId; } public function getCreatedAt() { return $this->createdAt; } public function getLastPlayed() { return $this->lastPlayed; } public function getCurrentMonth() { return $this->currentMonth; } public function setCurrentMonth($month) { $this->currentMonth = max(0, $month); } public function getCurrentSeason() { return $this->currentSeason; } public function setCurrentSeason($season) { $this->currentSeason = $season; } public function getEnvironmentId() { return $this->environmentId; } public function setEnvironmentId($environmentId) { $this->environmentId = $environmentId; } // Kobold management public function getKobolds($rivals = false) { if ($rivals) { return array_filter($this->rivals, function (Kobold $k) { return !$k->isDead() && !$k->isExpelled(); }); } return array_filter($this->kobolds, function (Kobold $k) { return !$k->isDead() && !$k->isExpelled(); }); } public function getKobold($id) { return $this->kobolds[$id] ?? $this->rivals[$id] ?? null; } public function addKobold(Kobold $kobold, $rival = false) { if ($rival) { $this->rivals[$kobold->getId()] = $kobold; return $kobold; } $this->kobolds[$kobold->getId()] = $kobold; return $kobold; } public function removeKobold($id) { if (isset($this->kobolds[$id])) unset($this->kobolds[$id]); if (isset($this->rivals[$id])) unset($this->rivals[$id]); } public function getAliveKobolds($rivals = false) { if ($rivals) { return array_filter($this->rivals, fn($k) => !$k->isDead()); } return array_filter($this->kobolds, fn($k) => !$k->isDead()); } // Storage management public function addToStorage(Item $item, int $count = 1): array { // Accept either Item object or array if (is_object($item) && method_exists($item, 'toArray')) { $this->storage[] = $item->toArray(); } elseif (is_array($item)) { // Ensure it has an id if (!isset($item['id'])) { $item['id'] = uniqid('itm_'); } for ($i = 0; $i < $count; $i++) $this->storage[] = $item; } return $this->storage; } public function getStorage() { return $this->storage; } // Food system methods public function getFoodCount() { return $this->foodCount; } public function addFood($amount) { $this->foodCount += $amount; return $this->foodCount; } public function removeFood($amount) { $this->foodCount = max(0, $this->foodCount - $amount); return $this->foodCount; } public function modifyFoodGain(&$amount) { $reason = null; if ($amount <= 0) { return $reason; } if (!empty($this->dataStore->draught) && $this->dataStore->draught > 0) { $amount = (int) floor($amount / 2); $reason = 'draught'; } return $reason; } /** * Calculate total food needed for all alive kobolds for one month */ public function calculateFoodNeeded() { $needed = 0; foreach ($this->getAliveKobolds() as $kobold) { $ageCategory = $kobold->getAgeCategory(); $requirement = $this->foodRequirements[$ageCategory] ?? 1.0; $needed += $requirement; } return $needed; } /** * Calculate how many full months the current kobolds can be fed * with the provided amount of food. */ public function foodMonthsLeft($amount) { $foodPerMonth = $this->calculateFoodNeeded(); if ($foodPerMonth <= 0) { return 0; } $available = max(0, (float) $amount); return (int) floor($available / $foodPerMonth); } public function foodTimeStr($amount) { $months = $this->foodMonthsLeft($amount); if ($months > 0) { if ($months == 1) return "1 month"; else return "{$months} months"; } $foodPerMonth = $this->calculateFoodNeeded(); if ($foodPerMonth <= 0) { return "years"; } $available = max(0, (float) $amount); $days = (int) floor(($available / $foodPerMonth) * 30); $weeks = intdiv($days, 7); if ($weeks >= 1) { return $weeks . " week" . ($weeks === 1 ? "" : "s"); } return $days . " day" . ($days === 1 ? "" : "s"); } /** * Get food requirement for a specific kobold */ public function getFoodRequirement(Kobold $kobold) { $ageCategory = $kobold->getAgeCategory(); return $this->foodRequirements[$ageCategory] ?? 1.0; } /** * Consume food at end of month after events * Prioritizes: malnourished kobolds first, then younger before older * Returns story of food consumption and any starvations */ public function consumeFood() { $story = ""; $aliveKobolds = $this->getAliveKobolds(); if (empty($aliveKobolds)) { return $story; } // Sort kobolds: malnourished first, then by age (younger first) usort($aliveKobolds, function ($a, $b) { // Check for malnourished injury $aMalnourished = $this->hasInjuryCategory($a, 'malnourished'); $bMalnourished = $this->hasInjuryCategory($b, 'malnourished'); if ($aMalnourished && !$bMalnourished) return -1; if (!$aMalnourished && $bMalnourished) return 1; // Both have or both don't have malnourished // Younger first (lower age = higher priority) return $a->getAge() - $b->getAge(); }); $fedKobolds = []; $starvedKobolds = []; foreach ($aliveKobolds as $kobold) { $needed = $this->getFoodRequirement($kobold); if ($this->foodCount >= $needed) { // Fed this kobold $this->foodCount -= $needed; $fedKobolds[$kobold->getId()] = $kobold; // If malnourished, cure it if ($this->hasInjuryCategory($kobold, 'malnourished')) { $this->removeMalnourishedInjury($kobold); $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n"; } } else { // Not enough food - starve this kobold $starvedKobolds[$kobold->getId()] = $kobold; $this->foodCount = 0; // Use remaining food $malnourishedId = $this->getMalnourishedInjuryId($kobold); if (!$malnourishedId) { $kobold->addInjury('malnourished-slight'); $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n"; } else { if ($malnourishedId === 'malnourished-slight') { $kobold->removeInjury($malnourishedId); $kobold->addInjury('malnourished-mild'); $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n"; } elseif ($malnourishedId === 'malnourished-mild') { $kobold->removeInjury($malnourishedId); $kobold->addInjury('malnourished-severe'); $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n"; } elseif ($malnourishedId === 'malnourished-severe') { $kobold->removeInjury($malnourishedId); $kobold->addInjury('malnourished-brink'); $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n"; } elseif ($malnourishedId === 'malnourished-brink') { $this->cleanupDeadKoboldLikes($kobold->getId()); $kobold->die(); $story .= "{$kobold->getName()} succumbed to starvation.\n"; } } } } // Save updated kobolds foreach ($aliveKobolds as $kobold) { $kobold->save(); } return $story; } /** * Check if a kobold has an injury in a specific category */ private function hasInjuryCategory(Kobold $kobold, $category) { $injuries = $kobold->getInjuries(); foreach ($injuries as $injury) { if ($injury['category'] === $category) { return true; } } return false; } /** * Remove all malnourished injuries from a kobold */ private function removeMalnourishedInjury(Kobold $kobold) { $injuries = $kobold->getInjuries(); foreach ($injuries as $injury) { if ($injury['category'] === 'malnourished') { $kobold->removeInjury($injury['id']); } } } /** * Get current malnourished injury id if present */ private function getMalnourishedInjuryId(Kobold $kobold) { $injuries = $kobold->getInjuries(); foreach ($injuries as $injury) { if (($injury['category'] ?? null) === 'malnourished') { return $injury['id'] ?? null; } } return null; } public function tryMate() { $kobolds = array_values($this->getKobolds()); $count = count($kobolds); if ($count === 0) { return ''; } $roll = rand(1, 30); if ($roll <= $count) { return ''; } $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult')); $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult')); if (empty($males) || empty($females)) { return ''; } $pair = null; $attempts = 20; while ($attempts-- > 0) { $male = $males[array_rand($males)]; $female = $females[array_rand($females)]; $maleParents = $male->getParents(); $femaleParents = $female->getParents(); $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null); $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null); $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null); $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null); if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) { continue; } $pair = [$male, $female]; break; } if (!$pair) { return ''; } [$male, $female] = $pair; if (!$male->checkPersonality($female) || !$female->checkPersonality($male)) { return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off."; } $child = Kobold::generate($this->userId, $this->saveId, -6); if (!isset($child->dataStore)) { $child->dataStore = new stdClass(); } if (!isset($child->dataStore->likes)) { $child->dataStore->likes = []; } // Child likes parents by default $child->dataStore->likes[$male->getId()] = 10; $child->dataStore->likes[$female->getId()] = 10; // Initialize parents' dataStore if needed if (!isset($male->dataStore)) { $male->dataStore = new stdClass(); } if (!isset($male->dataStore->likes)) { $male->dataStore->likes = []; } if (!isset($female->dataStore)) { $female->dataStore = new stdClass(); } if (!isset($female->dataStore->likes)) { $female->dataStore->likes = []; } // Parents like the child by default $male->dataStore->likes[$child->getId()] = 20; $female->dataStore->likes[$child->getId()] = 20; $inheritRoll = rand(1, 100); if ($inheritRoll <= 40) { $child->setSpriteMorph($male->getSpriteMorph()); } elseif ($inheritRoll <= 80) { $child->setSpriteMorph($female->getSpriteMorph()); } $blendHex = function ($a, $b) { $hexToRgb = function ($hex) { $hex = ltrim($hex, '#'); return [ 'r' => hexdec(substr($hex, 0, 2)), 'g' => hexdec(substr($hex, 2, 2)), 'b' => hexdec(substr($hex, 4, 2)) ]; }; $rgbToHex = function ($rgb) { return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']); }; $ra = $hexToRgb($a); $rb = $hexToRgb($b); $ratio = rand(0, 100) / 100; $offset = function () { return rand(-20, 20); }; $mix = function ($c1, $c2) use ($ratio, $offset) { $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset()); return max(0, min(255, $val)); }; $mixed = [ 'r' => $mix($ra['r'], $rb['r']), 'g' => $mix($ra['g'], $rb['g']), 'b' => $mix($ra['b'], $rb['b']) ]; return $rgbToHex($mixed); }; $maleColours = $male->getColours(); $femaleColours = $female->getColours(); $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']); $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']); $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']); $child->setColours($childPrimary, $childSecondary, $childTertiary); $child->setParents($male->getId(), $female->getId()); $child->regenerateSprite(); $this->addKobold($child); $pairName = $female->getName() . " and " . $male->getName(); $momName = $female->getName(); $variations = [ "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!", "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.", "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.", "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.", "After many shared moments, {$pairName} welcomed a new egg from {$momName}.", "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.", "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.", "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.", "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.", "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg." ]; return $variations[array_rand($variations)]; } public function getEndOfMonthEvents(): array { $maxCost = 250; $selectedEvents = []; $totalCost = 0; // Scan src/Events directory for event classes $eventsDir = __DIR__ . '/../../src/Events/'; $eventFiles = glob($eventsDir . '*.php'); $availableEventClasses = []; foreach ($eventFiles as $file) { $className = basename($file, '.php'); // Skip base classes if ($className === 'Event' || $className === 'MonthEndEvent') { continue; } require_once $file; // Check if class exists and extends MonthEndEvent if (!class_exists($className)) { continue; } // Create temporary instance to check conditions $tempEvent = new $className($this); // Check if it's an end-of-month event if (!$tempEvent->isEndOfMonth()) { continue; } // Check if event is available if (!$tempEvent->isAvailable()) { continue; } // Check if tribe has enough eligible kobolds $minAge = $tempEvent->getMinAge(); $minParticipants = $tempEvent->getMinParticipants(); $eligibleKobolds = array_filter($this->getAliveKobolds(), function ($kobold) use ($minAge) { return $kobold->getAge() >= $minAge; }); if (count($eligibleKobolds) < $minParticipants) { continue; } // This event is available $availableEventClasses[] = $className; } // If no events available, return empty array if (empty($availableEventClasses)) { return []; } // Select events randomly until cost exceeds maxCost while ($totalCost <= $maxCost && !empty($availableEventClasses)) { // Pick a weighted random event class (lower cost = higher weight) $weights = []; $weightTotal = 0; foreach ($availableEventClasses as $className) { $tempEvent = new $className($this); $eventCost = max(1, (int) $tempEvent->getCost()); $weight = 1 / $eventCost; $weights[] = $weight; $weightTotal += $weight; } $roll = (mt_rand() / mt_getrandmax()) * $weightTotal; $running = 0; $randomClass = $availableEventClasses[0]; foreach ($availableEventClasses as $index => $className) { $running += $weights[$index]; if ($roll <= $running) { $randomClass = $className; break; } } // Create new instance $event = new $randomClass($this); $eventCost = $event->getCost(); // Add to selection $selectedEvents[] = $event; $totalCost += $eventCost; } return $selectedEvents; } public function endMonth() { $this->currentMonth++; if (!isset($this->dataStore)) { $this->dataStore = new stdClass(); } $this->dataStore->heatWaveActive = max(0, (int) ($this->dataStore->heatWaveActive ?? 0) - 1); $this->dataStore->draught = max(0, (int) ($this->dataStore->draught ?? 0) - 1); $this->dataStore->floodedThisMonth = false; $reportedDeaths = []; $aliveAtStart = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); $ongoingWeatherStory = ''; if ($this->dataStore->draught > 0) { $droughtLines = [ "The drought continues, and the land remains cracked and dry.\n", "No rain comes yet; the drought persists across the camp.\n", "The drought has not broken, and the tribe endures another dry month.\n" ]; $ongoingWeatherStory .= $droughtLines[array_rand($droughtLines)]; } if ($this->dataStore->heatWaveActive > 0) { $heatLines = [ "The heat wave continues, and the camp moves slowly under the oppressive sun.\n", "The heat wave has not faded; the tribe bears another sweltering month.\n", "Relief does not come, and the heat wave presses on.\n" ]; $ongoingWeatherStory .= $heatLines[array_rand($heatLines)]; } if ($this->dataStore->draught <= 0) { foreach ($this->getKobolds() as $kobold) { $injuries = $kobold->getInjuries(); foreach ($injuries as $injury) { if (($injury['id'] ?? null) === 'dehydrated') { $kobold->removeInjury('dehydrated'); } } } } foreach ($this->getKobolds() as $kobold) { $injuries = $kobold->getInjuries(); $hasHeatstroke = false; foreach ($injuries as $injury) { if (($injury['id'] ?? null) === 'heatstroke') { $hasHeatstroke = true; break; } } if ($hasHeatstroke) { $vitality = (int) ($kobold->getStat('vitality') ?? 0); $baselineFatigue = (int) ceil($vitality * 0.75); if ($this->dataStore->heatWaveActive <= 0 || $kobold->getFatigue() <= $baselineFatigue) { $kobold->removeInjury('heatstroke'); } } } foreach ($this->kobolds as $kobold) { $kobold->resetFatigue(); } $seasons = ['spring', 'summer', 'autumn', 'winter']; $monthOfYear = (($this->currentMonth - 1) % 12) + 1; $index = intdiv($monthOfYear - 1, 3); $pIndex = ($index + 3) % 4; $previousSeason = $seasons[$pIndex]; $this->currentSeason = $seasons[$index]; if ($previousSeason == 'spring' && $this->currentSeason == 'summer') { if (!isset($this->dataStore->wasSowedInSpring) || !$this->dataStore->wasSowedInSpring) { $noHarvestVariations = [ "No seeds were sown in spring, so there can be no harvest come autumn.\n", "With spring left untilled, there can be no harvest in autumn.\n", "Spring passed without sowing; there can be no harvest this autumn.\n", "The tribe never sowed in spring, so there can be no harvest later.\n", "Nothing was planted in spring—there can be no harvest in autumn.\n", "Spring's fields lay empty, and there can be no harvest ahead.\n", "No planting happened in spring, so there can be no harvest when autumn arrives.\n" ]; $foodStory = $noHarvestVariations[array_rand($noHarvestVariations)]; } } if ( isset($this->dataStore->wasSowedInSpring) && $this->dataStore->wasSowedInSpring && $previousSeason == 'summer' && $this->currentSeason == 'autumn' ) { if (!isset($this->dataStore->wasTendedInSummer) || !$this->dataStore->wasTendedInSummer) { //this check is redundant but whatever $cropLossVariations = [ "The fields were not tended in summer, and all of the crops are lost.\n", "Neglected through summer, all of the crops are lost.\n", "With no summer care, all of the crops are lost to blight and pests.\n", "Summer passed without tending the fields, and all of the crops are lost.\n", "The fields were left to wild growth; all of the crops are lost.\n", "No hands worked the fields in summer, so all of the crops are lost.\n", "Left untended through summer, all of the crops are lost.\n" ]; $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; } } if ( isset($this->dataStore->wasTendedInSummer) //this being true means no harvest happened && $this->dataStore->wasTendedInSummer && $previousSeason == 'summer' && $this->currentSeason == 'autumn' ) { $cropLossVariations = [ "The crops stood too long, and winter's cold ruined what should have been gathered.\n", "Harvest came too late; the first hard freezes destroyed the crops.\n", "No harvest was taken in time, and the winter cold ruined the fields.\n", "The fields were left unharvested, and winter's chill destroyed the crops.\n", "The tribe missed the harvest window, and the cold of winter claimed the crops.\n", "By the time harvest was attempted, winter had already destroyed the crops.\n", "The crops were left in the fields until winter, and the cold destroyed them.\n" ]; $foodStory = $cropLossVariations[array_rand($cropLossVariations)]; } // Execute end-of-month events $monthEventStory = $ongoingWeatherStory; $endOfMonthEvents = $this->getEndOfMonthEvents(); $hasFloodEvent = false; foreach ($endOfMonthEvents as $event) { $className = get_class($event); if ($className === 'SmallFloodEvent' || $className === 'LargeFloodEvent') { $hasFloodEvent = true; } } if ($hasFloodEvent) { $this->dataStore->floodedThisMonth = true; $endOfMonthEvents = array_values(array_filter($endOfMonthEvents, function ($event) { return get_class($event) !== 'DroughtEvent'; })); } foreach ($endOfMonthEvents as $event) { $aliveBeforeEvent = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); $eventClass = get_class($event); $eventLabel = preg_replace('/Event$/', '', $eventClass); $eventLabel = strtolower(preg_replace('/([a-z])([A-Z])/', '$1 $2', $eventLabel)); // Select eligible participants $eligible = array_filter($this->getAliveKobolds(), function ($kobold) use ($event) { return $kobold->getAge() >= $event->getMinAge(); }); if (count($eligible) < $event->getMinParticipants()) { continue; } // Randomly select participants (between min and max) $eligible = array_values($eligible); shuffle($eligible); $participantCount = rand($event->getMinParticipants(), min($event->getMaxParticipants(), count($eligible))); $participants = array_slice($eligible, 0, $participantCount); $participantIds = array_map(fn($k) => $k->getId(), $participants); // Set participants and execute event $event->setParticipants($participantIds); $event->execute(); foreach ($event->getReportedDeaths() as $deadId) { $reportedDeaths[$deadId] = true; } foreach ($aliveBeforeEvent as $deadId) { $kobold = $this->getKobold($deadId); if (!$kobold || !$kobold->isDead()) { continue; } if (!isset($reportedDeaths[$deadId])) { $deathMessage = null; if (isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass) { $deathMessage = $kobold->dataStore->lastDeathMessage ?? null; if ($deathMessage) { unset($kobold->dataStore->lastDeathMessage); } } if ($deathMessage) { $monthEventStory .= $deathMessage . "\n"; } else { $monthEventStory .= $kobold->getName() . " died during the {$eventLabel}.\n"; } $reportedDeaths[$deadId] = true; } } foreach ($participants as $participant) { if ($participant->isDead() && !isset($reportedDeaths[$participant->getId()])) { $deathMessage = null; if (isset($participant->dataStore) && $participant->dataStore instanceof stdClass) { $deathMessage = $participant->dataStore->lastDeathMessage ?? null; if ($deathMessage) { unset($participant->dataStore->lastDeathMessage); } } if ($deathMessage) { $monthEventStory .= $deathMessage . "\n"; } else { $monthEventStory .= $participant->getName() . " has died.\n"; } $reportedDeaths[$participant->getId()] = true; } $participant->save(); } // Add event story if ($event->getStory()) { $monthEventStory .= $event->getStory() . "\n\n"; } } // After events, consume food // age eggs $aliveBeforeFood = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); $foodStory = "A month passes...\n" . $this->consumeFood(); $aliveAfterFood = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); $foodDeaths = array_diff($aliveBeforeFood, $aliveAfterFood); foreach ($foodDeaths as $deadId) { $reportedDeaths[$deadId] = true; } if ($monthEventStory) { $foodStory = $monthEventStory . "\n" . $foodStory; } foreach ($this->kobolds as $kobold) { if ($kobold->getAge() < 0) { $kobold->incrementAge(); if ($kobold->getAge() >= 0) { $kobold->setName(Kobold::generateRandomName()); $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n"; } $kobold->save(); } } // Age all kobolds if ($this->currentMonth % 12 === 0) { $foodStory .= "A new year begins.\n"; foreach ($this->kobolds as $kobold) { $wasAlive = !$kobold->isDead(); $foodStory .= $this->ageKobold($kobold); if ($wasAlive && $kobold->isDead()) { $reportedDeaths[$kobold->getId()] = true; } } foreach ($this->rivals as $kobold) { $this->ageKobold($kobold); //we don't log these } } $foodStory .= "\n" . $this->tryMate(); $foodStory .= "\nIt's {$this->currentSeason}.\n"; $aliveAtEnd = array_map(fn($k) => $k->getId(), $this->getAliveKobolds()); $newDeaths = array_diff($aliveAtStart, $aliveAtEnd); foreach ($newDeaths as $deadId) { if (isset($reportedDeaths[$deadId])) { continue; } $kobold = $this->getKobold($deadId); if (!$kobold) { continue; } $deathMessage = null; if (isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass) { $deathMessage = $kobold->dataStore->lastDeathMessage ?? null; if ($deathMessage) { unset($kobold->dataStore->lastDeathMessage); } } if ($deathMessage) { $foodStory .= "\n" . $deathMessage; } else { $injuryDeath = $kobold->getTotalInjurySeverity() >= (int) ($kobold->getStat('vitality') ?? 0); if ($injuryDeath) { $foodStory .= "\n" . $kobold->getName() . " succumbed to injuries."; } else { $foodStory .= "\n" . $kobold->getName() . " died."; } } $reportedDeaths[$deadId] = true; } $hasLeader = false; foreach ($this->getKobolds() as $kobold) { if ($kobold->isLeader()) { $hasLeader = true; break; } } if (!$hasLeader) { $eligibleKobolds = array_filter($this->getKobolds(), function ($kobold) { return $kobold->getAgeCategory() !== 'egg'; }); if (count($eligibleKobolds) >= 3) { $pickFromTier = function ($tier) { return array_values(array_filter($this->getKobolds(), function ($kobold) use ($tier) { return $kobold->getAgeCategory() === $tier; })); }; $candidatePools = [ $pickFromTier('adult'), $pickFromTier('old'), $pickFromTier('young') ]; $candidates = []; foreach ($candidatePools as $pool) { if (!empty($pool)) { $candidates = $pool; break; } } if (!empty($candidates)) { $scores = []; foreach ($candidates as $candidate) { $score = 0; foreach ($this->getKobolds() as $other) { if ($other->getId() === $candidate->getId()) { continue; } $likes = 0; if (isset($other->dataStore) && $other->dataStore instanceof stdClass) { if (isset($other->dataStore->likes) && is_array($other->dataStore->likes)) { $likes = (int) ($other->dataStore->likes[$candidate->getId()] ?? 0); } } $score += $likes; } $scores[$candidate->getId()] = $score; } $maxScore = max($scores); $topCandidates = array_values(array_filter($candidates, function ($candidate) use ($scores, $maxScore) { return $scores[$candidate->getId()] === $maxScore; })); if (count($topCandidates) > 1) { usort($topCandidates, function ($a, $b) { return $b->getAge() <=> $a->getAge(); }); $oldestAge = $topCandidates[0]->getAge(); $topCandidates = array_values(array_filter($topCandidates, function ($candidate) use ($oldestAge) { return $candidate->getAge() === $oldestAge; })); } $newLeader = $topCandidates[array_rand($topCandidates)]; $newLeader->setLeader(); $leaderName = $newLeader->getName(); $leaderStories = [ "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.", "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.", "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.", "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.", "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.", "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.", "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.", "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.", "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.", "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." ]; $foodStory .= "\n" . $leaderStories[array_rand($leaderStories)] . "\n"; } } } $this->save(); return $foodStory; } function ageKobold($kobold) { $foodStory = ""; if ($kobold->getAge() >= 0) { $kobold->incrementAge(); // Check for old-age injuries if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) { $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue']; $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)]; $kobold->addInjury($injury); } // Old-age death roll: if roll < (age + total injury severity), kobold dies if ($kobold->getAge() >= 35) { $roll = rand(1, 100); $totalSeverity = $kobold->getTotalInjurySeverity(); if ($roll < ($kobold->getAge() + $totalSeverity)) { $foodStory .= $kobold->getName() . " dies of old age.\n"; $this->cleanupDeadKoboldLikes($kobold->getId()); $kobold->die(); } } $kobold->save(); } return $foodStory; } private function shouldAddOldAgeInjury(Kobold $kobold) { // 1d100 roll under age starting at 35 $roll = rand(1, 100); return $roll <= $kobold->getAge(); } /** * Clean up all likes references to a kobold when they die * Removes the kobold's ID from all other kobolds' likes arrays * and from rival records */ private function cleanupDeadKoboldLikes($koboldId) { // Remove from all other kobolds' likes foreach ($this->kobolds as $other) { if ($other->getId() !== $koboldId) { if (!isset($other->dataStore)) { $other->dataStore = new stdClass(); } if (!isset($other->dataStore->likes)) { $other->dataStore->likes = []; } // Remove the dead kobold from this kobold's likes if (is_array($other->dataStore->likes)) { unset($other->dataStore->likes[$koboldId]); } } } // Remove from rivals' likes if they exist if (isset($this->dataStore->rivals) && is_array($this->dataStore->rivals)) { foreach ($this->dataStore->rivals as &$rival) { if (isset($rival['data']['likes']) && is_array($rival['data']['likes'])) { unset($rival['data']['likes'][$koboldId]); } } } } }