BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

fix events, item giving
timfa Tim Falken · pushed by timfa · 9 months ago
025e6a5e History
Kobold.php 17.7 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)
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 // ensure kobold id
442 $injData['kobold_id'] = $this->id;
443 $this->injuries[] = $injData;
444 return;
445 }
446 }
447
448 public function removeInjury($injuryId)
449 {
450 $this->injuries = array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId);
451 }
452
453 public function getInjuries()
454 {
455 return $this->injuries;
456 }
457
458 public function getTotalInjurySeverity()
459 {
460 $sum = 0;
461 foreach ($this->injuries as $injury) {
462 $sum += $injury['severity'] ?? 0;
463 }
464 return $sum;
465 }
466
467 public function isDead()
468 {
469 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
470 }
471
472 public function isExpelled()
473 {
474 return $this->isExpelled;
475 }
476
477 public function setExpelled($expelled)
478 {
479 $this->isExpelled = $expelled;
480 }
481
482 public function die()
483 {
484 $this->isAlive = false;
485 }
486
487 public function getSpriteMorph()
488 {
489 return $this->spriteMorph;
490 }
491
492 public function getStatLabel($statValue)
493 {
494 if ($statValue >= 90)
495 return 'godlike';
496 if ($statValue >= 80)
497 return 'divine';
498 if ($statValue >= 70)
499 return 'master';
500 if ($statValue >= 60)
501 return 'fantastic';
502 if ($statValue >= 50)
503 return 'excellent';
504 if ($statValue >= 40)
505 return 'good';
506 if ($statValue >= 30)
507 return 'decent';
508 if ($statValue >= 20)
509 return 'unskilled';
510 if ($statValue >= 10)
511 return 'bad';
512 return 'terrible';
513 }
514
515 public function setParents($fatherId, $motherId)
516 {
517 $this->fatherId = $fatherId;
518 $this->motherId = $motherId;
519 }
520
521 public function getParents()
522 {
523 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
524 }
525
526 public function getItems()
527 {
528 return $this->items;
529 }
530
531 public function addItem($item)
532 {
533 $this->items[] = $item;
534 }
535
536 public function removeItem($itemId)
537 {
538 $this->items = array_filter($this->items, function ($item) use ($itemId) {
539 return $item['id'] !== $itemId;
540 });
541 $this->items = array_values($this->items);
542 }
543
544 /**
545 * Apply transformations to sprite (injuries, age coloring, leadership marks)
546 * Uses PHP GD library to modify the sprite image
547 */
548 private function transformSprite($spritePath)
549 {
550 if (!file_exists($spritePath))
551 return;
552
553 $image = imagecreatefrompng($spritePath);
554 if (!$image)
555 return;
556
557 // Ensure truecolour (important if PNG is palette-based)
558 if (!imageistruecolor($image)) {
559 imagepalettetotruecolor($image);
560 }
561
562 $primaryRGB = $this->hexToRgb($this->colourPrimary);
563 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
564 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
565
566 $width = imagesx($image);
567 $height = imagesy($image);
568
569 // For exact per-pixel alpha writes:
570 imagealphablending($image, false);
571 imagesavealpha($image, true);
572
573 $cache = []; // cache allocated colours "r,g,b,a" => int
574
575 for ($y = 0; $y < $height; $y++) {
576 for ($x = 0; $x < $width; $x++) {
577 $idx = imagecolorat($image, $x, $y);
578 $rgba = imagecolorsforindex($image, $idx);
579
580 $baseR = $rgba['red'];
581 $baseG = $rgba['green'];
582 $baseB = $rgba['blue'];
583 $baseA = $rgba['alpha']; // 0..127
584
585 // If fully transparent, skip work (optional)
586 if ($baseA === 127) {
587 continue;
588 }
589
590 $newR = 0;
591 $newG = 0;
592 $newB = 0;
593
594 $rW = $baseR / 255.0;
595 $gW = $baseG / 255.0;
596 $bW = $baseB / 255.0;
597
598 $sum = $rW + $gW + $bW;
599
600 if ($sum > 0) {
601 $newR = ($rW * $primaryRGB['r']
602 + $gW * $secondaryRGB['r']
603 + $bW * $tertiaryRGB['r']) / $sum;
604
605 $newG = ($rW * $primaryRGB['g']
606 + $gW * $secondaryRGB['g']
607 + $bW * $tertiaryRGB['g']) / $sum;
608
609 $newB = ($rW * $primaryRGB['b']
610 + $gW * $secondaryRGB['b']
611 + $bW * $tertiaryRGB['b']) / $sum;
612 } else {
613 $newR = $newG = $newB = 0;
614 }
615
616 $w = min($baseR, $baseG, $baseB) / 255.0;
617
618 $newR = (int) round($newR + (255 - $newR) * $w);
619 $newG = (int) round($newG + (255 - $newG) * $w);
620 $newB = (int) round($newB + (255 - $newB) * $w);
621
622 $intensity = max($baseR, $baseG, $baseB) / 255.0; // 0..1 (how "strong" the mask is)
623
624 $newR *= $intensity;
625 $newG *= $intensity;
626 $newB *= $intensity;
627
628 $newR = max(0, min(255, $newR));
629 $newG = max(0, min(255, $newG));
630 $newB = max(0, min(255, $newB));
631
632 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
633 if (!isset($cache[$key])) {
634 $cache[$key] = imagecolorallocatealpha($image, intval($newR), intval($newG), intval($newB), intval($baseA));
635 }
636
637 imagesetpixel($image, $x, $y, $cache[$key]);
638 }
639 }
640
641 imagepng($image, $spritePath);
642 }
643
644
645 /**
646 * Convert HEX color string to RGB array
647 * @param string $hex HEX color in format #RRGGBB
648 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
649 */
650 private function hexToRgb($hex)
651 {
652 // Remove # if present
653 $hex = ltrim($hex, '#');
654
655 // Convert HEX to RGB
656 return [
657 'r' => hexdec(substr($hex, 0, 2)),
658 'g' => hexdec(substr($hex, 2, 2)),
659 'b' => hexdec(substr($hex, 4, 2))
660 ];
661 }
662}