BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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