BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

Titles
timfa Tim Falken · pushed by timfa · 9 months ago
734966ca History
Kobold.php 22.5 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 return true;
566 }
567
568 return false;
569 }
570
571 public function removeInjury($injuryId)
572 {
573 $this->injuries = array_values(array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId));
574 }
575
576 public function getInjuries()
577 {
578 return $this->injuries;
579 }
580
581 public function getFatigue()
582 {
583 return $this->fatigue;
584 }
585
586 public function setFatigue($value)
587 {
588 $this->fatigue = max(0, (int) $value);
589 }
590
591 public function addFatigue($amount)
592 {
593 $this->fatigue = max(0, $this->fatigue + (int) $amount);
594 }
595
596 public function resetFatigue()
597 {
598 $this->fatigue = 0;
599 }
600
601 public function getFatigueLabel()
602 {
603 $vitality = (int) ($this->getStat('vitality') ?? 0);
604 if ($vitality <= 0) {
605 return 'exhausted';
606 }
607
608 $ratio = $this->fatigue / max(1, $vitality);
609
610 if ($this->fatigue <= 0) {
611 return 'energetic';
612 }
613 if ($ratio < 0.3) {
614 return 'fresh';
615 }
616 if ($ratio < 0.6) {
617 return 'tired';
618 }
619 if ($ratio < 0.85) {
620 return 'weary';
621 }
622 return 'exhausted';
623 }
624
625 public function getTotalInjurySeverity()
626 {
627 $sum = 0;
628 foreach ($this->injuries as $injury) {
629 $sum += $injury['severity'] ?? 0;
630 }
631 return $sum;
632 }
633
634 public function isDead()
635 {
636 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
637 }
638
639 public function isExpelled()
640 {
641 return $this->isExpelled;
642 }
643
644 public function setExpelled($expelled)
645 {
646 $this->isExpelled = $expelled;
647 }
648
649 public function die()
650 {
651 $this->isAlive = false;
652 }
653
654 public function getSpriteMorph()
655 {
656 return $this->spriteMorph;
657 }
658
659 public function setSpriteMorph($spriteMorph)
660 {
661 $this->spriteMorph = $spriteMorph;
662 }
663
664 public function getColours()
665 {
666 return [
667 'primary' => $this->colourPrimary,
668 'secondary' => $this->colourSecondary,
669 'tertiary' => $this->colourTertiary
670 ];
671 }
672
673 public function setColours($primary, $secondary, $tertiary)
674 {
675 $this->colourPrimary = $primary;
676 $this->colourSecondary = $secondary;
677 $this->colourTertiary = $tertiary;
678 }
679
680 public function regenerateSprite()
681 {
682 $this->initializeSprite();
683 }
684
685 public function getStatLabel($statValue)
686 {
687 if ($statValue >= 90)
688 return 'godlike';
689 if ($statValue >= 80)
690 return 'divine';
691 if ($statValue >= 70)
692 return 'master';
693 if ($statValue >= 60)
694 return 'fantastic';
695 if ($statValue >= 50)
696 return 'excellent';
697 if ($statValue >= 40)
698 return 'good';
699 if ($statValue >= 30)
700 return 'decent';
701 if ($statValue >= 20)
702 return 'unskilled';
703 if ($statValue >= 10)
704 return 'bad';
705 return 'terrible';
706 }
707
708 public function setParents($fatherId, $motherId)
709 {
710 $this->fatherId = $fatherId;
711 $this->motherId = $motherId;
712 }
713
714 public function getParents()
715 {
716 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
717 }
718
719 public function getItems()
720 {
721 return $this->items;
722 }
723
724 public function addItem($item)
725 {
726 $this->items[] = $item;
727 }
728
729 public function removeItem($itemId)
730 {
731 $this->items = array_filter($this->items, function ($item) use ($itemId) {
732 return $item['id'] !== $itemId;
733 });
734 $this->items = array_values($this->items);
735 }
736
737 /**
738 * Apply transformations to sprite (injuries, age coloring, leadership marks)
739 * Uses PHP GD library to modify the sprite image
740 */
741 private function transformSprite($spritePath)
742 {
743 if (!file_exists($spritePath))
744 return;
745
746 $image = imagecreatefrompng($spritePath);
747 if (!$image)
748 return;
749
750 // Ensure truecolour (important if PNG is palette-based)
751 if (!imageistruecolor($image)) {
752 imagepalettetotruecolor($image);
753 }
754
755 $primaryRGB = $this->hexToRgb($this->colourPrimary);
756 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
757 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
758
759 $width = imagesx($image);
760 $height = imagesy($image);
761
762 // For exact per-pixel alpha writes:
763 imagealphablending($image, false);
764 imagesavealpha($image, true);
765
766 $cache = []; // cache allocated colours "r,g,b,a" => int
767
768 for ($y = 0; $y < $height; $y++) {
769 for ($x = 0; $x < $width; $x++) {
770 $idx = imagecolorat($image, $x, $y);
771 $rgba = imagecolorsforindex($image, $idx);
772
773 $baseR = $rgba['red'];
774 $baseG = $rgba['green'];
775 $baseB = $rgba['blue'];
776 $baseA = $rgba['alpha']; // 0..127
777
778 // If fully transparent, skip work (optional)
779 if ($baseA === 127) {
780 continue;
781 }
782
783 $newR = 0;
784 $newG = 0;
785 $newB = 0;
786
787 $rW = $baseR / 255.0;
788 $gW = $baseG / 255.0;
789 $bW = $baseB / 255.0;
790
791 $sum = $rW + $gW + $bW;
792
793 if ($sum > 0) {
794 $newR = ($rW * $primaryRGB['r']
795 + $gW * $secondaryRGB['r']
796 + $bW * $tertiaryRGB['r']) / $sum;
797
798 $newG = ($rW * $primaryRGB['g']
799 + $gW * $secondaryRGB['g']
800 + $bW * $tertiaryRGB['g']) / $sum;
801
802 $newB = ($rW * $primaryRGB['b']
803 + $gW * $secondaryRGB['b']
804 + $bW * $tertiaryRGB['b']) / $sum;
805 } else {
806 $newR = $newG = $newB = 0;
807 }
808
809 $w = min($baseR, $baseG, $baseB) / 255.0;
810
811 $newR = (int) round($newR + (255 - $newR) * $w);
812 $newG = (int) round($newG + (255 - $newG) * $w);
813 $newB = (int) round($newB + (255 - $newB) * $w);
814
815 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
816
817 $newR *= $intensity;
818 $newG *= $intensity;
819 $newB *= $intensity;
820
821 $newR = max(0, min(255, $newR));
822 $newG = max(0, min(255, $newG));
823 $newB = max(0, min(255, $newB));
824
825 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
826 if (!isset($cache[$key])) {
827 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
828 }
829
830 imagesetpixel($image, $x, $y, $cache[$key]);
831 }
832 }
833
834 imagepng($image, $spritePath);
835 }
836
837
838 /**
839 * Convert HEX color string to RGB array
840 * @param string $hex HEX color in format #RRGGBB
841 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
842 */
843 private function hexToRgb($hex)
844 {
845 // Remove # if present
846 $hex = ltrim($hex, '#');
847
848 // Convert HEX to RGB
849 return [
850 'r' => hexdec(substr($hex, 0, 2)),
851 'g' => hexdec(substr($hex, 2, 2)),
852 'b' => hexdec(substr($hex, 4, 2))
853 ];
854 }
855}