BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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