BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

mostly working
timfa Tim · pushed by timfa · 9 months ago
64970ec3 History
Kobold.php 14.9 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', 'Gnak', 'Drog', 'Mog', 'Bik', 'Zag', 'Kra', 'Snak',
115 'Grok', 'Tik', 'Nag', 'Brack', 'Flak', 'Grat', 'Krag', 'Skrit',
116 'Zik', 'Bog', 'Crag', 'Gull', 'Kith', 'Mick', 'Nib', 'Prat',
117 'Rik', 'Tig', 'Vex', 'Wik', 'Xak', 'Yak', 'Zap'
118 ];
119
120 $lastSyllables = [
121 'ink', 'ack', 'og', 'ag', 'ug', 'ik', 'ek', 'ock',
122 'ar', 'ax', 'er', 'it', 'ut', 'ot', 'or', 'in',
123 'an', 'en', 'un', 'on', 'oo', 'ee', 'im', 'um'
124 ];
125
126 $firstName = $firstSyllables[array_rand($firstSyllables)];
127 $lastName = $lastSyllables[array_rand($lastSyllables)];
128
129 return $firstName . $lastName;
130 }
131
132 public static function fromArray($data, $userId, $saveId)
133 {
134 $kobold = new self(
135 $data['id'] ?? null,
136 $userId,
137 $saveId,
138 $data['name'] ?? '',
139 $data['age'] ?? 0,
140 $data['sprite_morph'] ?? 'default',
141 $data['is_leader'] ?? false
142 );
143
144 if (isset($data['stats'])) {
145 $kobold->stats = $data['stats'];
146 }
147
148 $kobold->isAlive = $data['is_alive'] ?? true;
149 $kobold->isExpelled = $data['is_expelled'] ?? false;
150 $kobold->injuries = $data['injuries'] ?? [];
151 $kobold->items = $data['items'] ?? [];
152 $kobold->fatherId = $data['father_id'] ?? null;
153 $kobold->motherId = $data['mother_id'] ?? null;
154
155 $kobold->colourPrimary = $data['colour_primary'] ?? '#FFFFFF';
156 $kobold->colourSecondary = $data['colour_secondary'] ?? '#FFFFFF';
157 $kobold->colourTertiary = $data['colour_tertiary'] ?? '#FFFFFF';
158
159 return $kobold;
160 }
161
162 public function toArray()
163 {
164 return [
165 'id' => $this->id,
166 'name' => $this->name,
167 'age' => $this->age,
168 'ageCategory' => $this->getAgeCategory(),
169 'stats' => $this->stats,
170 'sprite_morph' => $this->spriteMorph,
171 'is_leader' => $this->isLeader,
172 'is_alive' => $this->isAlive,
173 'is_expelled' => $this->isExpelled,
174 'injuries' => $this->injuries,
175 'items' => $this->items,
176 'father_id' => $this->fatherId,
177 'mother_id' => $this->motherId,
178 'colour_primary' => $this->colourPrimary,
179 'colour_secondary' => $this->colourSecondary,
180 'colour_tertiary' => $this->colourTertiary
181 ];
182 }
183
184 public function save()
185 {
186 // Kobolds are saved as part of the Tribe's kobolds.json
187 // Sprite files are stored in:
188 // /data/saves/{userId}/kobolds/{koboldId}/sprites/
189 }
190
191 /**
192 * Initialize sprite by copying base sprite from assets and applying transformations
193 * Called on kobold generation to populate the save folder
194 */
195 private function initializeSprite()
196 {
197 $ageSprite = $this->getAgeSpriteName();
198 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);
199 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
200 $destFile = $spriteDir;
201
202 // Copy base sprite from assets
203 if (file_exists($sourceFile)) {
204 copy($sourceFile, $destFile);
205 }
206
207 // Apply transformations to the sprite
208 $this->transformSprite($destFile);
209 }
210
211 /**
212 * Get the sprite filename for current age
213 */
214 public function getAgeSpriteName()
215 {
216 $ageCategory = $this->getAgeCategory();
217 $spriteMap = [
218 'egg' => 'egg',
219 'baby' => 'baby',
220 'young' => 'young',
221 'adult' => 'adult',
222 'old' => 'old' // Reuse old sprite for very_old
223 ];
224
225 return $spriteMap[$ageCategory] ?? 'adult';
226 }
227
228 /**
229 * Get path to the kobold's sprite file for current age
230 */
231 public function getSpritePath($age)
232 {
233 $spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);
234 $ageSprite = $age ?? $this->getAgeSpriteName();
235 $destFile = $spriteDir;
236
237 if (!file_exists($destFile)) {
238 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
239
240 // Copy base sprite from assets
241 if (file_exists($sourceFile)) {
242 copy($sourceFile, $destFile);
243 }
244
245 // Apply transformations to the sprite
246 $this->transformSprite($destFile);
247 }
248
249 return $destFile;
250 }
251
252 public function getId()
253 {
254 return $this->id;
255 }
256
257 public function getName()
258 {
259 return $this->name;
260 }
261
262 public function setName($name)
263 {
264 $this->name = $name;
265 }
266
267 public function getAge()
268 {
269 return $this->age;
270 }
271
272 public function setAge($age)
273 {
274 $this->age = max(0, $age);
275 }
276
277 public function incrementAge()
278 {
279 $this->age++;
280 }
281
282 public function getAgeCategory()
283 {
284 if ($this->age < 0)
285 return 'egg';
286 if ($this->age < 4)
287 return 'baby';
288 if ($this->age < 35)
289 return 'young';
290 if ($this->age < 60)
291 return 'adult';
292 return 'old';
293 }
294
295 public function getAgeProgress()
296 {
297 // Returns 0-1 indicating progress to next age tier
298 $ageTiers = [-1, 0, 4, 35, 60];
299
300 for ($i = 0; $i < count($ageTiers) - 1; $i++) {
301 $tierStart = $ageTiers[$i];
302 $tierEnd = $ageTiers[$i + 1];
303
304 if ($this->age >= $tierStart && $this->age < $tierEnd) {
305 $duration = $tierEnd - $tierStart;
306 $progress = ($this->age - $tierStart) / $duration;
307 return $progress;
308 }
309 }
310
311 return 1;
312 }
313
314 public function getStat($statName)
315 {
316 if (!isset($this->stats[$statName])) {
317 return null;
318 }
319
320 $baseStat = $this->stats[$statName];
321
322 // Scale stats for non-adult kobolds
323 if ($this->getAgeCategory() === 'baby' || $this->getAgeCategory() === 'egg') {
324 $baseStat = (int) ($baseStat * $this->getAgeProgress());
325 }
326
327 return $baseStat;
328 }
329
330 public function setStat($statName, $value)
331 {
332 if (isset($this->stats[$statName])) {
333 $this->stats[$statName] = max(0, min(100, $value));
334 }
335 }
336
337 public function checkStat($statName)
338 {
339 $stat = $this->getStat($statName);
340
341 // Apply injury modifications
342 $totalInjurySeverity = array_sum(array_column($this->injuries, 'severity', null));
343 if ($totalInjurySeverity === null) {
344 $totalInjurySeverity = 0;
345 }
346
347 $stat -= $totalInjurySeverity;
348 $stat = max(0, min(100, $stat));
349
350 // Roll under 1d100
351 $roll = rand(1, 100);
352 return $roll <= $stat;
353 }
354
355 public function addInjury($injuryType, $category, $severity = 1)
356 {
357 $id = uniqid('inj_');
358
359 $this->injuries[] = [
360 'id' => $id,
361 'kobold_id' => $this->id,
362 'injury_type' => $injuryType,
363 'category' => $category,
364 'severity' => $severity
365 ];
366 }
367
368 public function removeInjury($injuryId)
369 {
370 $this->injuries = array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId);
371 }
372
373 public function getInjuries()
374 {
375 return $this->injuries;
376 }
377
378 public function getTotalInjurySeverity()
379 {
380 $sum = 0;
381 foreach ($this->injuries as $injury) {
382 $sum += $injury['severity'] ?? 0;
383 }
384 return $sum;
385 }
386
387 public function isDead()
388 {
389 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
390 }
391
392 public function isExpelled()
393 {
394 return $this->isExpelled;
395 }
396
397 public function setExpelled($expelled)
398 {
399 $this->isExpelled = $expelled;
400 }
401
402 public function die()
403 {
404 $this->isAlive = false;
405 }
406
407 public function getSpriteMorph()
408 {
409 return $this->spriteMorph;
410 }
411
412 public function getStatLabel($statValue)
413 {
414 if ($statValue >= 90)
415 return 'godlike';
416 if ($statValue >= 80)
417 return 'divine';
418 if ($statValue >= 70)
419 return 'master';
420 if ($statValue >= 60)
421 return 'fantastic';
422 if ($statValue >= 50)
423 return 'excellent';
424 if ($statValue >= 40)
425 return 'good';
426 if ($statValue >= 30)
427 return 'decent';
428 if ($statValue >= 20)
429 return 'unskilled';
430 if ($statValue >= 10)
431 return 'bad';
432 return 'terrible';
433 }
434
435 public function setParents($fatherId, $motherId)
436 {
437 $this->fatherId = $fatherId;
438 $this->motherId = $motherId;
439 }
440
441 public function getParents()
442 {
443 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
444 }
445
446 /**
447 * Apply transformations to sprite (injuries, age coloring, leadership marks)
448 * Uses PHP GD library to modify the sprite image
449 */
450 private function transformSprite($spritePath)
451 {
452 if (!file_exists($spritePath))
453 return;
454
455 $image = imagecreatefrompng($spritePath);
456 if (!$image)
457 return;
458
459 // Ensure truecolour (important if PNG is palette-based)
460 if (!imageistruecolor($image)) {
461 imagepalettetotruecolor($image);
462 }
463
464 $primaryRGB = $this->hexToRgb($this->colourPrimary);
465 $secondaryRGB = $this->hexToRgb($this->colourSecondary);
466 $tertiaryRGB = $this->hexToRgb($this->colourTertiary);
467
468 $width = imagesx($image);
469 $height = imagesy($image);
470
471 // For exact per-pixel alpha writes:
472 imagealphablending($image, false);
473 imagesavealpha($image, true);
474
475 $cache = []; // cache allocated colours "r,g,b,a" => int
476
477 for ($y = 0; $y < $height; $y++) {
478 for ($x = 0; $x < $width; $x++) {
479 $idx = imagecolorat($image, $x, $y);
480 $rgba = imagecolorsforindex($image, $idx);
481
482 $baseR = $rgba['red'];
483 $baseG = $rgba['green'];
484 $baseB = $rgba['blue'];
485 $baseA = $rgba['alpha']; // 0..127
486
487 // If fully transparent, skip work (optional)
488 if ($baseA === 127) {
489 continue;
490 }
491
492 $newR = 0;
493 $newG = 0;
494 $newB = 0;
495
496 $newR += (int) (($baseR / 255.0) * $primaryRGB['r']);
497 $newG += (int) (($baseR / 255.0) * $primaryRGB['g']);
498 $newB += (int) (($baseR / 255.0) * $primaryRGB['b']);
499
500 $newR += (int) (($baseG / 255.0) * $secondaryRGB['r']);
501 $newG += (int) (($baseG / 255.0) * $secondaryRGB['g']);
502 $newB += (int) (($baseG / 255.0) * $secondaryRGB['b']);
503
504 $newR += (int) (($baseB / 255.0) * $tertiaryRGB['r']);
505 $newG += (int) (($baseB / 255.0) * $tertiaryRGB['g']);
506 $newB += (int) (($baseB / 255.0) * $tertiaryRGB['b']);
507
508 $newR = max(0, min(255, $newR));
509 $newG = max(0, min(255, $newG));
510 $newB = max(0, min(255, $newB));
511
512 $key = $newR . ',' . $newG . ',' . $newB . ',' . $baseA;
513 if (!isset($cache[$key])) {
514 $cache[$key] = imagecolorallocatealpha($image, $newR, $newG, $newB, $baseA);
515 }
516
517 imagesetpixel($image, $x, $y, $cache[$key]);
518 }
519 }
520
521 imagepng($image, $spritePath);
522 }
523
524
525 /**
526 * Convert HEX color string to RGB array
527 * @param string $hex HEX color in format #RRGGBB
528 * @return array ['r' => 0-255, 'g' => 0-255, 'b' => 0-255]
529 */
530 private function hexToRgb($hex)
531 {
532 // Remove # if present
533 $hex = ltrim($hex, '#');
534
535 // Convert HEX to RGB
536 return [
537 'r' => hexdec(substr($hex, 0, 2)),
538 'g' => hexdec(substr($hex, 2, 2)),
539 'b' => hexdec(substr($hex, 4, 2))
540 ];
541 }
542}