BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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