BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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