| 1 | <?php |
| 2 | |
| 3 | require_once __DIR__ . '/../../src/System/SaveManager.php'; |
| 4 | require_once __DIR__ . '/../../src/Classes/Kobold.php'; |
| 5 | |
| 6 | class Tribe |
| 7 | { |
| 8 | private $userId; |
| 9 | private $saveId; |
| 10 | private $name; |
| 11 | public $kobolds = []; |
| 12 | private $storage = []; |
| 13 | private $currentMonth = 0; |
| 14 | private $currentSeason = 'spring'; |
| 15 | private $foodCount = 0; |
| 16 | private $createdAt; |
| 17 | private $lastPlayed; |
| 18 | private $saveManager; |
| 19 | |
| 20 | // Food requirement by age tier (portion units) |
| 21 | public $foodRequirements = [ |
| 22 | 'egg' => 0, |
| 23 | 'baby' => 1, |
| 24 | 'young' => 2, |
| 25 | 'adult' => 3, |
| 26 | 'old' => 2 |
| 27 | ]; |
| 28 | |
| 29 | public function __construct($userId, $saveId, $name = '') |
| 30 | { |
| 31 | $this->userId = $userId; |
| 32 | $this->saveId = $saveId; |
| 33 | $this->name = $name; |
| 34 | $this->saveManager = new SaveManager(); |
| 35 | $this->loadFromFile(); |
| 36 | } |
| 37 | |
| 38 | public static function create($userId, $saveName) |
| 39 | { |
| 40 | $saveManager = new SaveManager(); |
| 41 | $saveId = $saveManager->generateSaveId($userId); |
| 42 | |
| 43 | $tribe = new self($userId, $saveId, $saveName); |
| 44 | $tribe->createdAt = date('Y-m-d H:i:s'); |
| 45 | $tribe->lastPlayed = date('Y-m-d H:i:s'); |
| 46 | $tribe->save(); |
| 47 | |
| 48 | return $tribe; |
| 49 | } |
| 50 | |
| 51 | public static function load($userId, $saveId) |
| 52 | { |
| 53 | return new self($userId, $saveId); |
| 54 | } |
| 55 | |
| 56 | private function loadFromFile() |
| 57 | { |
| 58 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 59 | $saveFile = $savePath . '/save.json'; |
| 60 | |
| 61 | if (file_exists($saveFile)) { |
| 62 | $data = $this->saveManager->loadJson($saveFile); |
| 63 | |
| 64 | if ($data) { |
| 65 | $this->name = $data['name'] ?? ''; |
| 66 | $this->currentMonth = $data['current_month'] ?? 0; |
| 67 | $this->currentSeason = $data['current_season'] ?? 'spring'; |
| 68 | $this->foodCount = $data['food_count'] ?? 0; |
| 69 | $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s'); |
| 70 | $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s'); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | $this->loadKobolds(); |
| 75 | $this->loadStorage(); |
| 76 | } |
| 77 | |
| 78 | private function loadKobolds() |
| 79 | { |
| 80 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 81 | $koboldsFile = $savePath . '/kobolds.json'; |
| 82 | |
| 83 | $this->kobolds = []; |
| 84 | |
| 85 | if (file_exists($koboldsFile)) { |
| 86 | $data = $this->saveManager->loadJson($koboldsFile); |
| 87 | |
| 88 | if ($data && is_array($data)) { |
| 89 | foreach ($data as $koboldData) { |
| 90 | $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId); |
| 91 | if ($kobold) { |
| 92 | $this->kobolds[$kobold->getId()] = $kobold; |
| 93 | } |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | private function loadStorage() |
| 100 | { |
| 101 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 102 | $itemsFile = $savePath . '/items.json'; |
| 103 | |
| 104 | $this->storage = []; |
| 105 | |
| 106 | if (file_exists($itemsFile)) { |
| 107 | $this->storage = $this->saveManager->loadJson($itemsFile) ?? []; |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | public function save() |
| 112 | { |
| 113 | $this->lastPlayed = date('Y-m-d H:i:s'); |
| 114 | |
| 115 | $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId); |
| 116 | |
| 117 | // Save tribe metadata |
| 118 | $tribeData = [ |
| 119 | 'name' => $this->name, |
| 120 | 'current_month' => $this->currentMonth, |
| 121 | 'current_season' => $this->currentSeason, |
| 122 | 'food_count' => $this->foodCount, |
| 123 | 'food_months_left' => $this->foodMonthsLeft($this->foodCount), |
| 124 | 'created_at' => $this->createdAt, |
| 125 | 'last_played' => $this->lastPlayed |
| 126 | ]; |
| 127 | |
| 128 | $this->saveManager->saveJson($savePath . '/save.json', $tribeData); |
| 129 | |
| 130 | // Save kobolds |
| 131 | $koboldsData = []; |
| 132 | foreach ($this->kobolds as $kobold) { |
| 133 | if (!$kobold->isDead()) { |
| 134 | $kobold->save(); |
| 135 | $koboldsData[] = $kobold->toArray(); |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData); |
| 140 | |
| 141 | // Save items |
| 142 | $this->saveManager->saveJson($savePath . '/items.json', $this->storage); |
| 143 | |
| 144 | GameHelper::cleanupUnusedKoboldSprites($this->userId); |
| 145 | } |
| 146 | |
| 147 | // Getters and Setters |
| 148 | public function getName() |
| 149 | { |
| 150 | return $this->name; |
| 151 | } |
| 152 | |
| 153 | public function setName($name) |
| 154 | { |
| 155 | $this->name = $name; |
| 156 | } |
| 157 | |
| 158 | public function getSaveId() |
| 159 | { |
| 160 | return $this->saveId; |
| 161 | } |
| 162 | |
| 163 | public function getUserId() |
| 164 | { |
| 165 | return $this->userId; |
| 166 | } |
| 167 | |
| 168 | public function getCreatedAt() |
| 169 | { |
| 170 | return $this->createdAt; |
| 171 | } |
| 172 | |
| 173 | public function getLastPlayed() |
| 174 | { |
| 175 | return $this->lastPlayed; |
| 176 | } |
| 177 | |
| 178 | public function getCurrentMonth() |
| 179 | { |
| 180 | return $this->currentMonth; |
| 181 | } |
| 182 | |
| 183 | public function setCurrentMonth($month) |
| 184 | { |
| 185 | $this->currentMonth = max(0, $month); |
| 186 | } |
| 187 | |
| 188 | public function getCurrentSeason() |
| 189 | { |
| 190 | return $this->currentSeason; |
| 191 | } |
| 192 | |
| 193 | public function setCurrentSeason($season) |
| 194 | { |
| 195 | $this->currentSeason = $season; |
| 196 | } |
| 197 | |
| 198 | // Kobold management |
| 199 | public function getKobolds($includeDeadAndExpelled = false) |
| 200 | { |
| 201 | if ($includeDeadAndExpelled) { |
| 202 | return $this->kobolds; |
| 203 | } |
| 204 | |
| 205 | return array_filter($this->kobolds, function (Kobold $k) { |
| 206 | return !$k->isDead() && !$k->isExpelled(); |
| 207 | }); |
| 208 | } |
| 209 | |
| 210 | public function getKobold($id) |
| 211 | { |
| 212 | return $this->kobolds[$id] ?? null; |
| 213 | } |
| 214 | |
| 215 | public function addKobold(Kobold $kobold) |
| 216 | { |
| 217 | $this->kobolds[$kobold->getId()] = $kobold; |
| 218 | return $kobold; |
| 219 | } |
| 220 | |
| 221 | public function removeKobold($id) |
| 222 | { |
| 223 | unset($this->kobolds[$id]); |
| 224 | } |
| 225 | |
| 226 | public function getAliveKobolds() |
| 227 | { |
| 228 | return array_filter($this->kobolds, fn($k) => !$k->isDead()); |
| 229 | } |
| 230 | |
| 231 | // Storage management |
| 232 | public function addToStorage(Item $item, int $count = 1): array |
| 233 | { |
| 234 | // Accept either Item object or array |
| 235 | if (is_object($item) && method_exists($item, 'toArray')) { |
| 236 | $this->storage[] = $item->toArray(); |
| 237 | } elseif (is_array($item)) { |
| 238 | // Ensure it has an id |
| 239 | if (!isset($item['id'])) { |
| 240 | $item['id'] = uniqid('itm_'); |
| 241 | } |
| 242 | for ($i = 0; $i < $count; $i++) |
| 243 | $this->storage[] = $item; |
| 244 | } |
| 245 | return $this->storage; |
| 246 | } |
| 247 | |
| 248 | public function getStorage() |
| 249 | { |
| 250 | return $this->storage; |
| 251 | } |
| 252 | |
| 253 | // Food system methods |
| 254 | public function getFoodCount() |
| 255 | { |
| 256 | return $this->foodCount; |
| 257 | } |
| 258 | |
| 259 | public function addFood($amount) |
| 260 | { |
| 261 | $this->foodCount += $amount; |
| 262 | return $this->foodCount; |
| 263 | } |
| 264 | |
| 265 | public function removeFood($amount) |
| 266 | { |
| 267 | $this->foodCount = max(0, $this->foodCount - $amount); |
| 268 | return $this->foodCount; |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Calculate total food needed for all alive kobolds for one month |
| 273 | */ |
| 274 | public function calculateFoodNeeded() |
| 275 | { |
| 276 | $needed = 0; |
| 277 | |
| 278 | foreach ($this->getAliveKobolds() as $kobold) { |
| 279 | $ageCategory = $kobold->getAgeCategory(); |
| 280 | $requirement = $this->foodRequirements[$ageCategory] ?? 1.0; |
| 281 | $needed += $requirement; |
| 282 | } |
| 283 | |
| 284 | return $needed; |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * Calculate how many full months the current kobolds can be fed |
| 289 | * with the provided amount of food. |
| 290 | */ |
| 291 | public function foodMonthsLeft($amount) |
| 292 | { |
| 293 | $foodPerMonth = $this->calculateFoodNeeded(); |
| 294 | if ($foodPerMonth <= 0) { |
| 295 | return 0; |
| 296 | } |
| 297 | |
| 298 | $available = max(0, (float) $amount); |
| 299 | return (int) floor($available / $foodPerMonth); |
| 300 | } |
| 301 | |
| 302 | /** |
| 303 | * Get food requirement for a specific kobold |
| 304 | */ |
| 305 | public function getFoodRequirement(Kobold $kobold) |
| 306 | { |
| 307 | $ageCategory = $kobold->getAgeCategory(); |
| 308 | return $this->foodRequirements[$ageCategory] ?? 1.0; |
| 309 | } |
| 310 | |
| 311 | /** |
| 312 | * Consume food at end of month after events |
| 313 | * Prioritizes: malnourished kobolds first, then younger before older |
| 314 | * Returns story of food consumption and any starvations |
| 315 | */ |
| 316 | public function consumeFood() |
| 317 | { |
| 318 | $story = ""; |
| 319 | $aliveKobolds = $this->getAliveKobolds(); |
| 320 | |
| 321 | if (empty($aliveKobolds)) { |
| 322 | return $story; |
| 323 | } |
| 324 | |
| 325 | // Sort kobolds: malnourished first, then by age (younger first) |
| 326 | usort($aliveKobolds, function ($a, $b) { |
| 327 | // Check for malnourished injury |
| 328 | $aMalnourished = $this->hasInjuryCategory($a, 'malnourished'); |
| 329 | $bMalnourished = $this->hasInjuryCategory($b, 'malnourished'); |
| 330 | |
| 331 | if ($aMalnourished && !$bMalnourished) |
| 332 | return -1; |
| 333 | if (!$aMalnourished && $bMalnourished) |
| 334 | return 1; |
| 335 | |
| 336 | // Both have or both don't have malnourished |
| 337 | // Younger first (lower age = higher priority) |
| 338 | return $a->getAge() - $b->getAge(); |
| 339 | }); |
| 340 | |
| 341 | $fedKobolds = []; |
| 342 | $starvedKobolds = []; |
| 343 | |
| 344 | foreach ($aliveKobolds as $kobold) { |
| 345 | $needed = $this->getFoodRequirement($kobold); |
| 346 | |
| 347 | if ($this->foodCount >= $needed) { |
| 348 | // Fed this kobold |
| 349 | $this->foodCount -= $needed; |
| 350 | $fedKobolds[$kobold->getId()] = $kobold; |
| 351 | |
| 352 | // If malnourished, cure it |
| 353 | if ($this->hasInjuryCategory($kobold, 'malnourished')) { |
| 354 | $this->removeMalnourishedInjury($kobold); |
| 355 | $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n"; |
| 356 | } |
| 357 | } else { |
| 358 | // Not enough food - starve this kobold |
| 359 | $starvedKobolds[$kobold->getId()] = $kobold; |
| 360 | $this->foodCount = 0; // Use remaining food |
| 361 | |
| 362 | // Add malnourished injury if not already present |
| 363 | if (!$this->hasInjuryCategory($kobold, 'malnourished')) { |
| 364 | $kobold->addInjury('malnourished'); |
| 365 | $story .= "{$kobold->getName()} went hungry and became malnourished.\n"; |
| 366 | } else { |
| 367 | // Already malnourished - becomes more severe |
| 368 | $injuries = $kobold->getInjuries(); |
| 369 | foreach ($injuries as $injury) { |
| 370 | if ($injury['category'] === 'malnourished') { |
| 371 | $injury['severity']++; |
| 372 | $story .= "{$kobold->getName()} remained hungry and suffered.\n"; |
| 373 | break; |
| 374 | } |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | // Save updated kobolds |
| 381 | foreach ($aliveKobolds as $kobold) { |
| 382 | $kobold->save(); |
| 383 | } |
| 384 | |
| 385 | return $story; |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Check if a kobold has an injury in a specific category |
| 390 | */ |
| 391 | private function hasInjuryCategory(Kobold $kobold, $category) |
| 392 | { |
| 393 | $injuries = $kobold->getInjuries(); |
| 394 | foreach ($injuries as $injury) { |
| 395 | if ($injury['category'] === $category) { |
| 396 | return true; |
| 397 | } |
| 398 | } |
| 399 | return false; |
| 400 | } |
| 401 | |
| 402 | /** |
| 403 | * Remove all malnourished injuries from a kobold |
| 404 | */ |
| 405 | private function removeMalnourishedInjury(Kobold $kobold) |
| 406 | { |
| 407 | $injuries = $kobold->getInjuries(); |
| 408 | foreach ($injuries as $injury) { |
| 409 | if ($injury['category'] === 'malnourished') { |
| 410 | $kobold->removeInjury($injury['id']); |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | public function endMonth() |
| 416 | { |
| 417 | $this->currentMonth++; |
| 418 | |
| 419 | foreach ($this->kobolds as $kobold) { |
| 420 | $kobold->resetFatigue(); |
| 421 | } |
| 422 | |
| 423 | $seasons = ['spring', 'summer', 'autumn', 'winter']; |
| 424 | |
| 425 | $monthOfYear = (($this->currentMonth - 1) % 12) + 1; |
| 426 | $index = intdiv($monthOfYear - 1, 3); |
| 427 | |
| 428 | $this->currentSeason = $seasons[$index]; |
| 429 | // Random month events happen here (handled by EventManager in API) |
| 430 | // After events, consume food |
| 431 | |
| 432 | |
| 433 | |
| 434 | // age eggs |
| 435 | $foodStory = "A month passes...\n" . $this->consumeFood(); |
| 436 | $foodStory .= "\n"; |
| 437 | |
| 438 | foreach ($this->kobolds as $kobold) { |
| 439 | if ($kobold->getAge() < 0) { |
| 440 | $kobold->incrementAge(); |
| 441 | |
| 442 | if ($kobold->getAge() >= 0) { |
| 443 | $kobold->setName(Kobold::generateRandomName()); |
| 444 | $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n"; |
| 445 | } |
| 446 | |
| 447 | $kobold->save(); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | // Age all kobolds |
| 452 | if ($this->currentMonth % 12 === 0) { |
| 453 | $foodStory .= "\nA new year begins.\n"; |
| 454 | |
| 455 | foreach ($this->kobolds as $kobold) { |
| 456 | if ($kobold->getAge() >= 0) { |
| 457 | $kobold->incrementAge(); |
| 458 | |
| 459 | // Check for old-age injuries |
| 460 | if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) { |
| 461 | $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue']; |
| 462 | $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)]; |
| 463 | $kobold->addInjury($injury); |
| 464 | } |
| 465 | |
| 466 | // Old-age death roll: if roll < (age + total injury severity), kobold dies |
| 467 | if ($kobold->getAge() >= 35) { |
| 468 | $roll = rand(1, 100); |
| 469 | $totalSeverity = $kobold->getTotalInjurySeverity(); |
| 470 | if ($roll < ($kobold->getAge() + $totalSeverity)) { |
| 471 | $foodStory .= $kobold->getName() . " dies of old age.\n"; |
| 472 | $kobold->die(); |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | $kobold->save(); |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | $foodStory .= "\nIt's {$this->currentSeason}.\n"; |
| 481 | |
| 482 | foreach ($this->kobolds as $kobold) { |
| 483 | if ($kobold->isDead()) { |
| 484 | $story = $story . "\n" . $kobold->getName() . " has died."; |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | $this->save(); |
| 489 | |
| 490 | return $foodStory; |
| 491 | } |
| 492 | |
| 493 | private function shouldAddOldAgeInjury(Kobold $kobold) |
| 494 | { |
| 495 | // 1d100 roll under age starting at 35 |
| 496 | $roll = rand(1, 100); |
| 497 | return $roll <= $kobold->getAge(); |
| 498 | } |
| 499 | } |