BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

injuries, cures, event edits
timfa Tim Falken · pushed by timfa · 9 months ago
146dd342 History
game.php 20.7 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../vendor/autoload.php';
4require_once __DIR__ . '/../../src/Database/Database.php';
5require_once __DIR__ . '/../../src/Classes/User.php';
6require_once __DIR__ . '/../../src/Classes/Tribe.php';
7require_once __DIR__ . '/../../src/Classes/Kobold.php';
8require_once __DIR__ . '/../../src/System/SaveManager.php';
9
10foreach (glob(__DIR__ . "/../../src/Events/*Event.php") as $file) {
11 require_once $file;
12}
13
14$method = $_SERVER['REQUEST_METHOD'];
15
16if ($method === 'POST') {
17 $input = json_decode(file_get_contents('php://input'), true);
18
19 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
20
21 if (strpos($apiPath, 'generation') !== false) {
22 // Generate initial kobolds for new game
23 try {
24 $userId = $input['userId'] ?? null;
25 if (!$userId) {
26 throw new \Exception('User ID required');
27 }
28
29 $tribe = Tribe::create($userId, $input['saveName']);
30
31 // Generate 20 random kobolds
32 $kobolds = [];
33 for ($i = 0; $i < 10; $i++) {
34 $kobold = Kobold::generate($userId, $tribe->getSaveId());
35 $tribe->addKobold($kobold);
36
37 $kobolds[] = [
38 'id' => $kobold->getId(),
39 'name' => $kobold->getName(),
40 'ageCategory' => $kobold->getAgeCategory(),
41 'age' => $kobold->getAge(),
42 'stats' => [
43 'vitality' => $kobold->getStat('vitality'),
44 'intelligence' => $kobold->getStat('intelligence'),
45 'tinkering' => $kobold->getStat('tinkering'),
46 'medicine' => $kobold->getStat('medicine'),
47 'crafting' => $kobold->getStat('crafting'),
48 'personality' => $kobold->getStat('personality'),
49 'will' => $kobold->getStat('will')
50 ]
51 ];
52 }
53
54 $tribe->save();
55
56 echo json_encode([
57 'success' => true,
58 'save' => [
59 'id' => $tribe->getSaveId(),
60 'name' => $input['saveName']
61 ],
62 'kobolds' => $kobolds
63 ]);
64 } catch (\Exception $e) {
65 http_response_code(400);
66 echo json_encode([
67 'success' => false,
68 'error' => $e->getMessage()
69 ]);
70 }
71 } elseif (strpos($apiPath, 'cureInjury') !== false) {
72 // Cure an injury using an item from a kobold's inventory
73 try {
74 $userId = $input['userId'] ?? null;
75 $saveId = $input['saveId'] ?? null;
76 $koboldId = $input['koboldId'] ?? null;
77 $injuryId = $input['injuryId'] ?? null;
78 $itemId = $input['itemId'] ?? null;
79
80 if (!$userId || !$saveId || !$koboldId || !$injuryId || !$itemId) {
81 throw new \Exception('userId, saveId, koboldId, injuryId and itemId are required');
82 }
83
84 $tribe = Tribe::load($userId, $saveId);
85
86 // find kobold
87 $target = null;
88 foreach ($tribe->getKobolds(true) as $k) {
89 if ($k->getId() === $koboldId) {
90 $target = $k;
91 break;
92 }
93 }
94
95 if (!$target)
96 throw new \Exception('Kobold not found');
97
98 // find injury in kobold
99 $injuries = $target->getInjuries() ?? [];
100 $injury = null;
101 foreach ($injuries as $inj) {
102 if ($inj['id'] === $injuryId) {
103 $injury = $inj;
104 break;
105 }
106 }
107
108 if (!$injury)
109 throw new \Exception('Injury not found');
110
111 // malnourished cannot be cured via item
112 if (($injury['category'] ?? '') === 'malnourished') {
113 throw new \Exception('Malnourishment is cured via feeding at month end');
114 }
115
116 // required medicine by category
117 $required = Injury::getCureForCategory($injury['category'] ?? null);
118 if (!$required)
119 throw new \Exception('This injury cannot be cured with items');
120
121 if ($required !== $itemId) {
122 throw new \Exception('Provided item does not match required medicine');
123 }
124
125 // check kobold has the item
126 $has = false;
127 $itemName = $itemId;
128 $newItems = [];
129 foreach ($target->getItems() ?? [] as $it) {
130 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
131 if ($iid === $itemId && !$has) {
132 $has = true;
133 // capture name if present
134 if (is_array($it) && isset($it['name']))
135 $itemName = $it['name'];
136 elseif (is_object($it) && method_exists($it, 'getName'))
137 $itemName = $it->getName();
138 // consume (skip adding to newItems)
139 continue;
140 }
141 $newItems[] = $it;
142 }
143
144 if (!$has)
145 throw new \Exception('Kobold does not have the required item');
146
147 // remove injury
148 $target->removeInjury($injuryId);
149
150 // set kobold items to newItems (consumed)
151 $reflection = new ReflectionClass($target);
152 if ($reflection->hasProperty('items')) {
153 $prop = $reflection->getProperty('items');
154 $prop->setAccessible(true);
155 $prop->setValue($target, $newItems);
156 }
157
158 // save tribe
159 $tribe->save();
160
161 $koboldName = $target->getName();
162 $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');
163
164 $story = "{$koboldName} used the {$itemName} to cure their {$injuryName}.";
165
166 echo json_encode(['success' => true, 'story' => $story]);
167 } catch (\Exception $e) {
168 http_response_code(400);
169 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
170 }
171 } elseif (strpos($apiPath, 'giveItem') !== false) {
172 // Move item from tribe storage to kobold inventory and save
173 try {
174 $userId = $input['userId'] ?? null;
175 $saveId = $input['saveId'] ?? null;
176 $koboldId = $input['koboldId'] ?? null;
177 $itemId = $input['itemId'] ?? null;
178
179 if (!$userId || !$saveId || !$koboldId || !$itemId) {
180 throw new \Exception('userId, saveId, koboldId and itemId are required');
181 }
182
183 $tribe = Tribe::load($userId, $saveId);
184
185 // find item in storage
186 $storage = $tribe->getStorage() ?? [];
187 $found = null;
188 $newStorage = [];
189 foreach ($storage as $s) {
190 $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
191 if ($sid === $itemId && $found === null) {
192 $found = $s;
193 continue;
194 }
195 $newStorage[] = $s;
196 }
197
198 if ($found === null)
199 throw new \Exception('Item not found in storage');
200
201 // find kobold
202 $target = null;
203 foreach ($tribe->getKobolds(true) as $k) {
204 if ($k->getId() === $koboldId) {
205 $target = $k;
206 break;
207 }
208 }
209 if (!$target)
210 throw new \Exception('Kobold not found');
211
212 // add item to kobold
213 if (method_exists($target, 'addItem')) {
214 $target->addItem($found);
215 } else {
216 // fallback: set via reflection
217 $ref = new ReflectionClass($target);
218 if ($ref->hasProperty('items')) {
219 $prop = $ref->getProperty('items');
220 $prop->setAccessible(true);
221 $items = $prop->getValue($target) ?? [];
222 $items[] = $found;
223 $prop->setValue($target, $items);
224 }
225 }
226
227 // write back storage
228 $refT = new ReflectionClass($tribe);
229 if ($refT->hasProperty('storage')) {
230 $p = $refT->getProperty('storage');
231 $p->setAccessible(true);
232 $p->setValue($tribe, array_values($newStorage));
233 }
234
235 $tribe->save();
236
237 $koboldName = $target->getName();
238 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
239 $story = "{$itemName} was given to {$koboldName}.";
240
241 echo json_encode(['success' => true, 'story' => $story]);
242 } catch (\Exception $e) {
243 http_response_code(400);
244 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
245 }
246 } elseif (strpos($apiPath, 'returnItem') !== false) {
247 // Move item from kobold inventory back to tribe storage and save
248 try {
249 $userId = $input['userId'] ?? null;
250 $saveId = $input['saveId'] ?? null;
251 $koboldId = $input['koboldId'] ?? null;
252 $itemId = $input['itemId'] ?? null;
253
254 if (!$userId || !$saveId || !$koboldId || !$itemId) {
255 throw new \Exception('userId, saveId, koboldId and itemId are required');
256 }
257
258 $tribe = Tribe::load($userId, $saveId);
259
260 // find kobold
261 $target = null;
262 foreach ($tribe->getKobolds(true) as $k) {
263 if ($k->getId() === $koboldId) {
264 $target = $k;
265 break;
266 }
267 }
268 if (!$target)
269 throw new \Exception('Kobold not found');
270
271 // find item in kobold inventory
272 $found = null;
273 $newItems = [];
274 foreach ($target->getItems() ?? [] as $it) {
275 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
276 if ($iid === $itemId && $found === null) {
277 $found = $it;
278 continue;
279 }
280 $newItems[] = $it;
281 }
282 if ($found === null)
283 throw new \Exception('Item not found on kobold');
284
285 // set kobold items
286 if (method_exists($target, 'removeItem')) {
287 $target->removeItem($itemId);
288 } else {
289 $ref = new ReflectionClass($target);
290 if ($ref->hasProperty('items')) {
291 $p = $ref->getProperty('items');
292 $p->setAccessible(true);
293 $p->setValue($target, $newItems);
294 }
295 }
296
297 // add to tribe storage
298 $storage = $tribe->getStorage() ?? [];
299 $storage[] = $found;
300 $refT = new ReflectionClass($tribe);
301 if ($refT->hasProperty('storage')) {
302 $p = $refT->getProperty('storage');
303 $p->setAccessible(true);
304 $p->setValue($tribe, $storage);
305 }
306
307 $tribe->save();
308
309 $koboldName = $target->getName();
310 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
311 $story = "{$koboldName} returned the {$itemName} to storage.";
312
313 echo json_encode(['success' => true, 'story' => $story]);
314 } catch (\Exception $e) {
315 http_response_code(400);
316 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
317 }
318 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
319 // Save tribe setup
320 try {
321 $userId = $input['userId'] ?? null;
322 $saveId = $input['saveId'] ?? null;
323
324 if (!$userId || !$saveId) {
325 throw new \Exception('User ID and Save ID required');
326 }
327
328 $tribe = Tribe::load($userId, $saveId);
329
330 $i = array_keys($tribe->kobolds)[$input['memberIndices'][0]];
331 $tribe->kobolds[$i]->setName($input['leaderName']);
332
333 for ($i = 0; $i < count($input['memberIndices']); $i++) {
334 $input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
335 }
336
337 $tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
338 return in_array($index, $input['memberIndices']);
339 }, ARRAY_FILTER_USE_BOTH);
340
341 $tribe->kobolds = array_values($tribe->kobolds);
342 $tribe->save();
343
344 echo json_encode([
345 'success' => true,
346 'tribe' => []
347 ]);
348 } catch (\Exception $e) {
349 http_response_code(400);
350 echo json_encode([
351 'success' => false,
352 'error' => $e->getMessage()
353 ]);
354 }
355 } elseif (strpos($apiPath, 'event') !== false) {
356 // Execute an event
357 try {
358 $userId = $input['userId'] ?? null;
359 $saveId = $input['saveId'] ?? null;
360
361 if (!$userId || !$saveId) {
362 throw new \Exception('User ID and Save ID required');
363 }
364
365 $tribe = Tribe::load($userId, $saveId);
366
367 // Execute event and get story. Allow passing participant kobold IDs.
368 $className = $input['eventType'] . "Event";
369 if (!class_exists($className))
370 throw new \Exception('Unknown event type');
371 $event = new $className($tribe);
372
373 // Player-started events MUST provide participants (array of kobold IDs)
374 $participants = $input['participants'] ?? null;
375 if (empty($participants) || !is_array($participants)) {
376 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
377 }
378
379 // validate count against event limits
380 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
381 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
382 $count = count($participants);
383 if ($count < $min || $count > $max) {
384 throw new \Exception("Participants must be between {$min} and {$max}");
385 }
386
387 $event->setParticipants($participants);
388
389 $event?->execute();
390 $story = $event?->getStory() ?? 'No event occurred.';
391
392 $tribe->save();
393
394 echo json_encode([
395 'success' => true,
396 'story' => $story
397 ]);
398 } catch (\Exception $e) {
399 http_response_code(400);
400 echo json_encode([
401 'success' => false,
402 'error' => $e->getMessage()
403 ]);
404 }
405 } elseif (strpos($apiPath, 'endMonth') !== false) {
406 // End the current month
407 try {
408 $userId = $input['userId'] ?? null;
409 $saveId = $input['saveId'] ?? null;
410
411 if (!$userId || !$saveId) {
412 throw new \Exception('User ID and Save ID required');
413 }
414
415 $tribe = Tribe::load($userId, $saveId);
416 $foodStory = $tribe->endMonth();
417
418 echo json_encode([
419 'success' => true,
420 'save' => [
421 'id' => $tribe->getSaveId(),
422 'current_month' => $tribe->getCurrentMonth(),
423 'current_season' => $tribe->getCurrentSeason(),
424 'food_count' => $tribe->getFoodCount()
425 ],
426 'monthStory' => $foodStory
427 ]);
428 } catch (\Exception $e) {
429 http_response_code(400);
430 echo json_encode([
431 'success' => false,
432 'error' => $e->getMessage()
433 ]);
434 }
435 }
436} elseif ($method === 'GET') {
437 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
438
439 if (strpos($apiPath, 'sprite') !== false) {
440 // Serve a kobold sprite image
441 try {
442 $userId = $_GET['userId'] ?? null;
443 $koboldId = $_GET['koboldId'] ?? null;
444
445 if (!$userId || !$koboldId) {
446 throw new \Exception('User ID and Kobold ID required');
447 }
448
449 $saveManager = new SaveManager();
450 $ageSprite = $_GET['age'] ?? 'adult';
451 $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
452 $spriteFile = $spritePath;
453
454 if (!file_exists($spriteFile)) {
455 throw new \Exception('Sprite not found');
456 }
457
458 // Serve the sprite image
459 header('Content-Type: image/png');
460 header('Cache-Control: public, max-age=3600');
461 readfile($spriteFile);
462 exit;
463 } catch (\Exception $e) {
464 http_response_code(404);
465 echo json_encode([
466 'success' => false,
467 'error' => $e->getMessage()
468 ]);
469 }
470 } elseif (strpos($apiPath, 'list') !== false) {
471 // List saves for user
472 try {
473 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
474
475 if (!$userId) {
476 throw new \Exception('Not authenticated');
477 }
478
479 $user = new User($userId, '');
480 $saves = $user->getSaves();
481
482 echo json_encode([
483 'success' => true,
484 'saves' => $saves
485 ]);
486 } catch (\Exception $e) {
487 http_response_code(400);
488 echo json_encode([
489 'success' => false,
490 'error' => $e->getMessage()
491 ]);
492 }
493 } elseif (strpos($apiPath, 'load') !== false) {
494 // Load a specific game save
495 try {
496 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
497 $saveId = $_GET['saveId'] ?? null;
498
499 if (!$userId || !$saveId) {
500 throw new \Exception('User ID and Save ID required');
501 }
502
503 $tribe = Tribe::load($userId, $saveId);
504
505 // Get kobolds with full stats, items and injuries
506 $kobolds = [];
507 foreach ($tribe->getKobolds() as $kobold) {
508 $kInjuries = $kobold->getInjuries() ?? [];
509 // enrich injuries with required medicine mapping
510 foreach ($kInjuries as &$inj) {
511 $req = null;
512 if (class_exists('Injury')) {
513 $req = Injury::getCureForCategory($inj['category'] ?? null);
514 }
515 $inj['required_medicine'] = $req;
516 }
517
518 $kobolds[] = [
519 'id' => $kobold->getId(),
520 'name' => $kobold->getName(),
521 'age' => $kobold->getAge(),
522 'ageCategory' => $kobold->getAgeCategory(),
523 'stats' => [
524 'vitality' => $kobold->getStat('vitality'),
525 'intelligence' => $kobold->getStat('intelligence'),
526 'tinkering' => $kobold->getStat('tinkering'),
527 'medicine' => $kobold->getStat('medicine'),
528 'crafting' => $kobold->getStat('crafting'),
529 'personality' => $kobold->getStat('personality'),
530 'will' => $kobold->getStat('will')
531 ],
532 'items' => $kobold->getItems() ?? [],
533 'injuries' => $kInjuries
534 ];
535 }
536
537 // Get storage items
538 $storage = $tribe->getStorage();
539
540 echo json_encode([
541 'success' => true,
542 'save' => [
543 'id' => $tribe->getSaveId(),
544 'name' => $tribe->getName(),
545 'current_month' => $tribe->getCurrentMonth(),
546 'current_season' => $tribe->getCurrentSeason(),
547 'food_count' => $tribe->getFoodCount(),
548 'created_at' => $tribe->getCreatedAt(),
549 'last_played' => $tribe->getLastPlayed()
550 ],
551 'tribe' => [
552 'kobolds' => $kobolds,
553 'storage' => $storage
554 ]
555 ]);
556 } catch (\Exception $e) {
557 http_response_code(400);
558 echo json_encode([
559 'success' => false,
560 'error' => $e->getMessage()
561 ]);
562 }
563 }
564}
565