BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

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