BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

tweaks
timfa Tim · pushed by timfa · 9 months ago
8bb1fbc6 History
Tribe.php 19.2 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 $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 tryMate()
416 {
417 $kobolds = array_values($this->getKobolds());
418 $count = count($kobolds);
419
420 if ($count === 0) {
421 return '';
422 }
423
424 $roll = rand(1, 30);
425 if ($roll <= $count) {
426 return '';
427 }
428
429 $males = array_values(array_filter($kobolds, fn($k) => $k->getMale() && $k->getAgeCategory() === 'adult'));
430 $females = array_values(array_filter($kobolds, fn($k) => !$k->getMale() && $k->getAgeCategory() === 'adult'));
431
432 if (empty($males) || empty($females)) {
433 return '';
434 }
435
436 $pair = null;
437 $attempts = 20;
438 while ($attempts-- > 0) {
439 $male = $males[array_rand($males)];
440 $female = $females[array_rand($females)];
441
442 $maleParents = $male->getParents();
443 $femaleParents = $female->getParents();
444
445 $sharedFather = !empty($maleParents['father_id']) && $maleParents['father_id'] === ($femaleParents['father_id'] ?? null);
446 $sharedMother = !empty($maleParents['mother_id']) && $maleParents['mother_id'] === ($femaleParents['mother_id'] ?? null);
447 $isMaleParent = $male->getId() === ($femaleParents['father_id'] ?? null) || $male->getId() === ($femaleParents['mother_id'] ?? null);
448 $isFemaleParent = $female->getId() === ($maleParents['father_id'] ?? null) || $female->getId() === ($maleParents['mother_id'] ?? null);
449
450 if ($sharedFather || $sharedMother || $isMaleParent || $isFemaleParent) {
451 continue;
452 }
453
454 $pair = [$male, $female];
455 break;
456 }
457
458 if (!$pair) {
459 return '';
460 }
461
462 [$male, $female] = $pair;
463
464 if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
465 return "{$male->getName()} and {$female->getName()} spent some of time together this month, but didn't quite hit it off.";
466 }
467
468 $child = Kobold::generate($this->userId, $this->saveId, -6);
469
470 $inheritRoll = rand(1, 100);
471 if ($inheritRoll <= 40) {
472 $child->setSpriteMorph($male->getSpriteMorph());
473 } elseif ($inheritRoll <= 80) {
474 $child->setSpriteMorph($female->getSpriteMorph());
475 }
476
477 $blendHex = function ($a, $b) {
478 $hexToRgb = function ($hex) {
479 $hex = ltrim($hex, '#');
480 return [
481 'r' => hexdec(substr($hex, 0, 2)),
482 'g' => hexdec(substr($hex, 2, 2)),
483 'b' => hexdec(substr($hex, 4, 2))
484 ];
485 };
486
487 $rgbToHex = function ($rgb) {
488 return sprintf('#%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']);
489 };
490
491 $ra = $hexToRgb($a);
492 $rb = $hexToRgb($b);
493 $ratio = rand(0, 100) / 100;
494
495 $offset = function () {
496 return rand(-20, 20);
497 };
498
499 $mix = function ($c1, $c2) use ($ratio, $offset) {
500 $val = (int) round(($c1 * $ratio) + ($c2 * (1 - $ratio)) + $offset());
501 return max(0, min(255, $val));
502 };
503
504 $mixed = [
505 'r' => $mix($ra['r'], $rb['r']),
506 'g' => $mix($ra['g'], $rb['g']),
507 'b' => $mix($ra['b'], $rb['b'])
508 ];
509
510 return $rgbToHex($mixed);
511 };
512
513 $maleColours = $male->getColours();
514 $femaleColours = $female->getColours();
515
516 $childPrimary = $blendHex($maleColours['primary'], $femaleColours['primary']);
517 $childSecondary = $blendHex($maleColours['secondary'], $femaleColours['secondary']);
518 $childTertiary = $blendHex($maleColours['tertiary'], $femaleColours['tertiary']);
519
520 $child->setColours($childPrimary, $childSecondary, $childTertiary);
521 $child->setParents($male->getId(), $female->getId());
522 $child->regenerateSprite();
523
524 $this->addKobold($child);
525
526 $pairName = $female->getName() . " and " . $male->getName();
527 $momName = $female->getName();
528 $variations = [
529 "{$pairName} spent a lot of time together this month. After a while, {$momName} laid an egg!",
530 "A quiet bond formed between {$pairName}, and soon {$momName} laid an egg.",
531 "The tribe whispers as {$pairName} draw close. By month's end, {$momName} laid an egg.",
532 "Under the clan's watchful eyes, {$pairName} grew inseparable, and {$momName} laid an egg.",
533 "After many shared moments, {$pairName} welcomed a new egg from {$momName}.",
534 "A spark passed between {$pairName}. Before the month ended, {$momName} laid an egg.",
535 "The camp celebrates softly as {$pairName} brought new life—{$momName} laid an egg.",
536 "Fortunate days came for {$pairName}; the month closes with {$momName} laying an egg.",
537 "The tribe smiles as {$pairName} found harmony, and {$momName} laid an egg.",
538 "Among the kobolds, {$pairName} share a rare warmth, and {$momName} laid an egg."
539 ];
540
541 return $variations[array_rand($variations)];
542 }
543
544 public function endMonth()
545 {
546 $this->currentMonth++;
547
548 foreach ($this->kobolds as $kobold) {
549 $kobold->resetFatigue();
550 }
551
552 $seasons = ['spring', 'summer', 'autumn', 'winter'];
553
554 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
555 $index = intdiv($monthOfYear - 1, 3);
556
557 $this->currentSeason = $seasons[$index];
558 // Random month events happen here (handled by EventManager in API)
559 // After events, consume food
560
561
562
563 // age eggs
564 $foodStory = "A month passes...\n" . $this->consumeFood();
565 $foodStory .= "\n";
566
567 foreach ($this->kobolds as $kobold) {
568 if ($kobold->getAge() < 0) {
569 $kobold->incrementAge();
570
571 if ($kobold->getAge() >= 0) {
572 $kobold->setName(Kobold::generateRandomName());
573 $foodStory .= "An egg hatched! {$kobold->getName()} was born.\n";
574 }
575
576 $kobold->save();
577 }
578 }
579
580 // Age all kobolds
581 if ($this->currentMonth % 12 === 0) {
582 $foodStory .= "\nA new year begins.\n";
583
584 foreach ($this->kobolds as $kobold) {
585 if ($kobold->getAge() >= 0) {
586 $kobold->incrementAge();
587
588 // Check for old-age injuries
589 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
590 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia', 'limp', 'poor_hearing', 'chronic_fatigue'];
591 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
592 $kobold->addInjury($injury);
593 }
594
595 // Old-age death roll: if roll < (age + total injury severity), kobold dies
596 if ($kobold->getAge() >= 35) {
597 $roll = rand(1, 100);
598 $totalSeverity = $kobold->getTotalInjurySeverity();
599 if ($roll < ($kobold->getAge() + $totalSeverity)) {
600 $foodStory .= $kobold->getName() . " dies of old age.\n";
601 $kobold->die();
602 }
603 }
604
605 $kobold->save();
606 }
607 }
608 }
609 $foodStory .= "\n" . $this->tryMate();
610 $foodStory .= "\nIt's {$this->currentSeason}.\n";
611
612 foreach ($this->kobolds as $kobold) {
613 if ($kobold->isDead()) {
614 $story = $story . "\n" . $kobold->getName() . " has died.";
615 }
616 }
617
618 $this->save();
619
620 return $foodStory;
621 }
622
623 private function shouldAddOldAgeInjury(Kobold $kobold)
624 {
625 // 1d100 roll under age starting at 35
626 $roll = rand(1, 100);
627 return $roll <= $kobold->getAge();
628 }
629}