BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

injuries, cures, event edits
timfa Tim Falken · pushed by timfa · 9 months ago
146dd342 History
Kobold.php 18.3 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4
5class Kobold
6{
7 private $id;
8 private $userId;
9 private $saveId;
10 private $name;
11 private $age;
12 private $stats = [];
13 private $spriteMorph;
14 private $isLeader;
15 private $isAlive = true;
16 private $isExpelled = false;
17 private $injuries = [];
18 private $items = [];
19 private $fatherId;
20 private $motherId;
21 private $saveManager;
22
23 private $colourPrimary;
24 private $colourSecondary;
25 private $colourTertiary;
26
27 private static $statNames = [
28 'vitality',
29 'intelligence',
30 'tinkering',
31 'medicine',
32 'crafting',
33 'personality',
34 'will'
35 ];
36
37 public function __construct($id, $userId, $saveId, $name, $age, $spriteMorph, $isLeader = false)
38 {
39 $this->id = $id;
40 $this->userId = $userId;
41 $this->saveId = $saveId;
42 $this->name = $name;
43 $this->age = $age;
44 $this->spriteMorph = $spriteMorph;
45 $this->isLeader = $isLeader;
46
47 $min = 120;
48 $mx = 240;
49
50 $this->colourPrimary = sprintf(
51 "#%02X%02X%02X",
52 random_int($min, $mx),
53 random_int($min, $mx),
54 random_int($min, $mx)
55 );
56
57 $this->colourSecondary = sprintf(
58 "#%02X%02X%02X",
59 random_int($min, $mx),
60 random_int($min, $mx),
61 random_int($min, $mx)
62 );
63
64 $this->colourTertiary = sprintf(
65 "#%02X%02X%02X",
66 random_int($min, $mx),
67 random_int($min, $mx),
68 random_int($min, $mx)
69 );
70
71 $this->saveManager = new SaveManager();
72
73 // Initialize stats with random values
74 foreach (self::$statNames as $stat) {
75 $this->stats[$stat] = rand(0, 100);
76 }
77 }
78
79 public static function generate($userId, $saveId, $age = null)
80 {
81 if ($age === null) {
82 $age = rand(5, 20);
83 }
84
85 $spriteMorph = self::getRandomSpriteMorph();
86 $name = self::generateRandomName();
87 $kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);
88 // Copy and transform sprite from assets to save folder
89 $kobold->initializeSprite();
90
91 return $kobold;
92 }
93
94 private static function getRandomSpriteMorph()
95 {
96 $morphsPath = __DIR__ . '/../../assets/sprites';
97 if (!is_dir($morphsPath)) {
98 return 'default';
99 }
100
101 $morphs = array_filter(scandir($morphsPath), function ($item) use ($morphsPath) {
102 return is_dir($morphsPath . '/' . $item) && $item[0] !== '.';
103 });
104
105 $morphs = array_values($morphs);
106
107 return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';
108 }
109
110 private static function generateRandomName()
111 {
112 // Kobold name syllables
113 $firstSyllables = [
114 'Grik',
115 'Gnak',
116 'Drog',
117 'Mog',
118 'Bik',
119 'Zag',
120 'Kra',
121 'Snak',
122 'Grok',
123 'Tik',
124 'Nag',
125 'Brack',
126 'Flak',
127 'Grat',
128 'Krag',
129 'Skrit',
130 'Zik',
131 'Bog',
132 'Crag',
133 'Gull',
134 'Kith',
135 'Mick',
136 'Nib',
137 'Prat',
138 'Rik',
139 'Tig',
140 'Vex',
141 'Wik',
142 'Xak',
143 'Yak',
144 'Zap'
145 ];
146
147 $lastSyllables = [
148 'ink',
149 'ack',
150 'og',
151 'ag',
152 'ug',
153 'ik',
154 'ek',
155 'ock',
156 'ar',
157 'ax',
158 'er',
159 'it',
160 'ut',
161 'ot',
162 'or',
163 'in',
164 'an',
165 'en',
166 'un',
167 'on',
168 'oo',
169 'ee',
170 'im',
171 'um'
172 ];
173
174 $firstName = $firstSyllables[array_rand($firstSyllables)];
175 $lastName = $lastSyllables[array_rand($lastSyllables)];
176
177 return $firstName . $lastName;
178 }
179
180 public static function fromArray($data, $userId, $saveId)
181 {
182 $kobold = new self(
183 $data['id'] ?? null,
184 $userId,
185 $saveId,
186 $data['name'] ?? '',
187 $data['age'] ?? 0,
188 $data['sprite_morph'] ?? 'default',
189 $data['is_leader'] ?? false
190 );
191
192 if (isset($data['stats'])) {
193 $kobold->stats = $data['stats'];
194 }
195
196 $kobold->isAlive = $data['is_alive'] ?? true;
197 $kobold->isExpelled = $data['is_expelled'] ?? false;
198 $kobold->injuries = $data['injuries'] ?? [];
199 $kobold->items = $data['items'] ?? [];
200 $kobold->fatherId = $data['father_id'] ?? null;
201 $kobold->motherId = $data['mother_id'] ?? null;
202
203 $kobold->colourPrimary = $data['colour_primary'] ?? '#FFFFFF';
204 $kobold->colourSecondary = $data['colour_secondary'] ?? '#FFFFFF';
205 $kobold->colourTertiary = $data['colour_tertiary'] ?? '#FFFFFF';
206
207 return $kobold;
208 }
209
210 public function toArray()
211 {
212 return [
213 'id' => $this->id,
214 'name' => $this->name,
215 'age' => $this->age,
216 'ageCategory' => $this->getAgeCategory(),
217 'stats' => $this->stats,
218 'sprite_morph' => $this->spriteMorph,
219 'is_leader' => $this->isLeader,
220 'is_alive' => $this->isAlive,
221 'is_expelled' => $this->isExpelled,
222 'injuries' => $this->injuries,
223 'items' => $this->items,
224 'father_id' => $this->fatherId,
225 'mother_id' => $this->motherId,
226 'colour_primary' => $this->colourPrimary,
227 'colour_secondary' => $this->colourSecondary,
228 'colour_tertiary' => $this->colourTertiary
229 ];
230 }
231
232 public function save()
233 {
234 // Kobolds are saved as part of the Tribe's kobolds.json
235 // Sprite files are stored in:
236 // /data/saves/{userId}/kobolds/{koboldId}/sprites/
237 }
238
239 /**
240 * Initialize sprite by copying base sprite from assets and applying transformations
241 * Called on kobold generation to populate the save folder
242 */
243 private function initializeSprite()
244 {
245 $ageSprite = $this->getAgeSpriteName();
246 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);
247 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
248 $destFile = $spriteDir;
249
250 // Copy base sprite from assets
251 if (file_exists($sourceFile)) {
252 copy($sourceFile, $destFile);
253 }
254
255 // Apply transformations to the sprite
256 $this->transformSprite($destFile);
257 }
258
259 /**
260 * Get the sprite filename for current age
261 */
262 public function getAgeSpriteName()
263 {
264 $ageCategory = $this->getAgeCategory();
265 $spriteMap = [
266 'egg' => 'egg',
267 'baby' => 'baby',
268 'young' => 'young',
269 'adult' => 'adult',
270 'old' => 'old' // Reuse old sprite for very_old
271 ];
272
273 return $spriteMap[$ageCategory] ?? 'adult';
274 }
275
276 /**
277 * Get path to the kobold's sprite file for current age
278 */
279 public function getSpritePath($age)
280 {
281 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);
282 $ageSprite = $age ?? $this->getAgeSpriteName();
283 $destFile = $spriteDir;
284
285 if (!file_exists($destFile)) {
286 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
287
288 // Copy base sprite from assets
289 if (file_exists($sourceFile)) {
290 copy($sourceFile, $destFile);
291 }
292
293 // Apply transformations to the sprite
294 $this->transformSprite($destFile);
295 }
296
297 return $destFile;
298 }
299
300 public function getId()
301 {
302 return $this->id;
303 }
304
305 public function getName()
306 {
307 return $this->name;
308 }
309
310 public function setName($name)
311 {
312 $this->name = $name;
313 }
314
315 public function getAge()
316 {
317 return $this->age;
318 }
319
320 public function setAge($age)
321 {
322 $this->age = max(0, $age);
323 }
324
325 public function incrementAge()
326 {
327 $this->age++;
328 }
329
330 public function getAgeCategory()
331 {
332 if ($this->age < 0)
333 return 'egg';
334 if ($this->age < 4)
335 return 'baby';
336 if ($this->age < 35)
337 return 'young';
338 if ($this->age < 60)
339 return 'adult';
340 return 'old';
341 }
342
343 public function getAgeProgress()
344 {
345 // Returns 0-1 indicating progress to next age tier
346 $ageTiers = [-1, 0, 4, 35, 60];
347
348 for ($i = 0; $i < count($ageTiers) - 1; $i++) {
349 $tierStart = $ageTiers[$i];
350 $tierEnd = $ageTiers[$i + 1];
351
352 if ($this->age >= $tierStart && $this->age < $tierEnd) {
353 $duration = $tierEnd - $tierStart;
354 $progress = ($this->age - $tierStart) / $duration;
355 return $progress;
356 }
357 }
358
359 return 1;
360 }
361
362 public function getStat($statName)
363 {
364 if (!isset($this->stats[$statName])) {
365 return null;
366 }
367
368 $baseStat = $this->stats[$statName];
369
370 // Scale stats for non-adult kobolds
371 if ($this->getAgeCategory() === 'baby' || $this->getAgeCategory() === 'egg') {
372 $baseStat = (int) ($baseStat * $this->getAgeProgress());
373 }
374
375 return $baseStat;
376 }
377
378 public function setStat($statName, $value)
379 {
380 if (isset($this->stats[$statName])) {
381 $this->stats[$statName] = max(0, min(100, $value));
382 }
383 }
384
385 public function checkStat($statName)
386 {
387 $stat = $this->getStat($statName);
388
389 if ($stat === null) {
390 return false;
391 }
392
393 // Apply item stat modifications (support arrays from JSON or Item objects)
394 $itemModTotal = 0;
395 if (!empty($this->items) && is_array($this->items)) {
396 foreach ($this->items as $itm) {
397 $mods = [];
398 if (is_array($itm)) {
399 $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
400 } elseif (is_object($itm)) {
401 if (method_exists($itm, 'getStatModifications')) {
402 $mods = $itm->getStatModifications();
403 } elseif (property_exists($itm, 'statModifications')) {
404 $mods = $itm->statModifications;
405 }
406 }
407
408 if (is_array($mods) && isset($mods[$statName])) {
409 $itemModTotal += (int) $mods[$statName];
410 }
411 }
412 }
413
414 // First apply item modifications to the stat
415 $stat += $itemModTotal;
416
417 // Apply injury modifications
418 $totalInjurySeverity = 0;
419 if (!empty($this->injuries) && is_array($this->injuries)) {
420 foreach ($this->injuries as $inj) {
421 $totalInjurySeverity += $inj['severity'] ?? 0;
422 }
423 }
424
425 $stat -= $totalInjurySeverity;
426 $stat = max(0, min(100, $stat));
427
428 // Roll under 1d100
429 $roll = rand(1, 100);
430 return $roll <= $stat;
431 }
432
433 public function addInjury($injuryType, $category, $severity = 1)
434 {
435 // If an injury file exists in assets, load it for full data
436 $injData = null;
437 require_once __DIR__ . '/../Utilities/GameHelper.php';
438 $maybe = GameHelper::loadInjury($injuryType);
439 if ($maybe) {
440 $injData = $maybe;
441 // override severity and category if provided explicitly
442 $injData['severity'] = $severity ?? ($injData['severity'] ?? 1);
443 if ($category)
444 $injData['category'] = $category;
445 // ensure kobold id
446 $injData['kobold_id'] = $this->id;
447 $this->injuries[] = $injData;
448 return;
449 }
450
451 // Fallback: create a minimal injury array
452 $id = uniqid('inj_');
453 $this->injuries[] = [
454 'id' => $id,
455 'kobold_id' => $this->id,
456 'injury_type' => $injuryType,
457 'category' => $category,
458 'severity' => $severity,
459 'stat_modifications' => []
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}