BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

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