BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

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