BlueGit

blue-star tribegen

Files

tribegen / web / src / api / game.php

game.php

add fighting
timfa Tim Falken · pushed by timfa · 9 months ago
87adeb5e History
game.php 20.9 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 '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 $i = array_keys($tribe->kobolds)[$input['memberIndices'][0]];
333 $tribe->kobolds[$i]->setName($input['leaderName']);
334
335 for ($i = 0; $i < count($input['memberIndices']); $i++) {
336 $input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
337 }
338
339 $tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
340 return in_array($index, $input['memberIndices']);
341 }, ARRAY_FILTER_USE_BOTH);
342
343 $tribe->kobolds = array_values($tribe->kobolds);
344 $tribe->save();
345
346 echo json_encode([
347 'success' => true,
348 'tribe' => []
349 ]);
350 } catch (\Exception $e) {
351 http_response_code(400);
352 echo json_encode([
353 'success' => false,
354 'error' => $e->getMessage()
355 ]);
356 }
357 } elseif (strpos($apiPath, 'event') !== false) {
358 // Execute an event
359 try {
360 $userId = $input['userId'] ?? null;
361 $saveId = $input['saveId'] ?? null;
362
363 if (!$userId || !$saveId) {
364 throw new \Exception('User ID and Save ID required');
365 }
366
367 $tribe = Tribe::load($userId, $saveId);
368
369 // Execute event and get story. Allow passing participant kobold IDs.
370 $className = $input['eventType'] . "Event";
371 if (!class_exists($className))
372 throw new \Exception('Unknown event type');
373 $event = new $className($tribe);
374
375 // Player-started events MUST provide participants (array of kobold IDs)
376 $participants = $input['participants'] ?? null;
377 if (empty($participants) || !is_array($participants)) {
378 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
379 }
380
381 // validate count against event limits
382 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
383 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
384 $count = count($participants);
385 if ($count < $min || $count > $max) {
386 throw new \Exception("Participants must be between {$min} and {$max}");
387 }
388
389 $event->setParticipants($participants);
390
391 $event?->execute();
392 $story = $event?->getStory() ?? 'No event occurred.';
393
394 $tribe->save();
395
396 echo json_encode([
397 'success' => true,
398 'story' => $story
399 ]);
400 } catch (\Exception $e) {
401 http_response_code(400);
402 echo json_encode([
403 'success' => false,
404 'error' => $e->getMessage()
405 ]);
406 }
407 } elseif (strpos($apiPath, 'endMonth') !== false) {
408 // End the current month
409 try {
410 $userId = $input['userId'] ?? null;
411 $saveId = $input['saveId'] ?? null;
412
413 if (!$userId || !$saveId) {
414 throw new \Exception('User ID and Save ID required');
415 }
416
417 $tribe = Tribe::load($userId, $saveId);
418 $foodStory = $tribe->endMonth();
419
420 echo json_encode([
421 'success' => true,
422 'save' => [
423 'id' => $tribe->getSaveId(),
424 'current_month' => $tribe->getCurrentMonth(),
425 'current_season' => $tribe->getCurrentSeason(),
426 'food_count' => $tribe->getFoodCount()
427 ],
428 'monthStory' => $foodStory
429 ]);
430 } catch (\Exception $e) {
431 http_response_code(400);
432 echo json_encode([
433 'success' => false,
434 'error' => $e->getMessage()
435 ]);
436 }
437 }
438} elseif ($method === 'GET') {
439 $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
440
441 if (strpos($apiPath, 'sprite') !== false) {
442 // Serve a kobold sprite image
443 try {
444 $userId = $_GET['userId'] ?? null;
445 $koboldId = $_GET['koboldId'] ?? null;
446
447 if (!$userId || !$koboldId) {
448 throw new \Exception('User ID and Kobold ID required');
449 }
450
451 $saveManager = new SaveManager();
452 $ageSprite = $_GET['age'] ?? 'adult';
453 $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
454 $spriteFile = $spritePath;
455
456 if (!file_exists($spriteFile)) {
457 throw new \Exception('Sprite not found');
458 }
459
460 // Serve the sprite image
461 header('Content-Type: image/png');
462 header('Cache-Control: public, max-age=3600');
463 readfile($spriteFile);
464 exit;
465 } catch (\Exception $e) {
466 http_response_code(404);
467 echo json_encode([
468 'success' => false,
469 'error' => $e->getMessage()
470 ]);
471 }
472 } elseif (strpos($apiPath, 'list') !== false) {
473 // List saves for user
474 try {
475 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
476
477 if (!$userId) {
478 throw new \Exception('Not authenticated');
479 }
480
481 $user = new User($userId, '');
482 $saves = $user->getSaves();
483
484 echo json_encode([
485 'success' => true,
486 'saves' => $saves
487 ]);
488 } catch (\Exception $e) {
489 http_response_code(400);
490 echo json_encode([
491 'success' => false,
492 'error' => $e->getMessage()
493 ]);
494 }
495 } elseif (strpos($apiPath, 'load') !== false) {
496 // Load a specific game save
497 try {
498 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
499 $saveId = $_GET['saveId'] ?? null;
500
501 if (!$userId || !$saveId) {
502 throw new \Exception('User ID and Save ID required');
503 }
504
505 $tribe = Tribe::load($userId, $saveId);
506
507 // Get kobolds with full stats, items and injuries
508 $kobolds = [];
509 foreach ($tribe->getKobolds() as $kobold) {
510 $kInjuries = $kobold->getInjuries() ?? [];
511 // enrich injuries with required medicine mapping
512 foreach ($kInjuries as &$inj) {
513 $req = null;
514 if (class_exists('Injury')) {
515 $req = Injury::getCureForCategory($inj['category'] ?? null);
516 }
517 $inj['required_medicine'] = $req;
518 }
519
520 $kobolds[] = [
521 'id' => $kobold->getId(),
522 'name' => $kobold->getName(),
523 'age' => $kobold->getAge(),
524 'ageCategory' => $kobold->getAgeCategory(),
525 'stats' => [
526 'vitality' => $kobold->getStat('vitality'),
527 'intelligence' => $kobold->getStat('intelligence'),
528 'tinkering' => $kobold->getStat('tinkering'),
529 'medicine' => $kobold->getStat('medicine'),
530 'crafting' => $kobold->getStat('crafting'),
531 'personality' => $kobold->getStat('personality'),
532 'will' => $kobold->getStat('will'),
533 'fighting' => $kobold->getStat('fighting')
534 ],
535 'items' => $kobold->getItems() ?? [],
536 'injuries' => $kInjuries,
537 'male' => $kobold->getMale()
538 ];
539 }
540
541 // Get storage items
542 $storage = $tribe->getStorage();
543
544 echo json_encode([
545 'success' => true,
546 'save' => [
547 'id' => $tribe->getSaveId(),
548 'name' => $tribe->getName(),
549 'current_month' => $tribe->getCurrentMonth(),
550 'current_season' => $tribe->getCurrentSeason(),
551 'food_count' => $tribe->getFoodCount(),
552 'created_at' => $tribe->getCreatedAt(),
553 'last_played' => $tribe->getLastPlayed()
554 ],
555 'tribe' => [
556 'kobolds' => $kobolds,
557 'storage' => $storage
558 ]
559 ]);
560 } catch (\Exception $e) {
561 http_response_code(400);
562 echo json_encode([
563 'success' => false,
564 'error' => $e->getMessage()
565 ]);
566 }
567 }
568}
569