BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

63fe0a91 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 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 // If an injury file exists in assets, load it for full data
464 $injData = null;
465 require_once __DIR__ . '/../Utilities/GameHelper.php';
466 $maybe = GameHelper::loadInjury($injuryType);
467 if ($maybe) {
468 $injData = $maybe;
469 // ensure kobold id
470 $injData['kobold_id'] = $this->id;
471 $this->injuries[] = $injData;
472 return;
473 }
474 }
475
476 public function removeInjury($injuryId)
477 {
478 $this->injuries = array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId);
479 }
480
481 public function getInjuries()
482 {
483 return $this->injuries;
484 }
485
486 public function getFatigue()
487 {
488 return $this->fatigue;
489 }
490
491 public function setFatigue($value)
492 {
493 $this->fatigue = max(0, (int) $value);
494 }
495
496 public function addFatigue($amount)
497 {
498 $this->fatigue = max(0, $this->fatigue + (int) $amount);
499 }
500
501 public function resetFatigue()
502 {
503 $this->fatigue = 0;
504 }
505
506 public function getFatigueLabel()
507 {
508 $vitality = (int) ($this->getStat('vitality') ?? 0);
509 if ($vitality <= 0) {
510 return 'exhausted';
511 }
512
513 $ratio = $this->fatigue / max(1, $vitality);
514
515 if ($this->fatigue <= 0) {
516 return 'energetic';
517 }
518 if ($ratio < 0.3) {
519 return 'fresh';
520 }
521 if ($ratio < 0.6) {
522 return 'tired';
523 }
524 if ($ratio < 0.85) {
525 return 'weary';
526 }
527 return 'exhausted';
528 }
529
530 public function getTotalInjurySeverity()
531 {
532 $sum = 0;
533 foreach ($this->injuries as $injury) {
534 $sum += $injury['severity'] ?? 0;
535 }
536 return $sum;
537 }
538
539 public function isDead()
540 {
541 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
542 }
543
544 public function isExpelled()
545 {
546 return $this->isExpelled;
547 }
548
549 public function setExpelled($expelled)
550 {
551 $this->isExpelled = $expelled;
552 }
553
554 public function die()
555 {
556 $this->isAlive = false;
557 }
558
559 public function getSpriteMorph()
560 {
561 return $this->spriteMorph;
562 }
563
564 public function setSpriteMorph($spriteMorph)
565 {
566 $this->spriteMorph = $spriteMorph;
567 }
568
569 public function getColours()
570 {
571 return [
572 'primary' => $this->colourPrimary,
573 'secondary' => $this->colourSecondary,
574 'tertiary' => $this->colourTertiary
575 ];
576 }
577
578 public function setColours($primary, $secondary, $tertiary)
579 {
580 $this->colourPrimary = $primary;
581 $this->colourSecondary = $secondary;
582 $this->colourTertiary = $tertiary;
583 }
584
585 public function regenerateSprite()
586 {
587 $this->initializeSprite();
588 }
589
590 public function getStatLabel($statValue)
591 {
592 if ($statValue >= 90)
593 return 'godlike';
594 if ($statValue >= 80)
595 return 'divine';
596 if ($statValue >= 70)
597 return 'master';
598 if ($statValue >= 60)
599 return 'fantastic';
600 if ($statValue >= 50)
601 return 'excellent';
602 if ($statValue >= 40)
603 return 'good';
604 if ($statValue >= 30)
605 return 'decent';
606 if ($statValue >= 20)
607 return 'unskilled';
608 if ($statValue >= 10)
609 return 'bad';
610 return 'terrible';
611 }
612
613 public function setParents($fatherId, $motherId)
614 {
615 $this->fatherId = $fatherId;
616 $this->motherId = $motherId;
617 }
618
619 public function getParents()
620 {
621 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
622 }
623
624 public function getItems()
625 {
626 return $this->items;
627 }
628
629 public function addItem($item)
630 {
631 $this->items[] = $item;
632 }
633
634 public function removeItem($itemId)
635 {
636 $this->items = array_filter($this->items, function ($item) use ($itemId) {
637 return $item['id'] !== $itemId;
638 });
639 $this->items = array_values($this->items);
640 }
641
642 /**
643 * Apply transformations to sprite (injuries, age coloring, leadership marks)
644 * Uses PHP GD library to modify the sprite image
645 */
646 private function transformSprite($spritePath)
647 {
648 if (!file_exists($spritePath))
649 return;
650
651 $image = imagecreatefrompng($spritePath);
652 if (!$image)
653 return;
654
655 // Ensure truecolour (important if PNG is palette-based)
656 if (!imageistruecolor($image)) {
657 imagepalettetotruecolor($image);
658 }
659
660 $primaryRGB = $this->hexToRgb($this->colourPrimary);
661 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
662 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
663
664 $width = imagesx($image);
665 $height = imagesy($image);
666
667 // For exact per-pixel alpha writes:
668 imagealphablending($image, false);
669 imagesavealpha($image, true);
670
671 $cache = []; // cache allocated colours "r,g,b,a" => int
672
673 for ($y = 0; $y < $height; $y++) {
674 for ($x = 0; $x < $width; $x++) {
675 $idx = imagecolorat($image, $x, $y);
676 $rgba = imagecolorsforindex($image, $idx);
677
678 $baseR = $rgba['red'];
679 $baseG = $rgba['green'];
680 $baseB = $rgba['blue'];
681 $baseA = $rgba['alpha']; // 0..127
682
683 // If fully transparent, skip work (optional)
684 if ($baseA === 127) {
685 continue;
686 }
687
688 $newR = 0;
689 $newG = 0;
690 $newB = 0;
691
692 $rW = $baseR / 255.0;
693 $gW = $baseG / 255.0;
694 $bW = $baseB / 255.0;
695
696 $sum = $rW + $gW + $bW;
697
698 if ($sum > 0) {
699 $newR = ($rW * $primaryRGB['r']
700 + $gW * $secondaryRGB['r']
701 + $bW * $tertiaryRGB['r']) / $sum;
702
703 $newG = ($rW * $primaryRGB['g']
704 + $gW * $secondaryRGB['g']
705 + $bW * $tertiaryRGB['g']) / $sum;
706
707 $newB = ($rW * $primaryRGB['b']
708 + $gW * $secondaryRGB['b']
709 + $bW * $tertiaryRGB['b']) / $sum;
710 } else {
711 $newR = $newG = $newB = 0;
712 }
713
714 $w = min($baseR, $baseG, $baseB) / 255.0;
715
716 $newR = (int) round($newR + (255 - $newR) * $w);
717 $newG = (int) round($newG + (255 - $newG) * $w);
718 $newB = (int) round($newB + (255 - $newB) * $w);
719
720 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
721
722 $newR *= $intensity;
723 $newG *= $intensity;
724 $newB *= $intensity;
725
726 $newR = max(0, min(255, $newR));
727 $newG = max(0, min(255, $newG));
728 $newB = max(0, min(255, $newB));
729
730 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
731 if (!isset($cache[$key])) {
732 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
733 }
734
735 imagesetpixel($image, $x, $y, $cache[$key]);
736 }
737 }
738
739 imagepng($image, $spritePath);
740 }
741
742
743 /**
744 * Convert HEX color string to RGB array
745 * @param string $hex HEX color in format #RRGGBB
746 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
747 */
748 private function hexToRgb($hex)
749 {
750 // Remove # if present
751 $hex = ltrim($hex, '#');
752
753 // Convert HEX to RGB
754 return [
755 'r' => hexdec(substr($hex, 0, 2)),
756 'g' => hexdec(substr($hex, 2, 2)),
757 'b' => hexdec(substr($hex, 4, 2))
758 ];
759 }
760}