BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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