BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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