BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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