BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

farming
timfa Tim · pushed by timfa · 9 months ago
569cc974 History
Kobold.php 19.0 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 getStatLabel($statValue)
562 {
563 if ($statValue >= 90)
564 return 'godlike';
565 if ($statValue >= 80)
566 return 'divine';
567 if ($statValue >= 70)
568 return 'master';
569 if ($statValue >= 60)
570 return 'fantastic';
571 if ($statValue >= 50)
572 return 'excellent';
573 if ($statValue >= 40)
574 return 'good';
575 if ($statValue >= 30)
576 return 'decent';
577 if ($statValue >= 20)
578 return 'unskilled';
579 if ($statValue >= 10)
580 return 'bad';
581 return 'terrible';
582 }
583
584 public function setParents($fatherId, $motherId)
585 {
586 $this->fatherId = $fatherId;
587 $this->motherId = $motherId;
588 }
589
590 public function getParents()
591 {
592 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
593 }
594
595 public function getItems()
596 {
597 return $this->items;
598 }
599
600 public function addItem($item)
601 {
602 $this->items[] = $item;
603 }
604
605 public function removeItem($itemId)
606 {
607 $this->items = array_filter($this->items, function ($item) use ($itemId) {
608 return $item['id'] !== $itemId;
609 });
610 $this->items = array_values($this->items);
611 }
612
613 /**
614 * Apply transformations to sprite (injuries, age coloring, leadership marks)
615 * Uses PHP GD library to modify the sprite image
616 */
617 private function transformSprite($spritePath)
618 {
619 if (!file_exists($spritePath))
620 return;
621
622 $image = imagecreatefrompng($spritePath);
623 if (!$image)
624 return;
625
626 // Ensure truecolour (important if PNG is palette-based)
627 if (!imageistruecolor($image)) {
628 imagepalettetotruecolor($image);
629 }
630
631 $primaryRGB = $this->hexToRgb($this->colourPrimary);
632 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
633 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
634
635 $width = imagesx($image);
636 $height = imagesy($image);
637
638 // For exact per-pixel alpha writes:
639 imagealphablending($image, false);
640 imagesavealpha($image, true);
641
642 $cache = []; // cache allocated colours "r,g,b,a" => int
643
644 for ($y = 0; $y < $height; $y++) {
645 for ($x = 0; $x < $width; $x++) {
646 $idx = imagecolorat($image, $x, $y);
647 $rgba = imagecolorsforindex($image, $idx);
648
649 $baseR = $rgba['red'];
650 $baseG = $rgba['green'];
651 $baseB = $rgba['blue'];
652 $baseA = $rgba['alpha']; // 0..127
653
654 // If fully transparent, skip work (optional)
655 if ($baseA === 127) {
656 continue;
657 }
658
659 $newR = 0;
660 $newG = 0;
661 $newB = 0;
662
663 $rW = $baseR / 255.0;
664 $gW = $baseG / 255.0;
665 $bW = $baseB / 255.0;
666
667 $sum = $rW + $gW + $bW;
668
669 if ($sum > 0) {
670 $newR = ($rW * $primaryRGB['r']
671 + $gW * $secondaryRGB['r']
672 + $bW * $tertiaryRGB['r']) / $sum;
673
674 $newG = ($rW * $primaryRGB['g']
675 + $gW * $secondaryRGB['g']
676 + $bW * $tertiaryRGB['g']) / $sum;
677
678 $newB = ($rW * $primaryRGB['b']
679 + $gW * $secondaryRGB['b']
680 + $bW * $tertiaryRGB['b']) / $sum;
681 } else {
682 $newR = $newG = $newB = 0;
683 }
684
685 $w = min($baseR, $baseG, $baseB) / 255.0;
686
687 $newR = (int) round($newR + (255 - $newR) * $w);
688 $newG = (int) round($newG + (255 - $newG) * $w);
689 $newB = (int) round($newB + (255 - $newB) * $w);
690
691 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
692
693 $newR *= $intensity;
694 $newG *= $intensity;
695 $newB *= $intensity;
696
697 $newR = max(0, min(255, $newR));
698 $newG = max(0, min(255, $newG));
699 $newB = max(0, min(255, $newB));
700
701 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
702 if (!isset($cache[$key])) {
703 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
704 }
705
706 imagesetpixel($image, $x, $y, $cache[$key]);
707 }
708 }
709
710 imagepng($image, $spritePath);
711 }
712
713
714 /**
715 * Convert HEX color string to RGB array
716 * @param string $hex HEX color in format #RRGGBB
717 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
718 */
719 private function hexToRgb($hex)
720 {
721 // Remove # if present
722 $hex = ltrim($hex, '#');
723
724 // Convert HEX to RGB
725 return [
726 'r' => hexdec(substr($hex, 0, 2)),
727 'g' => hexdec(substr($hex, 2, 2)),
728 'b' => hexdec(substr($hex, 4, 2))
729 ];
730 }
731}