mostly working
todo: make food actually count up when finding it, fix events, add events, event member selection probably, etc.
@@ -37,6 +37,12 @@ if (strpos($path, '/api/') === 0) {
37
37
include __DIR__ . '/src/api/game.php';
38
38
} elseif ($apiPath === 'game/event') {
39
39
include __DIR__ . '/src/api/game.php';
40
} elseif ($apiPath === 'game/sprite') {
41
include __DIR__ . '/src/api/game.php';
42
} elseif ($apiPath === 'game/list') {
43
include __DIR__ . '/src/api/game.php';
44
} elseif ($apiPath === 'game/endMonth') {
45
include __DIR__ . '/src/api/game.php';
40
46
} else {
41
47
http_response_code(404);
42
48
echo json_encode(['error' => 'Not found']);
@@ -37,6 +37,12 @@ if (strpos($path, '/api/') === 0) {37
include __DIR__ . '/src/api/game.php';37
include __DIR__ . '/src/api/game.php';38
} elseif ($apiPath === 'game/event') {38
} elseif ($apiPath === 'game/event') {39
include __DIR__ . '/src/api/game.php';39
include __DIR__ . '/src/api/game.php';40
} elseif ($apiPath === 'game/sprite') {41
include __DIR__ . '/src/api/game.php';42
} elseif ($apiPath === 'game/list') {43
include __DIR__ . '/src/api/game.php';44
} elseif ($apiPath === 'game/endMonth') {45
include __DIR__ . '/src/api/game.php';40
} else {46
} else {41
http_response_code(404);47
http_response_code(404);42
echo json_encode(['error' => 'Not found']);48
echo json_encode(['error' => 'Not found']);@@ -1,3 +1,4 @@
1
var doneTyping = true;
1
2
// Main Game App
2
3
class TribeGenApp
3
4
{
@@ -245,6 +246,7 @@ class TribeGenApp
245
246
{
246
247
this.currentSave = data.save;
247
248
this.displayKobolds(data.kobolds, 'leader');
249
this.displayKobolds(data.kobolds, 'member');
248
250
249
251
document.getElementById('setupStep1').classList.add('hidden');
250
252
document.getElementById('setupStep2').classList.remove('hidden');
@@ -291,26 +293,41 @@ class TribeGenApp
291
293
});
292
294
}
293
295
294
selectLeaderCard (card, index)
296
async selectLeaderCard (card, index)
295
297
{
298
const leaderName = document.getElementById('leaderName').value;
299
300
if (!leaderName)
301
{
302
alert('Please enter a leader name');
303
return;
304
}
305
296
306
document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected'));
297
307
card.classList.add('selected');
298
308
document.getElementById('selectLeaderBtn').dataset.leaderIndex = index;
309
310
this.toggleMemberSelection(card, index, true);
311
await this.selectLeader();
299
312
}
300
313
301
toggleMemberSelection (card, index)
314
toggleMemberSelection (card, index, force)
302
315
{
303
card.classList.toggle('selected');
316
const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;
317
if (force || leaderIndex != index)
318
{
319
document.querySelectorAll('#memberSelectionGrid .kobold-card')[index].classList.toggle('selected');
304
320
305
const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;
306
document.getElementById('memberCount').textContent = `${selected} / 5 selected`;
321
const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;
322
document.getElementById('memberCount').textContent = `${selected} / 5 selected`;
307
323
308
if (selected === 5)
309
{
310
document.getElementById('finishTribeBtn').disabled = false;
311
} else
312
{
313
document.getElementById('finishTribeBtn').disabled = true;
324
if (selected === 5)
325
{
326
document.getElementById('finishTribeBtn').disabled = false;
327
} else
328
{
329
document.getElementById('finishTribeBtn').disabled = true;
330
}
314
331
}
315
332
}
316
333
@@ -350,6 +367,7 @@ class TribeGenApp
350
367
'Authorization': `Bearer ${this.currentUser.token}`
351
368
},
352
369
body: JSON.stringify({
370
userId: this.currentUser.id,
353
371
saveId: this.currentSave.id,
354
372
leaderName: document.getElementById('leaderName').value,
355
373
memberIndices: memberIndices
@@ -441,7 +459,7 @@ class TribeGenApp
441
459
const item = document.createElement('div');
442
460
item.className = 'event-item';
443
461
item.textContent = event;
444
item.addEventListener('click', () => this.executeEvent(event.toLowerCase()));
462
item.addEventListener('click', () => this.executeEvent(event));
445
463
list.appendChild(item);
446
464
});
447
465
}
@@ -457,6 +475,7 @@ class TribeGenApp
457
475
'Authorization': `Bearer ${this.currentUser.token}`
458
476
},
459
477
body: JSON.stringify({
478
userId: this.currentUser.id,
460
479
saveId: this.currentSave.id,
461
480
eventType: eventType
462
481
})
@@ -466,7 +485,7 @@ class TribeGenApp
466
485
467
486
if (data.success)
468
487
{
469
document.getElementById('eventStory').textContent = data.story;
488
typeText(document.getElementById('eventStory'), data.story);
470
489
this.showEventModal();
471
490
}
472
491
} catch (error)
@@ -486,15 +505,18 @@ class TribeGenApp
486
505
'Content-Type': 'application/json',
487
506
'Authorization': `Bearer ${this.currentUser.token}`
488
507
},
489
body: JSON.stringify({ saveId: this.currentSave.id })
508
body: JSON.stringify({
509
userId: this.currentUser.id, saveId: this.currentSave.id
510
})
490
511
});
491
512
492
const data = await response.json();
513
const dataT = await response.text();
514
const data = JSON.parse(dataT);
493
515
494
516
if (data.success)
495
517
{
496
518
this.currentSave = data.save;
497
document.getElementById('eventStory').textContent = data.monthStory;
519
typeText(document.getElementById('eventStory'), data.monthStory);
498
520
this.showEventModal();
499
521
}
500
522
} catch (error)
@@ -511,6 +533,7 @@ class TribeGenApp
511
533
512
534
hideEventModal ()
513
535
{
536
if (!doneTyping) return;
514
537
document.getElementById('eventModal').classList.add('hidden');
515
538
this.renderGame();
516
539
}
@@ -531,3 +554,48 @@ document.addEventListener('DOMContentLoaded', () =>
531
554
{
532
555
window.app = new TribeGenApp();
533
556
});
557
558
function typeText (element, text, minDelay = 3, maxDelay = 65)
559
{
560
doneTyping = false;
561
element.textContent = "";
562
let index = 0;
563
let timerId = null;
564
565
const randDelay = () =>
566
Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
567
568
const shouldStop = () =>
569
{
570
if (!element.isConnected) return true;
571
if (getComputedStyle(element).display === "none") return true;
572
return false;
573
};
574
575
return new Promise((resolve) =>
576
{
577
function tick ()
578
{
579
if (shouldStop())
580
{
581
if (timerId) clearTimeout(timerId);
582
doneTyping = true;
583
resolve(false); // stopped early
584
return;
585
}
586
587
if (index >= text.length)
588
{
589
doneTyping = true;
590
resolve(true); // finished normally
591
return;
592
}
593
594
element.textContent += text[index++];
595
timerId = setTimeout(tick, randDelay());
596
}
597
598
tick();
599
});
600
}
601
@@ -1,3 +1,4 @@1
var doneTyping = true;1
// Main Game App2
// Main Game App2
class TribeGenApp3
class TribeGenApp3
{4
{@@ -245,6 +246,7 @@ class TribeGenApp245
{246
{246
this.currentSave = data.save;247
this.currentSave = data.save;247
this.displayKobolds(data.kobolds, 'leader');248
this.displayKobolds(data.kobolds, 'leader');249
this.displayKobolds(data.kobolds, 'member');248
250
249
document.getElementById('setupStep1').classList.add('hidden');251
document.getElementById('setupStep1').classList.add('hidden');250
document.getElementById('setupStep2').classList.remove('hidden');252
document.getElementById('setupStep2').classList.remove('hidden');@@ -291,26 +293,41 @@ class TribeGenApp291
});293
});292
}294
}293
295
294
selectLeaderCard (card, index)296
async selectLeaderCard (card, index)295
{297
{298
const leaderName = document.getElementById('leaderName').value;299
300
if (!leaderName)301
{302
alert('Please enter a leader name');303
return;304
}305
296
document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected'));306
document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected'));297
card.classList.add('selected');307
card.classList.add('selected');298
document.getElementById('selectLeaderBtn').dataset.leaderIndex = index;308
document.getElementById('selectLeaderBtn').dataset.leaderIndex = index;309
310
this.toggleMemberSelection(card, index, true);311
await this.selectLeader();299
}312
}300
313
301
toggleMemberSelection (card, index)314
toggleMemberSelection (card, index, force)302
{315
{303
card.classList.toggle('selected');316
const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex;317
if (force || leaderIndex != index)318
{319
document.querySelectorAll('#memberSelectionGrid .kobold-card')[index].classList.toggle('selected');304
320
305
const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;321
const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length;306
document.getElementById('memberCount').textContent = `${selected} / 5 selected`;322
document.getElementById('memberCount').textContent = `${selected} / 5 selected`;307
323
308
if (selected === 5)324
if (selected === 5)309
{325
{310
document.getElementById('finishTribeBtn').disabled = false;326
document.getElementById('finishTribeBtn').disabled = false;311
} else327
} else312
{328
{313
document.getElementById('finishTribeBtn').disabled = true;329
document.getElementById('finishTribeBtn').disabled = true;330
}314
}331
}315
}332
}316
333
@@ -350,6 +367,7 @@ class TribeGenApp350
'Authorization': `Bearer ${this.currentUser.token}`367
'Authorization': `Bearer ${this.currentUser.token}`351
},368
},352
body: JSON.stringify({369
body: JSON.stringify({370
userId: this.currentUser.id,353
saveId: this.currentSave.id,371
saveId: this.currentSave.id,354
leaderName: document.getElementById('leaderName').value,372
leaderName: document.getElementById('leaderName').value,355
memberIndices: memberIndices373
memberIndices: memberIndices@@ -441,7 +459,7 @@ class TribeGenApp441
const item = document.createElement('div');459
const item = document.createElement('div');442
item.className = 'event-item';460
item.className = 'event-item';443
item.textContent = event;461
item.textContent = event;444
item.addEventListener('click', () => this.executeEvent(event.toLowerCase()));462
item.addEventListener('click', () => this.executeEvent(event));445
list.appendChild(item);463
list.appendChild(item);446
});464
});447
}465
}@@ -457,6 +475,7 @@ class TribeGenApp457
'Authorization': `Bearer ${this.currentUser.token}`475
'Authorization': `Bearer ${this.currentUser.token}`458
},476
},459
body: JSON.stringify({477
body: JSON.stringify({478
userId: this.currentUser.id,460
saveId: this.currentSave.id,479
saveId: this.currentSave.id,461
eventType: eventType480
eventType: eventType462
})481
})@@ -466,7 +485,7 @@ class TribeGenApp466
485
467
if (data.success)486
if (data.success)468
{487
{469
document.getElementById('eventStory').textContent = data.story;488
typeText(document.getElementById('eventStory'), data.story);470
this.showEventModal();489
this.showEventModal();471
}490
}472
} catch (error)491
} catch (error)@@ -486,15 +505,18 @@ class TribeGenApp486
'Content-Type': 'application/json',505
'Content-Type': 'application/json',487
'Authorization': `Bearer ${this.currentUser.token}`506
'Authorization': `Bearer ${this.currentUser.token}`488
},507
},489
body: JSON.stringify({ saveId: this.currentSave.id })508
body: JSON.stringify({509
userId: this.currentUser.id, saveId: this.currentSave.id510
})490
});511
});491
512
492
const data = await response.json();513
const dataT = await response.text();514
const data = JSON.parse(dataT);493
515
494
if (data.success)516
if (data.success)495
{517
{496
this.currentSave = data.save;518
this.currentSave = data.save;497
document.getElementById('eventStory').textContent = data.monthStory;519
typeText(document.getElementById('eventStory'), data.monthStory);498
this.showEventModal();520
this.showEventModal();499
}521
}500
} catch (error)522
} catch (error)@@ -511,6 +533,7 @@ class TribeGenApp511
533
512
hideEventModal ()534
hideEventModal ()513
{535
{536
if (!doneTyping) return;514
document.getElementById('eventModal').classList.add('hidden');537
document.getElementById('eventModal').classList.add('hidden');515
this.renderGame();538
this.renderGame();516
}539
}@@ -531,3 +554,48 @@ document.addEventListener('DOMContentLoaded', () =>531
{554
{532
window.app = new TribeGenApp();555
window.app = new TribeGenApp();533
});556
});557
558
function typeText (element, text, minDelay = 3, maxDelay = 65)559
{560
doneTyping = false;561
element.textContent = "";562
let index = 0;563
let timerId = null;564
565
const randDelay = () =>566
Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;567
568
const shouldStop = () =>569
{570
if (!element.isConnected) return true;571
if (getComputedStyle(element).display === "none") return true;572
return false;573
};574
575
return new Promise((resolve) =>576
{577
function tick ()578
{579
if (shouldStop())580
{581
if (timerId) clearTimeout(timerId);582
doneTyping = true;583
resolve(false); // stopped early584
return;585
}586
587
if (index >= text.length)588
{589
doneTyping = true;590
resolve(true); // finished normally591
return;592
}593
594
element.textContent += text[index++];595
timerId = setTimeout(tick, randDelay());596
}597
598
tick();599
});600
}601
@@ -83,7 +83,8 @@ class Kobold
83
83
}
84
84
85
85
$spriteMorph = self::getRandomSpriteMorph();
86
$kobold = new self(uniqid('kob_'), $userId, $saveId, '', $age, $spriteMorph);
86
$name = self::generateRandomName();
87
$kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);
87
88
// Copy and transform sprite from assets to save folder
88
89
$kobold->initializeSprite();
89
90
@@ -106,6 +107,28 @@ class Kobold
106
107
return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';
107
108
}
108
109
110
private static function generateRandomName()
111
{
112
// Kobold name syllables
113
$firstSyllables = [
114
'Grik', 'Gnak', 'Drog', 'Mog', 'Bik', 'Zag', 'Kra', 'Snak',
115
'Grok', 'Tik', 'Nag', 'Brack', 'Flak', 'Grat', 'Krag', 'Skrit',
116
'Zik', 'Bog', 'Crag', 'Gull', 'Kith', 'Mick', 'Nib', 'Prat',
117
'Rik', 'Tig', 'Vex', 'Wik', 'Xak', 'Yak', 'Zap'
118
];
119
120
$lastSyllables = [
121
'ink', 'ack', 'og', 'ag', 'ug', 'ik', 'ek', 'ock',
122
'ar', 'ax', 'er', 'it', 'ut', 'ot', 'or', 'in',
123
'an', 'en', 'un', 'on', 'oo', 'ee', 'im', 'um'
124
];
125
126
$firstName = $firstSyllables[array_rand($firstSyllables)];
127
$lastName = $lastSyllables[array_rand($lastSyllables)];
128
129
return $firstName . $lastName;
130
}
131
109
132
public static function fromArray($data, $userId, $saveId)
110
133
{
111
134
$kobold = new self(
@@ -142,6 +165,7 @@ class Kobold
142
165
'id' => $this->id,
143
166
'name' => $this->name,
144
167
'age' => $this->age,
168
'ageCategory' => $this->getAgeCategory(),
145
169
'stats' => $this->stats,
146
170
'sprite_morph' => $this->spriteMorph,
147
171
'is_leader' => $this->isLeader,
@@ -170,10 +194,10 @@ class Kobold
170
194
*/
171
195
private function initializeSprite()
172
196
{
173
$spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
174
197
$ageSprite = $this->getAgeSpriteName();
198
$spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);
175
199
$sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
176
$destFile = $spriteDir . '/' . $ageSprite . '.png';
200
$destFile = $spriteDir;
177
201
178
202
// Copy base sprite from assets
179
203
if (file_exists($sourceFile)) {
@@ -181,7 +205,7 @@ class Kobold
181
205
}
182
206
183
207
// Apply transformations to the sprite
184
$this->transformSprite();
208
$this->transformSprite($destFile);
185
209
}
186
210
187
211
/**
@@ -193,9 +217,9 @@ class Kobold
193
217
$spriteMap = [
194
218
'egg' => 'egg',
195
219
'baby' => 'baby',
220
'young' => 'young',
196
221
'adult' => 'adult',
197
'old' => 'old',
198
'very_old' => 'old' // Reuse old sprite for very_old
222
'old' => 'old' // Reuse old sprite for very_old
199
223
];
200
224
201
225
return $spriteMap[$ageCategory] ?? 'adult';
@@ -204,11 +228,25 @@ class Kobold
204
228
/**
205
229
* Get path to the kobold's sprite file for current age
206
230
*/
207
public function getSpritePath()
231
public function getSpritePath($age)
208
232
{
209
$spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);
210
$ageSprite = $this->getAgeSpriteName();
211
return $spriteDir . '/' . $ageSprite . '.png';
233
$spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);
234
$ageSprite = $age ?? $this->getAgeSpriteName();
235
$destFile = $spriteDir;
236
237
if (!file_exists($destFile)) {
238
$sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';
239
240
// Copy base sprite from assets
241
if (file_exists($sourceFile)) {
242
copy($sourceFile, $destFile);
243
}
244
245
// Apply transformations to the sprite
246
$this->transformSprite($destFile);
247
}
248
249
return $destFile;
212
250
}
213
251
214
252
public function getId()
@@ -409,9 +447,8 @@ class Kobold
409
447
* Apply transformations to sprite (injuries, age coloring, leadership marks)
410
448
* Uses PHP GD library to modify the sprite image
411
449
*/
412
private function transformSprite()
450
private function transformSprite($spritePath)
413
451
{
414
$spritePath = $this->getSpritePath();
415
452
if (!file_exists($spritePath))
416
453
return;
417
454
@@ -83,7 +83,8 @@ class Kobold83
}83
}84
84
85
$spriteMorph = self::getRandomSpriteMorph();85
$spriteMorph = self::getRandomSpriteMorph();86
$kobold = new self(uniqid('kob_'), $userId, $saveId, '', $age, $spriteMorph);86
$name = self::generateRandomName();87
$kobold = new self(uniqid('kob_' . $saveId . '_'), $userId, $saveId, $name, $age, $spriteMorph);87
// Copy and transform sprite from assets to save folder88
// Copy and transform sprite from assets to save folder88
$kobold->initializeSprite();89
$kobold->initializeSprite();89
90
@@ -106,6 +107,28 @@ class Kobold106
return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';107
return !empty($morphs) ? array_values($morphs)[array_rand($morphs)] : 'default';107
}108
}108
109
110
private static function generateRandomName()111
{112
// Kobold name syllables113
$firstSyllables = [114
'Grik', 'Gnak', 'Drog', 'Mog', 'Bik', 'Zag', 'Kra', 'Snak',115
'Grok', 'Tik', 'Nag', 'Brack', 'Flak', 'Grat', 'Krag', 'Skrit',116
'Zik', 'Bog', 'Crag', 'Gull', 'Kith', 'Mick', 'Nib', 'Prat',117
'Rik', 'Tig', 'Vex', 'Wik', 'Xak', 'Yak', 'Zap'118
];119
120
$lastSyllables = [121
'ink', 'ack', 'og', 'ag', 'ug', 'ik', 'ek', 'ock',122
'ar', 'ax', 'er', 'it', 'ut', 'ot', 'or', 'in',123
'an', 'en', 'un', 'on', 'oo', 'ee', 'im', 'um'124
];125
126
$firstName = $firstSyllables[array_rand($firstSyllables)];127
$lastName = $lastSyllables[array_rand($lastSyllables)];128
129
return $firstName . $lastName;130
}131
109
public static function fromArray($data, $userId, $saveId)132
public static function fromArray($data, $userId, $saveId)110
{133
{111
$kobold = new self(134
$kobold = new self(@@ -142,6 +165,7 @@ class Kobold142
'id' => $this->id,165
'id' => $this->id,143
'name' => $this->name,166
'name' => $this->name,144
'age' => $this->age,167
'age' => $this->age,168
'ageCategory' => $this->getAgeCategory(),145
'stats' => $this->stats,169
'stats' => $this->stats,146
'sprite_morph' => $this->spriteMorph,170
'sprite_morph' => $this->spriteMorph,147
'is_leader' => $this->isLeader,171
'is_leader' => $this->isLeader,@@ -170,10 +194,10 @@ class Kobold170
*/194
*/171
private function initializeSprite()195
private function initializeSprite()172
{196
{173
$spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);174
$ageSprite = $this->getAgeSpriteName();197
$ageSprite = $this->getAgeSpriteName();198
$spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $ageSprite);175
$sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';199
$sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';176
$destFile = $spriteDir . '/' . $ageSprite . '.png';200
$destFile = $spriteDir;177
201
178
// Copy base sprite from assets202
// Copy base sprite from assets179
if (file_exists($sourceFile)) {203
if (file_exists($sourceFile)) {@@ -181,7 +205,7 @@ class Kobold181
}205
}182
206
183
// Apply transformations to the sprite207
// Apply transformations to the sprite184
$this->transformSprite();208
$this->transformSprite($destFile);185
}209
}186
210
187
/**211
/**@@ -193,9 +217,9 @@ class Kobold193
$spriteMap = [217
$spriteMap = [194
'egg' => 'egg',218
'egg' => 'egg',195
'baby' => 'baby',219
'baby' => 'baby',220
'young' => 'young',196
'adult' => 'adult',221
'adult' => 'adult',197
'old' => 'old',222
'old' => 'old' // Reuse old sprite for very_old198
'very_old' => 'old' // Reuse old sprite for very_old199
];223
];200
224
201
return $spriteMap[$ageCategory] ?? 'adult';225
return $spriteMap[$ageCategory] ?? 'adult';@@ -204,11 +228,25 @@ class Kobold204
/**228
/**205
* Get path to the kobold's sprite file for current age229
* Get path to the kobold's sprite file for current age206
*/230
*/207
public function getSpritePath()231
public function getSpritePath($age)208
{232
{209
$spriteDir = $this->saveManager->getKoboldSpritePath($this->userId, $this->id);233
$spriteDir = $this->saveManager->getKoboldSpritePathBase($this->userId, $this->id, $age);210
$ageSprite = $this->getAgeSpriteName();234
$ageSprite = $age ?? $this->getAgeSpriteName();211
return $spriteDir . '/' . $ageSprite . '.png';235
$destFile = $spriteDir;236
237
if (!file_exists($destFile)) {238
$sourceFile = __DIR__ . '/../../assets/sprites/' . $this->spriteMorph . '/' . $ageSprite . '.png';239
240
// Copy base sprite from assets241
if (file_exists($sourceFile)) {242
copy($sourceFile, $destFile);243
}244
245
// Apply transformations to the sprite246
$this->transformSprite($destFile);247
}248
249
return $destFile;212
}250
}213
251
214
public function getId()252
public function getId()@@ -409,9 +447,8 @@ class Kobold409
* Apply transformations to sprite (injuries, age coloring, leadership marks)447
* Apply transformations to sprite (injuries, age coloring, leadership marks)410
* Uses PHP GD library to modify the sprite image448
* Uses PHP GD library to modify the sprite image411
*/449
*/412
private function transformSprite()450
private function transformSprite($spritePath)413
{451
{414
$spritePath = $this->getSpritePath();415
if (!file_exists($spritePath))452
if (!file_exists($spritePath))416
return;453
return;417
454
@@ -8,7 +8,7 @@ class Tribe
8
8
private $userId;
9
9
private $saveId;
10
10
private $name;
11
private $kobolds = [];
11
public $kobolds = [];
12
12
private $storage = [];
13
13
private $currentMonth = 0;
14
14
private $currentSeason = 'spring';
@@ -383,34 +383,41 @@ class Tribe
383
383
384
384
public function endMonth()
385
385
{
386
// Increment month and update season
387
386
$this->currentMonth++;
388
387
389
388
$seasons = ['spring', 'summer', 'autumn', 'winter'];
390
$this->currentSeason = $seasons[($this->currentMonth / 3) % 4];
391
389
390
$monthOfYear = (($this->currentMonth - 1) % 12) + 1;
391
$index = intdiv($monthOfYear - 1, 3);
392
393
$this->currentSeason = $seasons[$index];
392
394
// Random month events happen here (handled by EventManager in API)
393
395
// After events, consume food
394
396
$foodStory = $this->consumeFood();
395
397
396
398
// Age all kobolds
397
foreach ($this->kobolds as $kobold) {
398
$kobold->incrementAge();
399
if ($this->currentMonth % 12 === 0) {
400
$foodStory .= "\nA new year begins.\n";
399
401
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
}
402
foreach ($this->kobolds as $kobold) {
403
$kobold->incrementAge();
406
404
407
// Check if kobold should die
408
if ($kobold->isDead()) {
409
$kobold->die();
410
}
405
// Check for old-age injuries
406
if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {
407
$oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia'];
408
$injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];
409
$kobold->addInjury($injury, 'old-age', 1);
410
}
411
411
412
$kobold->save();
412
// Check if kobold should die
413
if ($kobold->isDead()) {
414
$kobold->die();
415
}
416
417
$kobold->save();
418
}
413
419
}
420
$foodStory .= "\nIt's {$this->currentSeason}.\n";
414
421
415
422
$this->save();
416
423
@@ -8,7 +8,7 @@ class Tribe8
private $userId;8
private $userId;9
private $saveId;9
private $saveId;10
private $name;10
private $name;11
private $kobolds = [];11
public $kobolds = [];12
private $storage = [];12
private $storage = [];13
private $currentMonth = 0;13
private $currentMonth = 0;14
private $currentSeason = 'spring';14
private $currentSeason = 'spring';@@ -383,34 +383,41 @@ class Tribe383
383
384
public function endMonth()384
public function endMonth()385
{385
{386
// Increment month and update season387
$this->currentMonth++;386
$this->currentMonth++;388
387
389
$seasons = ['spring', 'summer', 'autumn', 'winter'];388
$seasons = ['spring', 'summer', 'autumn', 'winter'];390
$this->currentSeason = $seasons[($this->currentMonth / 3) % 4];391
389
390
$monthOfYear = (($this->currentMonth - 1) % 12) + 1;391
$index = intdiv($monthOfYear - 1, 3);392
393
$this->currentSeason = $seasons[$index];392
// Random month events happen here (handled by EventManager in API)394
// Random month events happen here (handled by EventManager in API)393
// After events, consume food395
// After events, consume food394
$foodStory = $this->consumeFood();396
$foodStory = $this->consumeFood();395
397
396
// Age all kobolds398
// Age all kobolds397
foreach ($this->kobolds as $kobold) {399
if ($this->currentMonth % 12 === 0) {398
$kobold->incrementAge();400
$foodStory .= "\nA new year begins.\n";399
401
400
// Check for old-age injuries402
foreach ($this->kobolds as $kobold) {401
if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {403
$kobold->incrementAge();402
$oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia'];403
$injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];404
$kobold->addInjury($injury, 'old-age', 1);405
}406
404
407
// Check if kobold should die405
// Check for old-age injuries408
if ($kobold->isDead()) {406
if ($kobold->getAge() >= 35 && $this->shouldAddOldAgeInjury($kobold)) {409
$kobold->die();407
$oldAgeInjuries = ['bad_back', 'bad_liver', 'poor_eyesight', 'dementia'];410
}408
$injury = $oldAgeInjuries[array_rand($oldAgeInjuries)];409
$kobold->addInjury($injury, 'old-age', 1);410
}411
411
412
$kobold->save();412
// Check if kobold should die413
if ($kobold->isDead()) {414
$kobold->die();415
}416
417
$kobold->save();418
}413
}419
}420
$foodStory .= "\nIt's {$this->currentSeason}.\n";414
421
415
$this->save();422
$this->save();416
423
@@ -1,5 +1,7 @@
1
1
<?php
2
2
3
require_once __DIR__ . '/../Classes/Kobold.php';
4
3
5
class SaveManager
4
6
{
5
7
private $basePath;
@@ -44,12 +46,40 @@ class SaveManager
44
46
/**
45
47
* Get kobold sprites directory
46
48
*/
47
public function getKoboldSpritePath($userId, $koboldId)
49
public function getKoboldSpritePathBase($userId, $koboldId, $age)
48
50
{
49
$path = $this->basePath . '/' . ($userId) . '/kobolds/' . $koboldId . '/sprites';
50
if (!is_dir($path)) {
51
mkdir($path, 0755, true);
51
$path = $this->basePath . '/' . ($userId) . '/kobolds/' . $koboldId . '/sprites/' . $age . '.png';
52
53
if (!is_dir(dirname($path))) {
54
mkdir(dirname($path), 0755, true);
55
}
56
return $path;
57
}
58
public function getKoboldSpritePath($userId, $koboldId, $age)
59
{
60
// Extract saveId from kobold ID (format: kob_{saveId}_{uniqid})
61
$parts = explode('_', $koboldId, 3);
62
$saveId = $parts[1] ?? null;
63
64
// Load the kobold from the save
65
$koboldsPath = $this->getSavePath($userId, $saveId) . '/kobolds.json';
66
$kobold = null;
67
68
if (file_exists($koboldsPath)) {
69
$koboldsData = $this->loadJson($koboldsPath);
70
if ($koboldsData) {
71
// Find the kobold with matching ID
72
foreach ($koboldsData as $koboldData) {
73
if ($koboldData['id'] === $koboldId) {
74
$kobold = Kobold::fromArray($koboldData, $userId, $saveId);
75
break;
76
}
77
}
78
}
52
79
}
80
81
$path = $kobold ? $kobold->getSpritePath($age) : $this->getKoboldSpritePathBase($userId, $koboldId, $age);
82
53
83
return $path;
54
84
}
55
85
@@ -1,5 +1,7 @@1
<?php1
<?php2
2
3
require_once __DIR__ . '/../Classes/Kobold.php';4
3
class SaveManager5
class SaveManager4
{6
{5
private $basePath;7
private $basePath;@@ -44,12 +46,40 @@ class SaveManager44
/**46
/**45
* Get kobold sprites directory47
* Get kobold sprites directory46
*/48
*/47
public function getKoboldSpritePath($userId, $koboldId)49
public function getKoboldSpritePathBase($userId, $koboldId, $age)48
{50
{49
$path = $this->basePath . '/' . ($userId) . '/kobolds/' . $koboldId . '/sprites';51
$path = $this->basePath . '/' . ($userId) . '/kobolds/' . $koboldId . '/sprites/' . $age . '.png';50
if (!is_dir($path)) {52
51
mkdir($path, 0755, true);53
if (!is_dir(dirname($path))) {54
mkdir(dirname($path), 0755, true);55
}56
return $path;57
}58
public function getKoboldSpritePath($userId, $koboldId, $age)59
{60
// Extract saveId from kobold ID (format: kob_{saveId}_{uniqid})61
$parts = explode('_', $koboldId, 3);62
$saveId = $parts[1] ?? null;63
64
// Load the kobold from the save65
$koboldsPath = $this->getSavePath($userId, $saveId) . '/kobolds.json';66
$kobold = null;67
68
if (file_exists($koboldsPath)) {69
$koboldsData = $this->loadJson($koboldsPath);70
if ($koboldsData) {71
// Find the kobold with matching ID72
foreach ($koboldsData as $koboldData) {73
if ($koboldData['id'] === $koboldId) {74
$kobold = Kobold::fromArray($koboldData, $userId, $saveId);75
break;76
}77
}78
}52
}79
}80
81
$path = $kobold ? $kobold->getSpritePath($age) : $this->getKoboldSpritePathBase($userId, $koboldId, $age);82
53
return $path;83
return $path;54
}84
}55
85
@@ -7,6 +7,10 @@ require_once __DIR__ . '/../../src/Classes/Tribe.php';
7
7
require_once __DIR__ . '/../../src/Classes/Kobold.php';
8
8
require_once __DIR__ . '/../../src/System/SaveManager.php';
9
9
10
foreach (glob(__DIR__ . "/../../src/Events/*Event.php") as $file) {
11
require_once $file;
12
}
13
10
14
$method = $_SERVER['REQUEST_METHOD'];
11
15
12
16
if ($method === 'POST') {
@@ -28,12 +32,12 @@ if ($method === 'POST') {
28
32
$kobolds = [];
29
33
for ($i = 0; $i < 10; $i++) {
30
34
$kobold = Kobold::generate($userId, $tribe->getSaveId());
31
$kobold->setName('Kobold ' . ($i + 1));
32
35
$tribe->addKobold($kobold);
33
36
34
37
$kobolds[] = [
35
38
'id' => $kobold->getId(),
36
39
'name' => $kobold->getName(),
40
'ageCategory' => $kobold->getAgeCategory(),
37
41
'age' => $kobold->getAge(),
38
42
'stats' => [
39
43
'vitality' => $kobold->getStat('vitality'),
@@ -76,8 +80,18 @@ if ($method === 'POST') {
76
80
77
81
$tribe = Tribe::load($userId, $saveId);
78
82
79
// TODO: Process leader and members selection
80
// For now just save
83
$i = array_keys($tribe->kobolds)[$input['memberIndices'][0]];
84
$tribe->kobolds[$i]->setName($input['leaderName']);
85
86
for ($i = 0; $i < count($input['memberIndices']); $i++) {
87
$input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
88
}
89
90
$tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
91
return in_array($index, $input['memberIndices']);
92
}, ARRAY_FILTER_USE_BOTH);
93
94
$tribe->kobolds = array_values($tribe->kobolds);
81
95
$tribe->save();
82
96
83
97
echo json_encode([
@@ -104,7 +118,10 @@ if ($method === 'POST') {
104
118
$tribe = Tribe::load($userId, $saveId);
105
119
106
120
// TODO: Execute event and get story
107
$story = "An event occurred in the tribe...";
121
$className = $input['eventType'] . "Event";
122
$event = new $className($tribe);
123
$event?->execute();
124
$story = $event?->getStory() ?? 'No event occurred.';
108
125
109
126
echo json_encode([
110
127
'success' => true,
@@ -162,9 +179,9 @@ if ($method === 'POST') {
162
179
}
163
180
164
181
$saveManager = new SaveManager();
165
$spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId);
166
182
$ageSprite = $_GET['age'] ?? 'adult';
167
$spriteFile = $spritePath . '/' . $ageSprite . '.png';
183
$spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
184
$spriteFile = $spritePath;
168
185
169
186
if (!file_exists($spriteFile)) {
170
187
throw new \Exception('Sprite not found');
@@ -7,6 +7,10 @@ require_once __DIR__ . '/../../src/Classes/Tribe.php';7
require_once __DIR__ . '/../../src/Classes/Kobold.php';7
require_once __DIR__ . '/../../src/Classes/Kobold.php';8
require_once __DIR__ . '/../../src/System/SaveManager.php';8
require_once __DIR__ . '/../../src/System/SaveManager.php';9
9
10
foreach (glob(__DIR__ . "/../../src/Events/*Event.php") as $file) {11
require_once $file;12
}13
10
$method = $_SERVER['REQUEST_METHOD'];14
$method = $_SERVER['REQUEST_METHOD'];11
15
12
if ($method === 'POST') {16
if ($method === 'POST') {@@ -28,12 +32,12 @@ if ($method === 'POST') {28
$kobolds = [];32
$kobolds = [];29
for ($i = 0; $i < 10; $i++) {33
for ($i = 0; $i < 10; $i++) {30
$kobold = Kobold::generate($userId, $tribe->getSaveId());34
$kobold = Kobold::generate($userId, $tribe->getSaveId());31
$kobold->setName('Kobold ' . ($i + 1));32
$tribe->addKobold($kobold);35
$tribe->addKobold($kobold);33
36
34
$kobolds[] = [37
$kobolds[] = [35
'id' => $kobold->getId(),38
'id' => $kobold->getId(),36
'name' => $kobold->getName(),39
'name' => $kobold->getName(),40
'ageCategory' => $kobold->getAgeCategory(),37
'age' => $kobold->getAge(),41
'age' => $kobold->getAge(),38
'stats' => [42
'stats' => [39
'vitality' => $kobold->getStat('vitality'),43
'vitality' => $kobold->getStat('vitality'),@@ -76,8 +80,18 @@ if ($method === 'POST') {76
80
77
$tribe = Tribe::load($userId, $saveId);81
$tribe = Tribe::load($userId, $saveId);78
82
79
// TODO: Process leader and members selection83
$i = array_keys($tribe->kobolds)[$input['memberIndices'][0]];80
// For now just save84
$tribe->kobolds[$i]->setName($input['leaderName']);85
86
for ($i = 0; $i < count($input['memberIndices']); $i++) {87
$input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];88
}89
90
$tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {91
return in_array($index, $input['memberIndices']);92
}, ARRAY_FILTER_USE_BOTH);93
94
$tribe->kobolds = array_values($tribe->kobolds);81
$tribe->save();95
$tribe->save();82
96
83
echo json_encode([97
echo json_encode([@@ -104,7 +118,10 @@ if ($method === 'POST') {104
$tribe = Tribe::load($userId, $saveId);118
$tribe = Tribe::load($userId, $saveId);105
119
106
// TODO: Execute event and get story120
// TODO: Execute event and get story107
$story = "An event occurred in the tribe...";121
$className = $input['eventType'] . "Event";122
$event = new $className($tribe);123
$event?->execute();124
$story = $event?->getStory() ?? 'No event occurred.';108
125
109
echo json_encode([126
echo json_encode([110
'success' => true,127
'success' => true,@@ -162,9 +179,9 @@ if ($method === 'POST') {162
}179
}163
180
164
$saveManager = new SaveManager();181
$saveManager = new SaveManager();165
$spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId);166
$ageSprite = $_GET['age'] ?? 'adult';182
$ageSprite = $_GET['age'] ?? 'adult';167
$spriteFile = $spritePath . '/' . $ageSprite . '.png';183
$spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);184
$spriteFile = $spritePath;168
185
169
if (!file_exists($spriteFile)) {186
if (!file_exists($spriteFile)) {170
throw new \Exception('Sprite not found');187
throw new \Exception('Sprite not found');