BlueGit

blue-star tribegen

Files

tribegen / web / src / Utilities / GameHelper.php

GameHelper.php

farming
timfa Tim · pushed by timfa · 9 months ago
569cc974 History
GameHelper.php 9.2 KiB Download Raw
1<?php
2
3class GameHelper
4{
5 /**
6 * Delete cached kobold sprite sets for kobolds not present in any save for a user
7 * @param int $userId
8 * @return array List of deleted kobold IDs
9 */
10
11 public static function cleanupUnusedKoboldSprites($userId)
12 {
13 $deleted = [];
14 $saveManager = new \SaveManager();
15 $userSavesPath = $saveManager->getUserSavesPath($userId);
16 $koboldsDir = $userSavesPath . '/kobolds';
17 if (!is_dir($koboldsDir))
18 return $deleted;
19
20 // 1. Collect all kobold IDs in all saves for this user
21 $activeKoboldIds = [];
22 $saveDirs = glob($userSavesPath . '/*', GLOB_ONLYDIR);
23 foreach ($saveDirs as $saveDir) {
24 $koboldsJson = $saveDir . '/kobolds.json';
25 if (file_exists($koboldsJson)) {
26 $data = json_decode(file_get_contents($koboldsJson), true);
27 if (is_array($data)) {
28 foreach ($data as $kobold) {
29 if (isset($kobold['id'])) {
30 $activeKoboldIds[$kobold['id']] = true;
31 }
32 }
33 }
34 }
35 }
36
37 // 2. Scan kobolds/ for all sprite sets
38 $dirs = glob($koboldsDir . '/kob_*', GLOB_ONLYDIR);
39 foreach ($dirs as $koboldDir) {
40 $koboldId = basename($koboldDir);
41 if (!isset($activeKoboldIds[$koboldId])) {
42 // Delete the entire kobold sprite directory
43 self::rrmdir($koboldDir);
44 $deleted[] = $koboldId;
45 }
46 }
47 return $deleted;
48 }
49
50 /**
51 * Recursively remove a directory
52 */
53 private static function rrmdir($dir)
54 {
55 if (!is_dir($dir))
56 return;
57 $items = scandir($dir);
58 foreach ($items as $item) {
59 if ($item === '.' || $item === '..')
60 continue;
61 $path = $dir . DIRECTORY_SEPARATOR . $item;
62 if (is_dir($path)) {
63 self::rrmdir($path);
64 } else {
65 @unlink($path);
66 }
67 }
68 @rmdir($dir);
69 }
70
71 /**
72 * Get stat display label from numeric value
73 */
74 public static function getStatLabel($value)
75 {
76 $value = max(0, min(100, $value));
77
78 if ($value >= 90)
79 return 'godlike';
80 if ($value >= 80)
81 return 'divine';
82 if ($value >= 70)
83 return 'master';
84 if ($value >= 60)
85 return 'fantastic';
86 if ($value >= 50)
87 return 'excellent';
88 if ($value >= 40)
89 return 'good';
90 if ($value >= 30)
91 return 'decent';
92 if ($value >= 20)
93 return 'unskilled';
94 if ($value >= 10)
95 return 'bad';
96 return 'terrible';
97 }
98
99 /**
100 * Roll 1d100 under value
101 */
102 public static function rollUnder($value)
103 {
104 $value = max(0, min(100, $value));
105 $roll = rand(1, 100);
106 return $roll <= $value;
107 }
108
109 /**
110 * Get age category for display
111 */
112 public static function getAgeCategory($age)
113 {
114 if ($age < 0)
115 return 'egg';
116 if ($age < 4)
117 return 'baby';
118 if ($age < 17)
119 return 'young';
120 if ($age < 40)
121 return 'adult';
122
123 return 'old';
124 }
125
126 /**
127 * Get sprite name for age category
128 */
129 public static function getAgeSprite($ageCategory)
130 {
131 $spriteMap = [
132 'egg' => 'egg',
133 'baby' => 'baby',
134 'young' => 'young',
135 'adult' => 'adult',
136 'old' => 'old'
137 ];
138
139 return $spriteMap[$ageCategory] ?? 'adult';
140 }
141
142 /**
143 * Get season for month number
144 */
145 public static function getSeason($month)
146 {
147 $seasons = ['spring', 'summer', 'autumn', 'winter'];
148 return $seasons[($month / 3) % 4];
149 }
150
151 /**
152 * Check if kobold can have old-age injury
153 */
154 public static function shouldCheckOldAgeInjury($age)
155 {
156 return $age >= 35;
157 }
158
159 /**
160 * Get stat value with age scaling
161 */
162 public static function getEffectiveStat($baseStat, $age)
163 {
164 $ageCategory = self::getAgeCategory($age);
165
166 // For babies and eggs, scale by age
167 if ($ageCategory === 'egg') {
168 return 0; // Eggs can't do anything
169 }
170
171 if ($ageCategory === 'baby') {
172 // Progress from 0 to 4 years = 0% to 100%
173 $progress = $age / 4;
174 return (int) ($baseStat * $progress);
175 }
176
177 // Adults at full value
178 return $baseStat;
179 }
180
181 /**
182 * Get random name from list
183 */
184 public static function getRandomKoboldName()
185 {
186 $names = [
187 'Zyx',
188 'Krellin',
189 'Tik',
190 'Borp',
191 'Schnax',
192 'Grell',
193 'Vix',
194 'Nok',
195 'Pix',
196 'Grin',
197 'Skitter',
198 'Blort',
199 'Zap',
200 'Clicket',
201 'Snort',
202 'Gik',
203 'Spork',
204 'Krunk',
205 'Vik',
206 'Tock',
207 'Blix',
208 'Zazzle',
209 'Sprocket',
210 'Klik',
211 'Fizz',
212 'Gorp',
213 'Skronk',
214 'Thrall',
215 'Glint',
216 'Zink',
217 'Plock',
218 'Bzzzt'
219 ];
220
221 return $names[array_rand($names)];
222 }
223
224 /**
225 * Generate random stats
226 */
227 public static function generateRandomStats()
228 {
229 $stats = [];
230 $statNames = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
231
232 foreach ($statNames as $stat) {
233 $stats[$stat] = rand(0, 100);
234 }
235
236 return $stats;
237 }
238
239 /**
240 * Format story text (for narrative generation)
241 */
242 public static function formatStory($text)
243 {
244 // Could add markdown parsing, formatting, etc.
245 return nl2br(htmlspecialchars($text));
246 }
247
248 /**
249 * Get injury cure type
250 */
251 public static function getInjuryCure($injuryCategory)
252 {
253 $cureMap = [
254 'wound' => 'basic_medicine',
255 'fracture' => 'bone_setting',
256 'infection' => 'healing_herbs',
257 'poison' => 'antidote',
258 'burn' => 'burn_salve',
259 'malnourished' => 'food',
260 'old-age' => null
261 ];
262
263 return $cureMap[$injuryCategory] ?? null;
264 }
265
266 /**
267 * Check if injury is treatable
268 */
269 public static function isInjuryTreatable($injuryCategory)
270 {
271 return self::getInjuryCure($injuryCategory) !== null;
272 }
273
274 /**
275 * Capitalize words
276 */
277 public static function humanize($text)
278 {
279 return ucfirst(str_replace('_', ' ', $text));
280 }
281
282 /**
283 * Load item from JSON file by ID
284 *
285 * @param string $itemId The filename without extension (e.g. 'book')
286 * @return Item|null The loaded item or null if file not found
287 */
288 public static function loadItem($itemId)
289 {
290 require_once __DIR__ . '/../Classes/Item.php';
291
292 $itemPath = __DIR__ . '/../../assets/items/' . $itemId . '.json';
293
294 if (!file_exists($itemPath)) {
295 return null;
296 }
297
298 $json = file_get_contents($itemPath);
299 $data = json_decode($json, true);
300
301 if (!$data) {
302 return null;
303 }
304
305 // Create Item with filename as ID
306 $item = new Item(
307 $itemId,
308 $data['name'] ?? '',
309 $data['description'] ?? '',
310 $data['itemType'] ?? 'generic',
311 $data['statModifications'] ?? []
312 );
313
314 return $item;
315 }
316
317 /**
318 * Load injury from JSON file by ID
319 *
320 * @param string $injuryId filename without extension (e.g. 'brokenLeg')
321 * @return array|null normalized injury array or null if not found
322 */
323 public static function loadInjury(string $injuryId)
324 {
325 $injuryPath = __DIR__ . '/../../assets/injuries/' . $injuryId . '.json';
326
327 if (!file_exists($injuryPath)) {
328 return null;
329 }
330
331 $json = file_get_contents($injuryPath);
332 $data = json_decode($json, true);
333 if (!$data)
334 return null;
335
336 // Normalize to snake_case keys matching internal storage
337 $inj = [];
338 $inj['id'] = $injuryId;
339 $inj['injury_type'] = $data['injuryType'] ?? ($data['injury_type'] ?? $injuryId);
340 $inj['description'] = $data['description'] ?? '';
341 $inj['category'] = $data['category'] ?? null;
342 $inj['severity'] = $data['severity'] ?? ($data['severity'] ?? 1);
343 $inj['stat_modifications'] = $data['statModifications'] ?? $data['stat_modifications'] ?? [];
344 $inj['required_medicine'] = Injury::getCureForCategory($inj['category']);
345
346 return $inj;
347 }
348
349 public static function findBestKoboldForStat(array $kobolds, string $skillId): Kobold
350 {
351 $highest = -1;
352 $selected = null;
353
354 for ($k = 0; $k < count($kobolds); $k++) {
355 $kobold = $kobolds[$k];
356 if ($kobold->getStat($skillId) > $highest) {
357 $highest = $kobold->getStat($skillId);
358 $selected = $kobold;
359 }
360 }
361
362 return $selected;
363 }
364}