BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

test
timfa Tim Falken · pushed by timfa · 9 months ago
6b0cd665 History
Kobold.php 22.6 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4require_once __DIR__ . '/../../src/Utilities/GameHelper.php';
5
6class Kobold
7{
8 private $id;
9 private $userId;
10 private $saveId;
11 private $name;
12 private $age;
13 private $stats = [];
14 private $spriteMorph;
15 private $isLeader;
16 private $isAlive = true;
17 private $isExpelled = false;
18 private $injuries = [];
19 private $items = [];
20 private $fatigue = 0;
21 private $fatherId;
22 private $motherId;
23 private $saveManager;
24
25 private $colourPrimary;
26 private $colourSecondary;
27 private $colourTertiary;
28
29 private $male;
30 public $dataStore;
31
32 public $isRival = false;
33
34 private static $statNames = [
35 'vitality',
36 'intelligence',
37 'medicine',
38 'crafting',
39 'personality',
40 'will',
41 'fighting'
42 ];
43
44 private static $statTitles = [
45 'vitality' => 'Pathfinder',
46 'intelligence' => 'Lorekeeper',
47 'medicine' => 'Healer',
48 'crafting' => 'Tinkerer',
49 'personality' => 'Speaker',
50 'will' => 'Warden',
51 'fighting' => 'Warrior'
52 ];
53
54 public function getTitle($hasSecondary = true)
55 {
56 $rankedStats = [];
57
58 foreach (self::$statNames as $statName) {
59 $rankedStats[$statName] = (int) ($this->stats[$statName] ?? 0);
60 }
61
62 arsort($rankedStats);
63 $statKeys = array_keys($rankedStats);
64 $statValues = array_values($rankedStats);
65
66 if ($statValues[0] < 50)
67 return $this->male ? "Tribesman" : "Tribeswoman";
68
69 $topStat = $statKeys[0] ?? null;
70 if ($topStat === null) {
71 return '';
72 }
73
74 $topTitle = self::$statTitles[$topStat] ?? '';
75
76 if (($topTitle === 'Warrior' || $topTitle === 'Pathfinder') && $hasSecondary) {
77 $secondStat = $statKeys[1] ?? null;
78 $secondTitle = $secondStat !== null ? (self::$statTitles[$secondStat] ?? '') : '';
79
80 if ($secondTitle !== '') {
81 return trim($topTitle . ' ' . $secondTitle);
82 }
83 }
84
85 return $topTitle;
86 }
87
88 public function getHighestStatName()
89 {
90 $rankedStats = [];
91
92 foreach (self::$statNames as $statName) {
93 $rankedStats[$statName] = (int) ($this->stats[$statName] ?? 0);
94 }
95
96 arsort($rankedStats);
97 $statKeys = array_keys($rankedStats);
98
99 return $statKeys[0] ?? null;
100 }
101
102 public function __construct($id, $userId, $saveId, $name, $age, $spriteMorph, $isLeader = false)
103 {
104 $this->id = $id;
105 $this->userId = $userId;
106 $this->saveId = $saveId;
107 $this->name = $name;
108 $this->age = $age;
109 $this->spriteMorph = $spriteMorph;
110 $this->isLeader = $isLeader;
111 $this->male = rand(0, 100) > 50;
112 $this->fatigue = 0;
113
114 $min = 120;
115 $mx = 240;
116
117 $this->colourPrimary = sprintf(
118 "#%02X%02X%02X",
119 random_int($min, $mx),
120 random_int($min, $mx),
121 random_int($min, $mx)
122 );
123
124 $this->colourSecondary = sprintf(
125 "#%02X%02X%02X",
126 random_int($min, $mx),
127 random_int($min, $mx),
128 random_int($min, $mx)
129 );
130
131 $this->colourTertiary = sprintf(
132 "#%02X%02X%02X",
133 random_int($min, $mx),
134 random_int($min, $mx),
135 random_int($min, $mx)
136 );
137
138 $this->saveManager = new SaveManager();
139
140 // Initialize stats with random values
141 foreach (self::$statNames as $stat) {
142 $this->stats[$stat] = rand(0, 100);
143 }
144 }
145
146 public function he()
147 {
148 return $this->male ? "he" : "she";
149 }
150
151 public function him()
152 {
153 return $this->male ? "him" : "her";
154 }
155
156 public function his()
157 {
158 return $this->male ? "his" : "her";
159 }
160
161 public function setLeader()
162 {
163 $this->isLeader = true;
164 }
165
166 public function isLeader()
167 {
168 return $this->isLeader;
169 }
170
171 public static function generate($userId, $saveId, $age = null, $rival = false)
172 {
173 if ($age === null) {
174 $age = rand(5, 50);
175 }
176
177 $spriteMorph = self::getRandomSpriteMorph();
178 $name = self::generateRandomName();
179 $kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);
180
181 $kobold->isRival = $rival;
182
183 return $kobold;
184 }
185
186 private static function getRandomSpriteMorph()
187 {
188 $morphsPath = __DIR__ . '/../../assets/sprites';
189 if (!is_dir($morphsPath)) {
190 return 'default';
191 }
192
193 $morphs = array_filter(scandir($morphsPath), function ($item) use ($morphsPath) {
194 return is_dir($morphsPath . '/' . $item) && $item[0] !== '.';
195 });
196
197 $morphs = array_values($morphs);
198
199 return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';
200 }
201
202 public static function generateRandomName()
203 {
204 // Kobold name syllables
205 $firstSyllables = [
206 'Grik',
207 'Gnak',
208 'Drog',
209 'Mog',
210 'Bik',
211 'Zag',
212 'Kra',
213 'Snak',
214 'Grok',
215 'Tik',
216 'Nag',
217 'Brack',
218 'Flak',
219 'Grat',
220 'Krag',
221 'Skrit',
222 'Zik',
223 'Bog',
224 'Crag',
225 'Gull',
226 'Kith',
227 'Mick',
228 'Nib',
229 'Prat',
230 'Rik',
231 'Tig',
232 'Vex',
233 'Wik',
234 'Xak',
235 'Yak',
236 'Zap'
237 ];
238
239 $lastSyllables = [
240 'ink',
241 'ack',
242 'og',
243 'ag',
244 'ug',
245 'ik',
246 'ek',
247 'ock',
248 'ar',
249 'ax',
250 'er',
251 'it',
252 'ut',
253 'ot',
254 'or',
255 'in',
256 'an',
257 'en',
258 'un',
259 'on',
260 'oo',
261 'ee',
262 'im',
263 'um'
264 ];
265
266 $firstName = $firstSyllables[array_rand($firstSyllables)];
267 $lastName = $lastSyllables[array_rand($lastSyllables)];
268
269 return $firstName . $lastName;
270 }
271
272 public static function fromArray($data, $userId, $saveId)
273 {
274 $kobold = new self(
275 $data['id'] ?? null,
276 $userId,
277 $saveId,
278 $data['name'] ?? '',
279 $data['age'] ?? 0,
280 $data['sprite_morph'] ?? 'default',
281 $data['is_leader'] ?? false
282 );
283
284 if (isset($data['stats'])) {
285 $kobold->stats = $data['stats'];
286 }
287
288 $kobold->isAlive = $data['is_alive'] ?? true;
289 $kobold->isExpelled = $data['is_expelled'] ?? false;
290 $kobold->injuries = array_values($data['injuries'] ?? []);
291 $kobold->items = $data['items'] ?? [];
292 $kobold->fatigue = $data['fatigue'] ?? 0;
293 $kobold->fatherId = $data['father_id'] ?? null;
294 $kobold->motherId = $data['mother_id'] ?? null;
295 $kobold->male = $data['male'] ?? rand(0, 100) > 50;
296
297 $kobold->colourPrimary = $data['colour_primary'] ?? '#FFFFFF';
298 $kobold->colourSecondary = $data['colour_secondary'] ?? '#FFFFFF';
299 $kobold->colourTertiary = $data['colour_tertiary'] ?? '#FFFFFF';
300 $kobold->dataStore = $data['data_store'] ?? new stdClass();
301 $kobold->isRival = $data['is_rival'] ?? false;
302
303 if (is_array($kobold->dataStore)) {
304 $kobold->dataStore = (object) $kobold->dataStore;
305 }
306
307 return $kobold;
308 }
309
310 public function toArray()
311 {
312 return [
313 'id' => $this->id,
314 'name' => $this->getAgeCategory() !== "egg" ? $this->name : "Egg",
315 'age' => $this->age,
316 'ageCategory' => $this->getAgeCategory(),
317 'stats' => $this->stats,
318 'sprite_morph' => $this->spriteMorph,
319 'is_leader' => $this->isLeader,
320 'is_alive' => !$this->isDead(),
321 'is_expelled' => $this->isExpelled,
322 'injuries' => $this->injuries,
323 'items' => $this->items,
324 'fatigue' => $this->fatigue,
325 'fatigue_label' => $this->getFatigueLabel(),
326 'father_id' => $this->fatherId,
327 'mother_id' => $this->motherId,
328 'colour_primary' => $this->colourPrimary,
329 'colour_secondary' => $this->colourSecondary,
330 'colour_tertiary' => $this->colourTertiary,
331 'male' => $this->male,
332 'data_store' => $this->dataStore ?? new stdClass(),
333 'is_rival' => $this->isRival ?? false
334 ];
335 }
336
337 public function save()
338 {
339 // Kobolds are saved as part of the Tribe's kobolds.json
340 // Sprite files are stored in:
341 // /data/saves/{userId}/kobolds/{koboldId}/sprites/
342 }
343
344 /**
345 * Initialize sprite by copying base sprite from assets and applying transformations
346 * Called on kobold generation to populate the save folder
347 */
348 private function initializeSprite()
349 {
350 $ageSprite = $this->getAgeSpriteName();
351
352 if ($ageSprite === "old" || $ageSprite === "adult")
353 $ageSprite = $ageSprite . "_" . ($this->male ? "male" : "female");
354
355 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);
356 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
357 $destFile = $spriteDir;
358
359 // Copy base sprite from assets
360 if (file_exists($sourceFile)) {
361 copy($sourceFile, $destFile);
362 }
363
364 // Apply transformations to the sprite
365 $this->transformSprite($destFile);
366 }
367
368 /**
369 * Get the sprite filename for current age
370 */
371 public function getAgeSpriteName()
372 {
373 $ageCategory = $this->getAgeCategory();
374 $spriteMap = [
375 'egg' => 'egg',
376 'baby' => 'baby',
377 'young' => 'young',
378 'adult' => 'adult',
379 'old' => 'old'
380 ];
381
382 return $spriteMap[$ageCategory] ?? 'adult';
383 }
384
385 /**
386 * Get path to the kobold's sprite file for current age
387 */
388 public function getSpritePath($age)
389 {
390 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);
391 $ageSprite = $age ?? $this->getAgeSpriteName();
392
393 if ($ageSprite === "old" || $ageSprite === "adult")
394 $ageSprite = $ageSprite . "_" . ($this->male ? "male" : "female");
395
396 $destFile = $spriteDir;
397
398 if (!file_exists($destFile)) {
399 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
400
401 // Copy base sprite from assets
402 if (file_exists($sourceFile)) {
403 copy($sourceFile, $destFile);
404 }
405
406 // Apply transformations to the sprite
407 $this->transformSprite($destFile);
408 }
409
410 return $destFile;
411 }
412
413 public function getMale()
414 {
415 return $this->male;
416 }
417
418 public function getId()
419 {
420 return $this->id;
421 }
422
423 public function getName(): string
424 {
425 return $this->name;
426 }
427
428 public function setName($name)
429 {
430 $this->name = $name;
431 }
432
433 public function getAge()
434 {
435 return $this->age;
436 }
437
438 public function setAge($age)
439 {
440 $this->age = max(0, $age);
441 }
442
443 public function incrementAge()
444 {
445 $this->age++;
446 }
447
448 public function getAgeCategory()
449 {
450 return GameHelper::getAgeCategory($this->age);
451 }
452
453 public function getAgeProgress()
454 {
455 if ($this->age < 17) {
456 return max(1, $this->age / 17);
457 } else if ($this->age > 40) {
458 return max(1, 1 - (40 / $this->age));
459 }
460
461 return 1;
462 }
463
464 public function getStat($statName)
465 {
466 if (!isset($this->stats[$statName])) {
467 return null;
468 }
469
470 $baseStat = $this->stats[$statName];
471
472 $baseStat = (int) ($baseStat * $this->getAgeProgress());
473
474 return $baseStat;
475 }
476
477 public function setStat($statName, $value)
478 {
479 if (isset($this->stats[$statName])) {
480 $this->stats[$statName] = max(0, min(100, $value));
481 }
482 }
483
484 public function checkStat($statName, $bonus = 0)
485 {
486 $stat = $this->getStat($statName);
487
488 if ($stat === null) {
489 return false;
490 }
491
492 // Apply item stat modifications (support arrays from JSON or Item objects)
493 $itemModTotal = 0;
494 if (!empty($this->items) && is_array($this->items)) {
495 foreach ($this->items as $itm) {
496 $mods = [];
497 if (is_array($itm)) {
498 $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
499 } elseif (is_object($itm)) {
500 if (method_exists($itm, 'getStatModifications')) {
501 $mods = $itm->getStatModifications();
502 } elseif (property_exists($itm, 'statModifications')) {
503 $mods = $itm->statModifications;
504 }
505 }
506
507 if (is_array($mods) && isset($mods[$statName])) {
508 $itemModTotal += (int) $mods[$statName];
509 }
510 }
511 }
512
513 // First apply item modifications to the stat
514 $stat += $itemModTotal;
515
516 // Apply injury modifications
517 $totalInjurySeverity = 0;
518 if (!empty($this->injuries) && is_array($this->injuries)) {
519 foreach ($this->injuries as $inj) {
520 $totalInjurySeverity += $inj['severity'] ?? 0;
521 }
522 }
523
524 $stat -= $totalInjurySeverity;
525 $stat = max(0, min(100, $stat));
526
527 // Roll under 1d100
528 $roll = min(100, rand(1, 100) + $bonus);
529 return $roll <= $stat;
530 }
531
532 public function checkPersonality(Kobold $otherKobold)
533 {
534 // Get the like value that otherKobold has for this kobold
535 $bonus = 0;
536
537 if (isset($otherKobold->dataStore) && $otherKobold->dataStore instanceof stdClass) {
538 if (isset($otherKobold->dataStore->likes) && is_array($otherKobold->dataStore->likes)) {
539 $bonus = $otherKobold->dataStore->likes[$this->getId()] ?? 0;
540 }
541 }
542
543 // Call checkStat with the like value as bonus
544 return $this->checkStat('personality', $bonus);
545 }
546
547 public function addInjury($injuryType)
548 {
549 // Reject duplicates
550 foreach ($this->injuries as $inj) {
551 if (($inj['id'] ?? null) === $injuryType) {
552 return false;
553 }
554 }
555
556 // If an injury file exists in assets, load it for full data
557 $injData = null;
558 require_once __DIR__ . '/../Utilities/GameHelper.php';
559 $maybe = GameHelper::loadInjury($injuryType);
560 if ($maybe) {
561 $injData = $maybe;
562 // ensure kobold id
563 $injData['kobold_id'] = $this->id;
564 $this->injuries[] = $injData;
565
566 if ($this->isDead())
567 return "{$this->getName()} died due to a {$injuryType}.";
568
569 return true;
570 }
571
572 return false;
573 }
574
575 public function removeInjury($injuryId)
576 {
577 $this->injuries = array_values(array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId));
578 }
579
580 public function getInjuries()
581 {
582 return $this->injuries;
583 }
584
585 public function getFatigue()
586 {
587 return $this->fatigue;
588 }
589
590 public function setFatigue($value)
591 {
592 $this->fatigue = max(0, (int) $value);
593 }
594
595 public function addFatigue($amount)
596 {
597 $this->fatigue = max(0, $this->fatigue + (int) $amount);
598 }
599
600 public function resetFatigue()
601 {
602 $this->fatigue = 0;
603 }
604
605 public function getFatigueLabel()
606 {
607 $vitality = (int) ($this->getStat('vitality') ?? 0);
608 if ($vitality <= 0) {
609 return 'exhausted';
610 }
611
612 $ratio = $this->fatigue / max(1, $vitality);
613
614 if ($this->fatigue <= 0) {
615 return 'energetic';
616 }
617 if ($ratio < 0.3) {
618 return 'fresh';
619 }
620 if ($ratio < 0.6) {
621 return 'tired';
622 }
623 if ($ratio < 0.85) {
624 return 'weary';
625 }
626 return 'exhausted';
627 }
628
629 public function getTotalInjurySeverity()
630 {
631 $sum = 0;
632 foreach ($this->injuries as $injury) {
633 $sum += $injury['severity'] ?? 0;
634 }
635 return $sum;
636 }
637
638 public function isDead()
639 {
640 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
641 }
642
643 public function isExpelled()
644 {
645 return $this->isExpelled;
646 }
647
648 public function setExpelled($expelled)
649 {
650 $this->isExpelled = $expelled;
651 }
652
653 public function die()
654 {
655 $this->isAlive = false;
656 }
657
658 public function getSpriteMorph()
659 {
660 return $this->spriteMorph;
661 }
662
663 public function setSpriteMorph($spriteMorph)
664 {
665 $this->spriteMorph = $spriteMorph;
666 }
667
668 public function getColours()
669 {
670 return [
671 'primary' => $this->colourPrimary,
672 'secondary' => $this->colourSecondary,
673 'tertiary' => $this->colourTertiary
674 ];
675 }
676
677 public function setColours($primary, $secondary, $tertiary)
678 {
679 $this->colourPrimary = $primary;
680 $this->colourSecondary = $secondary;
681 $this->colourTertiary = $tertiary;
682 }
683
684 public function regenerateSprite()
685 {
686 $this->initializeSprite();
687 }
688
689 public function getStatLabel($statValue)
690 {
691 if ($statValue >= 90)
692 return 'godlike';
693 if ($statValue >= 80)
694 return 'divine';
695 if ($statValue >= 70)
696 return 'master';
697 if ($statValue >= 60)
698 return 'fantastic';
699 if ($statValue >= 50)
700 return 'excellent';
701 if ($statValue >= 40)
702 return 'good';
703 if ($statValue >= 30)
704 return 'decent';
705 if ($statValue >= 20)
706 return 'unskilled';
707 if ($statValue >= 10)
708 return 'bad';
709 return 'terrible';
710 }
711
712 public function setParents($fatherId, $motherId)
713 {
714 $this->fatherId = $fatherId;
715 $this->motherId = $motherId;
716 }
717
718 public function getParents()
719 {
720 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
721 }
722
723 public function getItems()
724 {
725 return $this->items;
726 }
727
728 public function addItem($item)
729 {
730 $this->items[] = $item;
731 }
732
733 public function removeItem($itemId)
734 {
735 $this->items = array_filter($this->items, function ($item) use ($itemId) {
736 return $item['id'] !== $itemId;
737 });
738 $this->items = array_values($this->items);
739 }
740
741 /**
742 * Apply transformations to sprite (injuries, age coloring, leadership marks)
743 * Uses PHP GD library to modify the sprite image
744 */
745 private function transformSprite($spritePath)
746 {
747 if (!file_exists($spritePath))
748 return;
749
750 $image = imagecreatefrompng($spritePath);
751 if (!$image)
752 return;
753
754 // Ensure truecolour (important if PNG is palette-based)
755 if (!imageistruecolor($image)) {
756 imagepalettetotruecolor($image);
757 }
758
759 $primaryRGB = $this->hexToRgb($this->colourPrimary);
760 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
761 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
762
763 $width = imagesx($image);
764 $height = imagesy($image);
765
766 // For exact per-pixel alpha writes:
767 imagealphablending($image, false);
768 imagesavealpha($image, true);
769
770 $cache = []; // cache allocated colours "r,g,b,a" => int
771
772 for ($y = 0; $y < $height; $y++) {
773 for ($x = 0; $x < $width; $x++) {
774 $idx = imagecolorat($image, $x, $y);
775 $rgba = imagecolorsforindex($image, $idx);
776
777 $baseR = $rgba['red'];
778 $baseG = $rgba['green'];
779 $baseB = $rgba['blue'];
780 $baseA = $rgba['alpha']; // 0..127
781
782 // If fully transparent, skip work (optional)
783 if ($baseA === 127) {
784 continue;
785 }
786
787 $newR = 0;
788 $newG = 0;
789 $newB = 0;
790
791 $rW = $baseR / 255.0;
792 $gW = $baseG / 255.0;
793 $bW = $baseB / 255.0;
794
795 $sum = $rW + $gW + $bW;
796
797 if ($sum > 0) {
798 $newR = ($rW * $primaryRGB['r']
799 + $gW * $secondaryRGB['r']
800 + $bW * $tertiaryRGB['r']) / $sum;
801
802 $newG = ($rW * $primaryRGB['g']
803 + $gW * $secondaryRGB['g']
804 + $bW * $tertiaryRGB['g']) / $sum;
805
806 $newB = ($rW * $primaryRGB['b']
807 + $gW * $secondaryRGB['b']
808 + $bW * $tertiaryRGB['b']) / $sum;
809 } else {
810 $newR = $newG = $newB = 0;
811 }
812
813 $w = min($baseR, $baseG, $baseB) / 255.0;
814
815 $newR = (int) round($newR + (255 - $newR) * $w);
816 $newG = (int) round($newG + (255 - $newG) * $w);
817 $newB = (int) round($newB + (255 - $newB) * $w);
818
819 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
820
821 $newR *= $intensity;
822 $newG *= $intensity;
823 $newB *= $intensity;
824
825 $newR = max(0, min(255, $newR));
826 $newG = max(0, min(255, $newG));
827 $newB = max(0, min(255, $newB));
828
829 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
830 if (!isset($cache[$key])) {
831 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
832 }
833
834 imagesetpixel($image, $x, $y, $cache[$key]);
835 }
836 }
837
838 imagepng($image, $spritePath);
839 }
840
841
842 /**
843 * Convert HEX color string to RGB array
844 * @param string $hex HEX color in format #RRGGBB
845 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
846 */
847 private function hexToRgb($hex)
848 {
849 // Remove # if present
850 $hex = ltrim($hex, '#');
851
852 // Convert HEX to RGB
853 return [
854 'r' => hexdec(substr($hex, 0, 2)),
855 'g' => hexdec(substr($hex, 2, 2)),
856 'b' => hexdec(substr($hex, 4, 2))
857 ];
858 }
859}