BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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