BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Kobold.php

Kobold.php

initial generation
timfa Tim · pushed by timfa · 9 months ago
0b655138 History
Kobold.php 13.6 KiB Download Raw
1<?php
2
3namespace TribeGen\Classes;
4
5use TribeGen\System\SaveManager;
6
7class Kobold
8{
9 private $id;
10 private $userId;
11 private $saveId;
12 private $name;
13 private $age;
14 private $stats = [];
15 private $spriteMorph;
16 private $isLeader;
17 private $isAlive = true;
18 private $isExpelled = false;
19 private $injuries = [];
20 private $items = [];
21 private $fatherId;
22 private $motherId;
23 private $saveManager;
24
25 private static $statNames = [
26 'vitality',
27 'intelligence',
28 'tinkering',
29 'medicine',
30 'crafting',
31 'personality',
32 'will'
33 ];
34
35 public function __construct($id, $userId, $saveId, $name, $age, $spriteMorph, $isLeader = false)
36 {
37 $this->id = $id;
38 $this->userId = $userId;
39 $this->saveId = $saveId;
40 $this->name = $name;
41 $this->age = $age;
42 $this->spriteMorph = $spriteMorph;
43 $this->isLeader = $isLeader;
44 $this->saveManager = new SaveManager();
45
46 // Initialize stats with random values
47 foreach (self::$statNames as $stat) {
48 $this->stats[$stat] = rand(0, 100);
49 }
50 }
51
52 public static function generate($userId, $saveId, $age = null)
53 {
54 if ($age === null) {
55 $age = rand(5, 20);
56 }
57
58 $spriteMorph = self::getRandomSpriteMorph();
59 $kobold = new self(uniqid('kob_'), $userId, $saveId, '', $age, $spriteMorph);
60
61 // Copy and transform sprite from assets to save folder
62 $kobold->initializeSprite();
63
64 return $kobold;
65 }
66
67 private static function getRandomSpriteMorph()
68 {
69 $morphsPath = __DIR__ . '/../../assets/sprites';
70 if (!is_dir($morphsPath)) {
71 return 'default';
72 }
73
74 $morphs = array_filter(scandir($morphsPath), function ($item) use ($morphsPath) {
75 return is_dir($morphsPath . '/' . $item) && $item[0] !== '.';
76 });
77
78 return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';
79 }
80
81 public static function fromArray($data, $userId, $saveId)
82 {
83 $kobold = new self(
84 $data['id'] ?? null,
85 $userId,
86 $saveId,
87 $data['name'] ?? '',
88 $data['age'] ?? 0,
89 $data['sprite_morph'] ?? 'default',
90 $data['is_leader'] ?? false
91 );
92
93 if (isset($data['stats'])) {
94 $kobold->stats = $data['stats'];
95 }
96
97 $kobold->isAlive = $data['is_alive'] ?? true;
98 $kobold->isExpelled = $data['is_expelled'] ?? false;
99 $kobold->injuries = $data['injuries'] ?? [];
100 $kobold->items = $data['items'] ?? [];
101 $kobold->fatherId = $data['father_id'] ?? null;
102 $kobold->motherId = $data['mother_id'] ?? null;
103
104 return $kobold;
105 }
106
107 public function toArray()
108 {
109 return [
110 'id' => $this->id,
111 'name' => $this->name,
112 'age' => $this->age,
113 'stats' => $this->stats,
114 'sprite_morph' => $this->spriteMorph,
115 'is_leader' => $this->isLeader,
116 'is_alive' => $this->isAlive,
117 'is_expelled' => $this->isExpelled,
118 'injuries' => $this->injuries,
119 'items' => $this->items,
120 'father_id' => $this->fatherId,
121 'mother_id' => $this->motherId
122 ];
123 }
124
125 public function save()
126 {
127 // Kobolds are saved as part of the Tribe's kobolds.json
128 // Sprite files are stored in:
129 // /data/saves/{userId}/kobolds/{koboldId}/sprites/
130 }
131
132 /**
133 * Initialize sprite by copying base sprite from assets and applying transformations
134 * Called on kobold generation to populate the save folder
135 */
136 private function initializeSprite()
137 {
138 $spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
139 $ageSprite = $this->getAgeSpriteName();
140 $sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
141 $destFile = $spriteDir . '/' . $ageSprite . '.png';
142
143 // Copy base sprite from assets
144 if (file_exists($sourceFile)) {
145 copy($sourceFile, $destFile);
146 }
147
148 // Apply transformations to the sprite
149 $this->transformSprite();
150 }
151
152 /**
153 * Get the sprite filename for current age
154 */
155 public function getAgeSpriteName()
156 {
157 $ageCategory = $this->getAgeCategory();
158 $spriteMap = [
159 'egg' => 'egg',
160 'baby' => 'baby',
161 'adult' => 'adult',
162 'old' => 'old',
163 'very_old' => 'old' // Reuse old sprite for very_old
164 ];
165
166 return $spriteMap[$ageCategory] ?? 'adult';
167 }
168
169 /**
170 * Get path to the kobold's sprite file for current age
171 */
172 public function getSpritePath()
173 {
174 $spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
175 $ageSprite = $this->getAgeSpriteName();
176 return $spriteDir . '/' . $ageSprite . '.png';
177 }
178
179 public function getId()
180 {
181 return $this->id;
182 }
183
184 public function getName()
185 {
186 return $this->name;
187 }
188
189 public function setName($name)
190 {
191 $this->name = $name;
192 }
193
194 public function getAge()
195 {
196 return $this->age;
197 }
198
199 public function setAge($age)
200 {
201 $this->age = max(0, $age);
202 }
203
204 public function incrementAge()
205 {
206 $this->age++;
207 }
208
209 public function getAgeCategory()
210 {
211 if ($this->age < 0)
212 return 'egg';
213 if ($this->age < 4)
214 return 'baby';
215 if ($this->age < 35)
216 return 'young';
217 if ($this->age < 60)
218 return 'adult';
219 return 'old';
220 }
221
222 public function getAgeProgress()
223 {
224 // Returns 0-1 indicating progress to next age tier
225 $ageTiers = [-1, 0, 4, 35, 60];
226
227 for ($i = 0; $i < count($ageTiers) - 1; $i++) {
228 $tierStart = $ageTiers[$i];
229 $tierEnd = $ageTiers[$i + 1];
230
231 if ($this->age >= $tierStart && $this->age < $tierEnd) {
232 $duration = $tierEnd - $tierStart;
233 $progress = ($this->age - $tierStart) / $duration;
234 return $progress;
235 }
236 }
237
238 return 1;
239 }
240
241 public function getStat($statName)
242 {
243 if (!isset($this->stats[$statName])) {
244 return null;
245 }
246
247 $baseStat = $this->stats[$statName];
248
249 // Scale stats for non-adult kobolds
250 if ($this->getAgeCategory() === 'baby' || $this->getAgeCategory() === 'egg') {
251 $baseStat = (int) ($baseStat * $this->getAgeProgress());
252 }
253
254 return $baseStat;
255 }
256
257 public function setStat($statName, $value)
258 {
259 if (isset($this->stats[$statName])) {
260 $this->stats[$statName] = max(0, min(100, $value));
261 }
262 }
263
264 public function checkStat($statName)
265 {
266 $stat = $this->getStat($statName);
267
268 // Apply injury modifications
269 $totalInjurySeverity = array_sum(array_column($this->injuries, 'severity', null));
270 if ($totalInjurySeverity === null) {
271 $totalInjurySeverity = 0;
272 }
273
274 $stat -= $totalInjurySeverity;
275 $stat = max(0, min(100, $stat));
276
277 // Roll under 1d100
278 $roll = rand(1, 100);
279 return $roll <= $stat;
280 }
281
282 public function addInjury($injuryType, $category, $severity = 1)
283 {
284 $id = uniqid('inj_');
285
286 $this->injuries[] = [
287 'id' => $id,
288 'kobold_id' => $this->id,
289 'injury_type' => $injuryType,
290 'category' => $category,
291 'severity' => $severity
292 ];
293 }
294
295 public function removeInjury($injuryId)
296 {
297 $this->injuries = array_filter($this->injuries, fn($inj) => $inj['id'] !== $injuryId);
298 }
299
300 public function getInjuries()
301 {
302 return $this->injuries;
303 }
304
305 public function getTotalInjurySeverity()
306 {
307 $sum = 0;
308 foreach ($this->injuries as $injury) {
309 $sum += $injury['severity'] ?? 0;
310 }
311 return $sum;
312 }
313
314 public function isDead()
315 {
316 return $this->getTotalInjurySeverity() >= $this->getStat('vitality') || !$this->isAlive;
317 }
318
319 public function isExpelled()
320 {
321 return $this->isExpelled;
322 }
323
324 public function setExpelled($expelled)
325 {
326 $this->isExpelled = $expelled;
327 }
328
329 public function die()
330 {
331 $this->isAlive = false;
332 }
333
334 public function getSpriteMorph()
335 {
336 return $this->spriteMorph;
337 }
338
339 public function getStatLabel($statValue)
340 {
341 if ($statValue >= 90)
342 return 'godlike';
343 if ($statValue >= 80)
344 return 'divine';
345 if ($statValue >= 70)
346 return 'master';
347 if ($statValue >= 60)
348 return 'fantastic';
349 if ($statValue >= 50)
350 return 'excellent';
351 if ($statValue >= 40)
352 return 'good';
353 if ($statValue >= 30)
354 return 'decent';
355 if ($statValue >= 20)
356 return 'unskilled';
357 if ($statValue >= 10)
358 return 'bad';
359 return 'terrible';
360 }
361
362 public function setParents($fatherId, $motherId)
363 {
364 $this->fatherId = $fatherId;
365 $this->motherId = $motherId;
366 }
367
368 public function getParents()
369 {
370 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
371 }
372
373 /**
374 * Apply transformations to sprite (injuries, age coloring, leadership marks)
375 * Uses PHP GD library to modify the sprite image
376 */
377 private function transformSprite()
378 {
379 $spritePath = $this->getSpritePath();
380
381 if (!file_exists($spritePath)) {
382 return; // Base sprite not created yet
383 }
384
385 // Load the image
386 $image = imagecreatefrompng($spritePath);
387 if (!$image) {
388 return; // Failed to load image
389 }
390
391 // Apply injury markings if kobold has taken damage
392 $vitalityStat = $this->getStat('vitality');
393 if ($vitalityStat < 50) {
394 $this->applyInjuryMarkings($image);
395 }
396
397 // Apply age-based color adjustments (desaturate for elderly)
398 if ($this->getAgeCategory() === 'old' || $this->getAgeCategory() === 'very_old') {
399 $this->desaturateImage($image);
400 }
401
402 // Apply leadership marking if this kobold has high will stat
403 if ($this->getStat('will') > 70) {
404 $this->addLeadershipMarkings($image);
405 }
406
407 // Save modified image back to the sprite file
408 imagepng($image, $spritePath);
409 imagedestroy($image);
410 }
411
412 /**
413 * Draw injury marks (red scars) on the sprite
414 * Number of marks increases with injury level
415 */
416 private function applyInjuryMarkings(&$image)
417 {
418 $red = imagecolorallocate($image, 255, 0, 0);
419 $darkRed = imagecolorallocate($image, 139, 0, 0);
420
421 // Number of scars based on vitality stat
422 $vitalityStat = $this->getStat('vitality');
423 $scarCount = intval((50 - $vitalityStat) / 10) + 1;
424 $scarCount = min(5, $scarCount);
425
426 $imageWidth = imagesx($image);
427 $imageHeight = imagesy($image);
428
429 // Draw scars at various positions
430 for ($i = 0; $i < $scarCount; $i++) {
431 $x = rand(10, $imageWidth - 10);
432 $y = rand(10, $imageHeight - 10);
433 $length = rand(5, 15);
434
435 // Draw a jagged line scar
436 imageline($image, $x, $y, $x + $length, $y, $darkRed);
437 imageline($image, $x, $y + 1, $x + $length, $y + 1, $red);
438 }
439 }
440
441 /**
442 * Desaturate the sprite image for elderly kobolds
443 * Reduces color saturation to make them appear older
444 */
445 private function desaturateImage(&$image)
446 {
447 $imageWidth = imagesx($image);
448 $imageHeight = imagesy($image);
449
450 for ($y = 0; $y < $imageHeight; $y++) {
451 for ($x = 0; $x < $imageWidth; $x++) {
452 $rgb = imagecolorat($image, $x, $y);
453
454 // Extract color components
455 $r = ($rgb >> 16) & 0xFF;
456 $g = ($rgb >> 8) & 0xFF;
457 $b = $rgb & 0xFF;
458 $a = ($rgb >> 24) & 0xFF;
459
460 // Calculate grayscale value using luminance formula
461 $gray = intval(0.299 * $r + 0.587 * $g + 0.114 * $b);
462
463 // Blend original color with grayscale (60% desaturated)
464 $newR = intval($r * 0.4 + $gray * 0.6);
465 $newG = intval($g * 0.4 + $gray * 0.6);
466 $newB = intval($b * 0.4 + $gray * 0.6);
467
468 $newColor = imagecolorallocatealpha($image, $newR, $newG, $newB, $a);
469 imagesetpixel($image, $x, $y, $newColor);
470 }
471 }
472 }
473
474 /**
475 * Add leadership marking (gold crown) to indicate a leader
476 */
477 private function addLeadershipMarkings(&$image)
478 {
479 $gold = imagecolorallocate($image, 255, 215, 0);
480 $darkGold = imagecolorallocate($image, 184, 155, 0);
481
482 $imageWidth = imagesx($image);
483 $topY = 5;
484 $crownX = intval($imageWidth / 2);
485
486 // Draw a simple crown shape at the top center
487 // Left peak
488 imageline($image, $crownX - 15, $topY + 10, $crownX - 10, $topY, $gold);
489 // Center peak
490 imageline($image, $crownX - 10, $topY, $crownX, $topY - 5, $gold);
491 imageline($image, $crownX, $topY - 5, $crownX + 10, $topY, $gold);
492 // Right peak
493 imageline($image, $crownX + 10, $topY, $crownX + 15, $topY + 10, $gold);
494
495 // Base of crown
496 imageline($image, $crownX - 15, $topY + 10, $crownX + 15, $topY + 10, $darkGold);
497 }
498}