BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

63fe0a91 History
Tribe.php 20.6 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 private $storage = [];
13 private $currentMonth = 0;
14 private $currentSeason = 'spring';
15 private $foodCount = 0;
16 private $environmentId = null;
17 private $createdAt;
18 private $lastPlayed;
19 private $saveManager;
20
21 // Food requirement by age tier (portion units)
22 public $foodRequirements = [
23 'egg' => 0,
24 'baby' => 1,
25 'young' => 2,
26 'adult' => 3,
27 'old' => 2
28 ];
29
30 public function __construct($userId, $saveId, $name = '')
31 {
32 $this->userId = $userId;
33 $this->saveId = $saveId;
34 $this->name = $name;
35 $this->saveManager = new SaveManager();
36 $this->loadFromFile();
37 }
38
39 public static function create($userId, $saveName)
40 {
41 $saveManager = new SaveManager();
42 $saveId = $saveManager->generateSaveId($userId);
43
44 $tribe = new self($userId, $saveId, $saveName);
45 $tribe->createdAt = date('Y-m-d H:i:s');
46 $tribe->lastPlayed = date('Y-m-d H:i:s');
47 $tribe->save();
48
49 return $tribe;
50 }
51
52 public static function load($userId, $saveId)
53 {
54 return new self($userId, $saveId);
55 }
56
57 private function loadFromFile()
58 {
59 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
60 $saveFile = $savePath . '/save.json';
61
62 if (file_exists($saveFile)) {
63 $data = $this->saveManager->loadJson($saveFile);
64
65 if ($data) {
66 $this->name = $data['name'] ?? '';
67 $this->currentMonth = $data['current_month'] ?? 0;
68 $this->currentSeason = $data['current_season'] ?? 'spring';
69 $this->foodCount = $data['food_count'] ?? 0;
70 $this->environmentId = $data['environment_id'] ?? null;
71 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
72 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
73 }
74 }
75
76 $this->loadKobolds();
77 $this->loadStorage();
78 }
79
80 private function loadKobolds()
81 {
82 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
83 $koboldsFile = $savePath . '/kobolds.json';
84
85 $this->kobolds = [];
86
87 if (file_exists($koboldsFile)) {
88 $data = $this->saveManager->loadJson($koboldsFile);
89
90 if ($data && is_array($data)) {
91 foreach ($data as $koboldData) {
92 $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId);
93 if ($kobold) {
94 $this->kobolds[$kobold->getId()] = $kobold;
95 }
96 }
97 }
98 }
99 }
100
101 private function loadStorage()
102 {
103 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
104 $itemsFile = $savePath . '/items.json';
105
106 $this->storage = [];
107
108 if (file_exists($itemsFile)) {
109 $this->storage = $this->saveManager->loadJson($itemsFile) ?? [];
110 }
111 }
112
113 public function save()
114 {
115 $this->lastPlayed = date('Y-m-d H:i:s');
116
117 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
118
119 // Save tribe metadata
120 $tribeData = [
121 'name' => $this->name,
122 'current_month' => $this->currentMonth,
123 'current_season' => $this->currentSeason,
124 'food_count' => $this->foodCount,
125 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
126 'environment_id' => $this->environmentId,
127 'created_at' => $this->createdAt,
128 'last_played' => $this->lastPlayed
129 ];
130
131 $this->saveManager->saveJson($savePath . '/save.json', $tribeData);
132
133 // Save kobolds
134 $koboldsData = [];
135 foreach ($this->kobolds as $kobold) {
136 if (!$kobold->isDead()) {
137 $kobold->save();
138 $koboldsData[] = $kobold->toArray();
139 }
140 }
141
142 $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData);
143
144 // Save items
145 $this->saveManager->saveJson($savePath . '/items.json', $this->storage);
146
147 GameHelper::cleanupUnusedKoboldSprites($this->userId);
148 }
149
150 // Getters and Setters
151 public function getName()
152 {
153 return $this->name;
154 }
155
156 public function setName($name)
157 {
158 $this->name = $name;
159 }
160
161 public function getSaveId()
162 {
163 return $this->saveId;
164 }
165
166 public function getUserId()
167 {
168 return $this->userId;
169 }
170
171 public function getCreatedAt()
172 {
173 return $this->createdAt;
174 }
175
176 public function getLastPlayed()
177 {
178 return $this->lastPlayed;
179 }
180
181 public function getCurrentMonth()
182 {
183 return $this->currentMonth;
184 }
185
186 public function setCurrentMonth($month)
187 {
188 $this->currentMonth = max(0, $month);
189 }
190
191 public function getCurrentSeason()
192 {
193 return $this->currentSeason;
194 }
195
196 public function setCurrentSeason($season)
197 {
198 $this->currentSeason = $season;
199 }
200
201 public function getEnvironmentId()
202 {
203 return $this->environmentId;
204 }
205
206 public function setEnvironmentId($environmentId)
207 {
208 $this->environmentId = $environmentId;
209 }
210
211 // Kobold management
212 public function getKobolds($includeDeadAndExpelled = false)
213 {
214 if ($includeDeadAndExpelled) {
215 return $this->kobolds;
216 }
217
218 return array_filter($this->kobolds, function (Kobold $k) {
219 return !$k->isDead() && !$k->isExpelled();
220 });
221 }
222
223 public function getKobold($id)
224 {
225 return $this->kobolds[$id] ?? null;
226 }
227
228 public function addKobold(Kobold $kobold)
229 {
230 $this->kobolds[$kobold->getId()] = $kobold;
231 return $kobold;
232 }
233
234 public function removeKobold($id)
235 {
236 unset($this->kobolds[$id]);
237 }
238
239 public function getAliveKobolds()
240 {
241 return array_filter($this->kobolds, fn($k) => !$k->isDead());
242 }
243
244 // Storage management
245 public function addToStorage(Item $item, int $count = 1): array
246 {
247 // Accept either Item object or array
248 if (is_object($item) && method_exists($item, 'toArray')) {
249 $this->storage[] = $item->toArray();
250 } elseif (is_array($item)) {
251 // Ensure it has an id
252 if (!isset($item['id'])) {
253 $item['id'] = uniqid('itm_');
254 }
255 for ($i = 0; $i < $count; $i++)
256 $this->storage[] = $item;
257 }
258 return $this->storage;
259 }
260
261 public function getStorage()
262 {
263 return $this->storage;
264 }
265
266 // Food system methods
267 public function getFoodCount()
268 {
269 return $this->foodCount;
270 }
271
272 public function addFood($amount)
273 {
274 $this->foodCount += $amount;
275 return $this->foodCount;
276 }
277
278 public function removeFood($amount)
279 {
280 $this->foodCount = max(0, $this->foodCount - $amount);
281 return $this->foodCount;
282 }
283
284 /**
285 * Calculate total food needed for all alive kobolds for one month
286 */
287 public function calculateFoodNeeded()
288 {
289 $needed = 0;
290
291 foreach ($this->getAliveKobolds() as $kobold) {
292 $ageCategory = $kobold->getAgeCategory();
293 $requirement = $this->foodRequirements[$ageCategory] ?? 1.0;
294 $needed += $requirement;
295 }
296
297 return $needed;
298 }
299
300 /**
301 * Calculate how many full months the current kobolds can be fed
302 * with the provided amount of food.
303 */
304 public function foodMonthsLeft($amount)
305 {
306 $foodPerMonth = $this->calculateFoodNeeded();
307 if ($foodPerMonth <= 0) {
308 return 0;
309 }
310
311 $available = max(0, (float) $amount);
312 return (int) floor($available / $foodPerMonth);
313 }
314
315 /**
316 * Get food requirement for a specific kobold
317 */
318 public function getFoodRequirement(Kobold $kobold)
319 {
320 $ageCategory = $kobold->getAgeCategory();
321 return $this->foodRequirements[$ageCategory] ?? 1.0;
322 }
323
324 /**
325 * Consume food at end of month after events
326 * Prioritizes: malnourished kobolds first, then younger before older
327 * Returns story of food consumption and any starvations
328 */
329 public function consumeFood()
330 {
331 $story = "";
332 $aliveKobolds = $this->getAliveKobolds();
333
334 if (empty($aliveKobolds)) {
335 return $story;
336 }
337
338 // Sort kobolds: malnourished first, then by age (younger first)
339 usort($aliveKobolds, function ($a, $b) {
340 // Check for malnourished injury
341 $aMalnourished = $this->hasInjuryCategory($a, 'malnourished');
342 $bMalnourished = $this->hasInjuryCategory($b, 'malnourished');
343
344 if ($aMalnourished && !$bMalnourished)
345 return -1;
346 if (!$aMalnourished && $bMalnourished)
347 return 1;
348
349 // Both have or both don't have malnourished
350 // Younger first (lower age = higher priority)
351 return $a->getAge() - $b->getAge();
352 });
353
354 $fedKobolds = [];
355 $starvedKobolds = [];
356
357 foreach ($aliveKobolds as $kobold) {
358 $needed = $this->getFoodRequirement($kobold);
359
360 if ($this->foodCount >= $needed) {
361 // Fed this kobold
362 $this->foodCount -= $needed;
363 $fedKobolds[$kobold->getId()] = $kobold;
364
365 // If malnourished, cure it
366 if ($this->hasInjuryCategory($kobold, 'malnourished')) {
367 $this->removeMalnourishedInjury($kobold);
368 $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n";
369 }
370 } else {
371 // Not enough food - starve this kobold
372 $starvedKobolds[$kobold->getId()] = $kobold;
373 $this->foodCount = 0; // Use remaining food
374
375
376 $malnourishedId = $this->getMalnourishedInjuryId($kobold);
377 if (!$malnourishedId) {
378 $kobold->addInjury('malnourished-slight');
379 $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
380 } else {
381 if ($malnourishedId === 'malnourished-slight') {
382 $kobold->removeInjury($malnourishedId);
383 $kobold->addInjury('malnourished-mild');
384 $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
385 } elseif ($malnourishedId === 'malnourished-mild') {
386 $kobold->removeInjury($malnourishedId);
387 $kobold->addInjury('malnourished-severe');
388 $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
389 } elseif ($malnourishedId === 'malnourished-severe') {
390 $kobold->removeInjury($malnourishedId);
391 $kobold->addInjury('malnourished-brink');
392 $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
393 } elseif ($malnourishedId === 'malnourished-brink') {
394 $kobold->die();
395 $story .= "{$kobold->getName()} succumbed to starvation.\n";
396 }
397 }
398 }
399 }
400
401 // Save updated kobolds
402 foreach ($aliveKobolds as $kobold) {
403 $kobold->save();
404 }
405
406 return $story;
407 }
408
409 /**
410 * Check if a kobold has an injury in a specific category
411 */
412 private function hasInjuryCategory(Kobold $kobold, $category)
413 {
414 $injuries = $kobold->getInjuries();
415 foreach ($injuries as $injury) {
416 if ($injury['category'] === $category) {
417 return true;
418 }
419 }
420 return false;
421 }
422
423 /**
424 * Remove all malnourished injuries from a kobold
425 */
426 private function removeMalnourishedInjury(Kobold $kobold)
427 {
428 $injuries = $kobold->getInjuries();
429 foreach ($injuries as $injury) {
430 if ($injury['category'] === 'malnourished') {
431 $kobold->removeInjury($injury['id']);
432 }
433 }
434 }
435
436 /**
437 * Get current malnourished injury id if present
438 */
439 private function getMalnourishedInjuryId(Kobold $kobold)
440 {
441 $injuries = $kobold->getInjuries();
442 foreach ($injuries as $injury) {
443 if (($injury['category'] ?? null) === 'malnourished') {
444 return $injury['id'] ?? null;
445 }
446 }
447 return null;
448 }
449
450 public function tryMate()
451 {
452 $kobolds = array_values($this->getKobolds());
453 $count = count($kobolds);
454
455 if ($count === 0) {
456 return '';
457 }
458
459 $roll = rand(1, 30);
460 if ($roll <= $count) {
461 return '';
462 }
463
464 $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
465 $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));
466
467 if (empty($males) || empty($females)) {
468 return '';
469 }
470
471 $pair = null;
472 $attempts = 20;
473 while ($attempts-- > 0) {
474 $male = $males[array_rand($males)];
475 $female = $females[array_rand($females)];
476
477 $maleParents = $male->getParents();
478 $femaleParents = $female->getParents();
479
480 $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
481 $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
482 $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
483 $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);
484
485 if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
486 continue;
487 }
488
489 $pair = [$male, $female];
490 break;
491 }
492
493 if (!$pair) {
494 return '';
495 }
496
497 [$male, $female] = $pair;
498
499 if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
500 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
501 }
502
503 $child = Kobold::generate($this->userId, $this->saveId, -6);
504
505 $inheritRoll = rand(1, 100);
506 if ($inheritRoll <= 40) {
507 $child->setSpriteMorph($male->getSpriteMorph());
508 } elseif ($inheritRoll <= 80) {
509 $child->setSpriteMorph($female->getSpriteMorph());
510 }
511
512 $blendHex = function ($a, $b) {
513 $hexToRgb = function ($hex) {
514 $hex = ltrim($hex, '#');
515 return [
516 'r' => hexdec(substr($hex, 0, 2)),
517 'g' => hexdec(substr($hex, 2, 2)),
518 'b' => hexdec(substr($hex, 4, 2))
519 ];
520 };
521
522 $rgbToHex = function ($rgb) {
523 return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
524 };
525
526 $ra = $hexToRgb($a);
527 $rb = $hexToRgb($b);
528 $ratio = rand(0, 100) / 100;
529
530 $offset = function () {
531 return rand(-20, 20);
532 };
533
534 $mix = function ($c1, $c2) use ($ratio, $offset) {
535 $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
536 return max(0, min(255, $val));
537 };
538
539 $mixed = [
540 'r' => $mix($ra['r'], $rb['r']),
541 'g' => $mix($ra['g'], $rb['g']),
542 'b' => $mix($ra['b'], $rb['b'])
543 ];
544
545 return $rgbToHex($mixed);
546 };
547
548 $maleColours = $male->getColours();
549 $femaleColours = $female->getColours();
550
551 $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
552 $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
553 $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);
554
555 $child->setColours($childPrimary, $childSecondary, $childTertiary);
556 $child->setParents($male->getId(), $female->getId());
557 $child->regenerateSprite();
558
559 $this->addKobold($child);
560
561 $pairName = $female->getName() . " and " . $male->getName();
562 $momName = $female->getName();
563 $variations = [
564 "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
565 "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
566 "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
567 "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
568 "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
569 "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
570 "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
571 "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
572 "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
573 "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
574 ];
575
576 return $variations[array_rand($variations)];
577 }
578
579 public function endMonth()
580 {
581 $this->currentMonth++;
582
583 foreach ($this->kobolds as $kobold) {
584 $kobold->resetFatigue();
585 }
586
587 $seasons = ['spring', 'summer', 'autumn', 'winter'];
588
589 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
590 $index = intdiv($monthOfYear - 1, 3);
591
592 $this->currentSeason = $seasons[$index];
593 // Random month events happen here (handled by EventManager in API)
594 // After events, consume food
595
596
597
598 // age eggs
599 $foodStory = "A month passes...\n" . $this->consumeFood();
600 $foodStory .= "\n";
601
602 foreach ($this->kobolds as $kobold) {
603 if ($kobold->getAge() < 0) {
604 $kobold->incrementAge();
605
606 if ($kobold->getAge() >= 0) {
607 $kobold->setName(Kobold::generateRandomName());
608 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
609 }
610
611 $kobold->save();
612 }
613 }
614
615 // Age all kobolds
616 if ($this->currentMonth % 12 === 0) {
617 $foodStory .= "\nA new year begins.\n";
618
619 foreach ($this->kobolds as $kobold) {
620 if ($kobold->getAge() >= 0) {
621 $kobold->incrementAge();
622
623 // Check for old-age injuries
624 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
625 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
626 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
627 $kobold->addInjury($injury);
628 }
629
630 // Old-age death roll: if roll < (age + total injury severity), kobold dies
631 if ($kobold->getAge() >= 35) {
632 $roll = rand(1, 100);
633 $totalSeverity = $kobold->getTotalInjurySeverity();
634 if ($roll < ($kobold->getAge() + $totalSeverity)) {
635 $foodStory .= $kobold->getName() . " dies of old age.\n";
636 $kobold->die();
637 }
638 }
639
640 $kobold->save();
641 }
642 }
643 }
644 $foodStory .= "\n" . $this->tryMate();
645 $foodStory .= "\nIt's {$this->currentSeason}.\n";
646
647 foreach ($this->kobolds as $kobold) {
648 if ($kobold->isDead()) {
649 $foodStory = $foodStory . "\n" . $kobold->getName() . " has died.";
650 }
651 }
652
653 $this->save();
654
655 return $foodStory;
656 }
657
658 private function shouldAddOldAgeInjury(Kobold $kobold)
659 {
660 // 1d100 roll under age starting at 35
661 $roll = rand(1, 100);
662 return $roll <= $kobold->getAge();
663 }
664}