BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

event tweaks
timfa Tim Falken · pushed by timfa · 9 months ago
fd114d31 History
Kobold.php 17.8 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 if ($this->age < 17) {
372 return $this->age / 17;
373 } else if ($this->age > 40) {
374 return 1 - (40 / $this->age);
375 }
376
377 return 1;
378 }
379
380 public function getStat($statName)
381 {
382 if (!isset($this->stats[$statName])) {
383 return null;
384 }
385
386 $baseStat = $this->stats[$statName];
387
388 $baseStat = (int) ($baseStat * $this->getAgeProgress());
389
390 return $baseStat;
391 }
392
393 public function setStat($statName, $value)
394 {
395 if (isset($this->stats[$statName])) {
396 $this->stats[$statName] = max(0, min(100, $value));
397 }
398 }
399
400 public function checkStat($statName)
401 {
402 $stat = $this->getStat($statName);
403
404 if ($stat === null) {
405 return false;
406 }
407
408 // Apply item stat modifications (support arrays from JSON or Item objects)
409 $itemModTotal = 0;
410 if (!empty($this->items) && is_array($this->items)) {
411 foreach ($this->items as $itm) {
412 $mods = [];
413 if (is_array($itm)) {
414 $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
415 } elseif (is_object($itm)) {
416 if (method_exists($itm, 'getStatModifications')) {
417 $mods = $itm->getStatModifications();
418 } elseif (property_exists($itm, 'statModifications')) {
419 $mods = $itm->statModifications;
420 }
421 }
422
423 if (is_array($mods) && isset($mods[$statName])) {
424 $itemModTotal += (int) $mods[$statName];
425 }
426 }
427 }
428
429 // First apply item modifications to the stat
430 $stat += $itemModTotal;
431
432 // Apply injury modifications
433 $totalInjurySeverity = 0;
434 if (!empty($this->injuries) && is_array($this->injuries)) {
435 foreach ($this->injuries as $inj) {
436 $totalInjurySeverity += $inj['severity'] ?? 0;
437 }
438 }
439
440 $stat -= $totalInjurySeverity;
441 $stat = max(0, min(100, $stat));
442
443 // Roll under 1d100
444 $roll = rand(1, 100);
445 return $roll <= $stat;
446 }
447
448 public function addInjury($injuryType)
449 {
450 // If an injury file exists in assets, load it for full data
451 $injData = null;
452 require_once __DIR__ . '/../Utilities/GameHelper.php';
453 $maybe = GameHelper::loadInjury($injuryType);
454 if ($maybe) {
455 $injData = $maybe;
456 // ensure kobold id
457 $injData['kobold_id'] = $this->id;
458 $this->injuries[] = $injData;
459 return;
460 }
461 }
462
463 public function removeInjury($injuryId)
464 {
465 $this->injuries = array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId);
466 }
467
468 public function getInjuries()
469 {
470 return $this->injuries;
471 }
472
473 public function getTotalInjurySeverity()
474 {
475 $sum = 0;
476 foreach ($this->injuries as $injury) {
477 $sum += $injury['severity'] ?? 0;
478 }
479 return $sum;
480 }
481
482 public function isDead()
483 {
484 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
485 }
486
487 public function isExpelled()
488 {
489 return $this->isExpelled;
490 }
491
492 public function setExpelled($expelled)
493 {
494 $this->isExpelled = $expelled;
495 }
496
497 public function die()
498 {
499 $this->isAlive = false;
500 }
501
502 public function getSpriteMorph()
503 {
504 return $this->spriteMorph;
505 }
506
507 public function getStatLabel($statValue)
508 {
509 if ($statValue >= 90)
510 return 'godlike';
511 if ($statValue >= 80)
512 return 'divine';
513 if ($statValue >= 70)
514 return 'master';
515 if ($statValue >= 60)
516 return 'fantastic';
517 if ($statValue >= 50)
518 return 'excellent';
519 if ($statValue >= 40)
520 return 'good';
521 if ($statValue >= 30)
522 return 'decent';
523 if ($statValue >= 20)
524 return 'unskilled';
525 if ($statValue >= 10)
526 return 'bad';
527 return 'terrible';
528 }
529
530 public function setParents($fatherId, $motherId)
531 {
532 $this->fatherId = $fatherId;
533 $this->motherId = $motherId;
534 }
535
536 public function getParents()
537 {
538 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
539 }
540
541 public function getItems()
542 {
543 return $this->items;
544 }
545
546 public function addItem($item)
547 {
548 $this->items[] = $item;
549 }
550
551 public function removeItem($itemId)
552 {
553 $this->items = array_filter($this->items, function ($item) use ($itemId) {
554 return $item['id'] !== $itemId;
555 });
556 $this->items = array_values($this->items);
557 }
558
559 /**
560 * Apply transformations to sprite (injuries, age coloring, leadership marks)
561 * Uses PHP GD library to modify the sprite image
562 */
563 private function transformSprite($spritePath)
564 {
565 if (!file_exists($spritePath))
566 return;
567
568 $image = imagecreatefrompng($spritePath);
569 if (!$image)
570 return;
571
572 // Ensure truecolour (important if PNG is palette-based)
573 if (!imageistruecolor($image)) {
574 imagepalettetotruecolor($image);
575 }
576
577 $primaryRGB = $this->hexToRgb($this->colourPrimary);
578 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
579 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
580
581 $width = imagesx($image);
582 $height = imagesy($image);
583
584 // For exact per-pixel alpha writes:
585 imagealphablending($image, false);
586 imagesavealpha($image, true);
587
588 $cache = []; // cache allocated colours "r,g,b,a" => int
589
590 for ($y = 0; $y < $height; $y++) {
591 for ($x = 0; $x < $width; $x++) {
592 $idx = imagecolorat($image, $x, $y);
593 $rgba = imagecolorsforindex($image, $idx);
594
595 $baseR = $rgba['red'];
596 $baseG = $rgba['green'];
597 $baseB = $rgba['blue'];
598 $baseA = $rgba['alpha']; // 0..127
599
600 // If fully transparent, skip work (optional)
601 if ($baseA === 127) {
602 continue;
603 }
604
605 $newR = 0;
606 $newG = 0;
607 $newB = 0;
608
609 $rW = $baseR / 255.0;
610 $gW = $baseG / 255.0;
611 $bW = $baseB / 255.0;
612
613 $sum = $rW + $gW + $bW;
614
615 if ($sum > 0) {
616 $newR = ($rW * $primaryRGB['r']
617 + $gW * $secondaryRGB['r']
618 + $bW * $tertiaryRGB['r']) / $sum;
619
620 $newG = ($rW * $primaryRGB['g']
621 + $gW * $secondaryRGB['g']
622 + $bW * $tertiaryRGB['g']) / $sum;
623
624 $newB = ($rW * $primaryRGB['b']
625 + $gW * $secondaryRGB['b']
626 + $bW * $tertiaryRGB['b']) / $sum;
627 } else {
628 $newR = $newG = $newB = 0;
629 }
630
631 $w = min($baseR, $baseG, $baseB) / 255.0;
632
633 $newR = (int) round($newR + (255 - $newR) * $w);
634 $newG = (int) round($newG + (255 - $newG) * $w);
635 $newB = (int) round($newB + (255 - $newB) * $w);
636
637 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
638
639 $newR *= $intensity;
640 $newG *= $intensity;
641 $newB *= $intensity;
642
643 $newR = max(0, min(255, $newR));
644 $newG = max(0, min(255, $newG));
645 $newB = max(0, min(255, $newB));
646
647 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
648 if (!isset($cache[$key])) {
649 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
650 }
651
652 imagesetpixel($image, $x, $y, $cache[$key]);
653 }
654 }
655
656 imagepng($image, $spritePath);
657 }
658
659
660 /**
661 * Convert HEX color string to RGB array
662 * @param string $hex HEX color in format #RRGGBB
663 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
664 */
665 private function hexToRgb($hex)
666 {
667 // Remove # if present
668 $hex = ltrim($hex, '#');
669
670 // Convert HEX to RGB
671 return [
672 'r' => hexdec(substr($hex, 0, 2)),
673 'g' => hexdec(substr($hex, 2, 2)),
674 'b' => hexdec(substr($hex, 4, 2))
675 ];
676 }
677}