BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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