BlueGit

blue-star tribegen

Files

tribegen / web / src / Classes / Tribe.php

Tribe.php

various fixes
timfa Tim · pushed by timfa · 9 months ago
49730f61 History
Tribe.php 11.8 KiB Download Raw
1<?php
2
3require_once __DIR__ . '/../../src/System/SaveManager.php';
4require_once __DIR__ . '/../../src/Classes/Kobold.php';
5
6class Tribe
7{
8 private $userId;
9 private $saveId;
10 private $name;
11 private $kobolds = [];
12 private $storage = [];
13 private $currentMonth = 0;
14 private $currentSeason = 'spring';
15 private $foodCount = 0;
16 private $createdAt;
17 private $lastPlayed;
18 private $saveManager;
19
20 // Food requirement by age tier (portion units)
21 private $foodRequirements = [
22 'egg' => 0, // Eggs don't eat
23 'baby' => 0.5, // Babies eat less
24 'adult' => 1.0, // Adults eat standard amount
25 'old' => 0.6, // Elderly eat less
26 'very_old' => 0.4 // Very old eat even less
27 ];
28
29 public function __construct($userId, $saveId, $name = '')
30 {
31 $this->userId = $userId;
32 $this->saveId = $saveId;
33 $this->name = $name;
34 $this->saveManager = new SaveManager();
35 $this->loadFromFile();
36 }
37
38 public static function create($userId, $saveName)
39 {
40 $saveManager = new SaveManager();
41 $saveId = $saveManager->generateSaveId($userId);
42
43 $tribe = new self($userId, $saveId, $saveName);
44 $tribe->createdAt = date('Y-m-d H:i:s');
45 $tribe->lastPlayed = date('Y-m-d H:i:s');
46 $tribe->save();
47
48 return $tribe;
49 }
50
51 public static function load($userId, $saveId)
52 {
53 return new self($userId, $saveId);
54 }
55
56 private function loadFromFile()
57 {
58 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
59 $saveFile = $savePath . '/save.json';
60
61 if (file_exists($saveFile)) {
62 $data = $this->saveManager->loadJson($saveFile);
63
64 if ($data) {
65 $this->name = $data['name'] ?? '';
66 $this->currentMonth = $data['current_month'] ?? 0;
67 $this->currentSeason = $data['current_season'] ?? 'spring';
68 $this->foodCount = $data['food_count'] ?? 0;
69 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
70 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
71 }
72 }
73
74 $this->loadKobolds();
75 $this->loadStorage();
76 }
77
78 private function loadKobolds()
79 {
80 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
81 $koboldsFile = $savePath . '/kobolds.json';
82
83 $this->kobolds = [];
84
85 if (file_exists($koboldsFile)) {
86 $data = $this->saveManager->loadJson($koboldsFile);
87
88 if ($data && is_array($data)) {
89 foreach ($data as $koboldData) {
90 $kobold = Kobold::fromArray($koboldData, $this->userId, $this->saveId);
91 if ($kobold) {
92 $this->kobolds[$kobold->getId()] = $kobold;
93 }
94 }
95 }
96 }
97 }
98
99 private function loadStorage()
100 {
101 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
102 $itemsFile = $savePath . '/items.json';
103
104 $this->storage = [];
105
106 if (file_exists($itemsFile)) {
107 $this->storage = $this->saveManager->loadJson($itemsFile) ?? [];
108 }
109 }
110
111 public function save()
112 {
113 $this->lastPlayed = date('Y-m-d H:i:s');
114
115 $savePath = $this->saveManager->getSavePath($this->userId, $this->saveId);
116
117 // Save tribe metadata
118 $tribeData = [
119 'name' => $this->name,
120 'current_month' => $this->currentMonth,
121 'current_season' => $this->currentSeason,
122 'food_count' => $this->foodCount,
123 'created_at' => $this->createdAt,
124 'last_played' => $this->lastPlayed
125 ];
126
127 $this->saveManager->saveJson($savePath . '/save.json', $tribeData);
128
129 // Save kobolds
130 $koboldsData = [];
131 foreach ($this->kobolds as $kobold) {
132 $kobold->save();
133 $koboldsData[] = $kobold->toArray();
134 }
135
136 $this->saveManager->saveJson($savePath . '/kobolds.json', $koboldsData);
137
138 // Save items
139 $this->saveManager->saveJson($savePath . '/items.json', $this->storage);
140 }
141
142 // Getters and Setters
143 public function getName()
144 {
145 return $this->name;
146 }
147
148 public function setName($name)
149 {
150 $this->name = $name;
151 }
152
153 public function getSaveId()
154 {
155 return $this->saveId;
156 }
157
158 public function getUserId()
159 {
160 return $this->userId;
161 }
162
163 public function getCreatedAt()
164 {
165 return $this->createdAt;
166 }
167
168 public function getLastPlayed()
169 {
170 return $this->lastPlayed;
171 }
172
173 public function getCurrentMonth()
174 {
175 return $this->currentMonth;
176 }
177
178 public function setCurrentMonth($month)
179 {
180 $this->currentMonth = max(0, $month);
181 }
182
183 public function getCurrentSeason()
184 {
185 return $this->currentSeason;
186 }
187
188 public function setCurrentSeason($season)
189 {
190 $this->currentSeason = $season;
191 }
192
193 // Kobold management
194 public function getKobolds($includeDeadAndExpelled = false)
195 {
196 if ($includeDeadAndExpelled) {
197 return $this->kobolds;
198 }
199
200 return array_filter($this->kobolds, function (Kobold $k) {
201 return !$k->isDead() && !$k->isExpelled();
202 });
203 }
204
205 public function getKobold($id)
206 {
207 return $this->kobolds[$id] ?? null;
208 }
209
210 public function addKobold(Kobold $kobold)
211 {
212 $this->kobolds[$kobold->getId()] = $kobold;
213 return $kobold;
214 }
215
216 public function removeKobold($id)
217 {
218 unset($this->kobolds[$id]);
219 }
220
221 public function getAliveKobolds()
222 {
223 return array_filter($this->kobolds, fn($k) => !$k->isDead());
224 }
225
226 // Storage management
227 public function addToStorage($itemId)
228 {
229 // Items are already linked to saves
230 }
231
232 public function getStorage()
233 {
234 return $this->storage;
235 }
236
237 // Food system methods
238 public function getFoodCount()
239 {
240 return $this->foodCount;
241 }
242
243 public function addFood($amount)
244 {
245 $this->foodCount += $amount;
246 return $this->foodCount;
247 }
248
249 public function removeFood($amount)
250 {
251 $this->foodCount = max(0, $this->foodCount - $amount);
252 return $this->foodCount;
253 }
254
255 /**
256 * Calculate total food needed for all alive kobolds
257 */
258 public function calculateFoodNeeded()
259 {
260 $needed = 0;
261
262 foreach ($this->getAliveKobolds() as $kobold) {
263 $ageCategory = $kobold->getAgeCategory();
264 $requirement = $this->foodRequirements[$ageCategory] ?? 1.0;
265 $needed += $requirement;
266 }
267
268 return $needed;
269 }
270
271 /**
272 * Get food requirement for a specific kobold
273 */
274 public function getFoodRequirement(Kobold $kobold)
275 {
276 $ageCategory = $kobold->getAgeCategory();
277 return $this->foodRequirements[$ageCategory] ?? 1.0;
278 }
279
280 /**
281 * Consume food at end of month after events
282 * Prioritizes: malnourished kobolds first, then younger before older
283 * Returns story of food consumption and any starvations
284 */
285 public function consumeFood()
286 {
287 $story = "";
288 $aliveKobolds = $this->getAliveKobolds();
289
290 if (empty($aliveKobolds)) {
291 return $story;
292 }
293
294 // Sort kobolds: malnourished first, then by age (younger first)
295 usort($aliveKobolds, function ($a, $b) {
296 // Check for malnourished injury
297 $aMalnourished = $this->hasInjuryCategory($a, 'malnourished');
298 $bMalnourished = $this->hasInjuryCategory($b, 'malnourished');
299
300 if ($aMalnourished && !$bMalnourished)
301 return -1;
302 if (!$aMalnourished && $bMalnourished)
303 return 1;
304
305 // Both have or both don't have malnourished
306 // Younger first (lower age = higher priority)
307 return $a->getAge() - $b->getAge();
308 });
309
310 $fedKobolds = [];
311 $starvedKobolds = [];
312
313 foreach ($aliveKobolds as $kobold) {
314 $needed = $this->getFoodRequirement($kobold);
315
316 if ($this->foodCount >= $needed) {
317 // Fed this kobold
318 $this->foodCount -= $needed;
319 $fedKobolds[$kobold->getId()] = $kobold;
320
321 // If malnourished, cure it
322 if ($this->hasInjuryCategory($kobold, 'malnourished')) {
323 $this->removeMalnourishedInjury($kobold);
324 $story .= "{$kobold->getName()} was fed and recovered from malnutrition.\n";
325 }
326 } else {
327 // Not enough food - starve this kobold
328 $starvedKobolds[$kobold->getId()] = $kobold;
329 $this->foodCount = 0; // Use remaining food
330
331 // Add malnourished injury if not already present
332 if (!$this->hasInjuryCategory($kobold, 'malnourished')) {
333 $kobold->addInjury('malnourished', 'malnourished', 1);
334 $story .= "{$kobold->getName()} went hungry and became malnourished.\n";
335 } else {
336 // Already malnourished - becomes more severe
337 $injuries = $kobold->getInjuries();
338 foreach ($injuries as $injury) {
339 if ($injury['category'] === 'malnourished') {
340 // Could increase severity or add another injury
341 $story .= "{$kobold->getName()} remained hungry and suffered.\n";
342 break;
343 }
344 }
345 }
346 }
347 }
348
349 // Save updated kobolds
350 foreach ($aliveKobolds as $kobold) {
351 $kobold->save();
352 }
353
354 return $story;
355 }
356
357 /**
358 * Check if a kobold has an injury in a specific category
359 */
360 private function hasInjuryCategory(Kobold $kobold, $category)
361 {
362 $injuries = $kobold->getInjuries();
363 foreach ($injuries as $injury) {
364 if ($injury['category'] === $category) {
365 return true;
366 }
367 }
368 return false;
369 }
370
371 /**
372 * Remove all malnourished injuries from a kobold
373 */
374 private function removeMalnourishedInjury(Kobold $kobold)
375 {
376 $injuries = $kobold->getInjuries();
377 foreach ($injuries as $injury) {
378 if ($injury['category'] === 'malnourished') {
379 $kobold->removeInjury($injury['id']);
380 }
381 }
382 }
383
384 public function endMonth()
385 {
386 // Increment month and update season
387 $this->currentMonth++;
388
389 $seasons = ['spring', 'summer', 'autumn', 'winter'];
390 $this->currentSeason = $seasons[($this->currentMonth / 3) % 4];
391
392 // Random month events happen here (handled by EventManager in API)
393 // After events, consume food
394 $foodStory = $this->consumeFood();
395
396 // Age all kobolds
397 foreach ($this->kobolds as $kobold) {
398 $kobold->incrementAge();
399
400 // Check for old-age injuries
401 if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
402 $oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia'];
403 $injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
404 $kobold->addInjury($injury, 'old-age', 1);
405 }
406
407 // Check if kobold should die
408 if ($kobold->isDead()) {
409 $kobold->die();
410 }
411
412 $kobold->save();
413 }
414
415 $this->save();
416
417 return $foodStory;
418 }
419
420 private function shouldAddOldAgeInjury(Kobold $kobold)
421 {
422 // 1d100 roll under age starting at 35
423 $roll = rand(1, 100);
424 return $roll <= $kobold->getAge();
425 }
426}