BlueGit

blue-star tribegen

fix death, add environment

timfa Tim · pushed by timfa

Authored 2026-01-30 · 9 months ago

Hash
63fe0a913e466283836ee299840c1ed8e51cc83d
Parent
7ae7886d
13 files changed +671 −73
web/assets/environments/test/metadata.json +34 −30
@@ -3,64 +3,68 @@
3 3 "description": "A controlled environment used for testing purposes.",
4 4 "koboldLocations": [
5 5 {
6 "x": 0.3,
7 "y": 0.4
6 "x": 0.146,
7 "y": 0.24
8 8 },
9 9 {
10 "x": 0.6,
11 "y": 0.7
10 "x": 0.138,
11 "y": 0.51
12 12 },
13 13 {
14 "x": 0.8,
15 "y": 0.2
14 "x": 0.508,
15 "y": 0.735
16 16 },
17 17 {
18 "x": 0.1,
19 "y": 0.9
18 "x": 0.87,
19 "y": 0.314
20 20 },
21 21 {
22 "x": 0.5,
23 "y": 0.5
22 "x": 0.712,
23 "y": 0.667
24 },
25 {
26 "x": 0.891,
27 "y": 0.695
24 28 },
25 29 {
26 "x": 0.4,
27 "y": 0.3
30 "x": 0.802,
31 "y": 0.758
28 32 },
29 33 {
30 "x": 0.7,
31 "y": 0.8
34 "x": 0.391,
35 "y": 0.518
32 36 },
33 37 {
34 "x": 0.2,
35 "y": 0.1
38 "x": 0.686,
39 "y": 0.5
36 40 },
37 41 {
38 "x": 0.9,
39 "y": 0.6
42 "x": 0.578,
43 "y": 0.346
40 44 },
41 45 {
42 "x": 0.15,
43 "y": 0.25
46 "x": 0.141,
47 "y": 0.775
44 48 },
45 49 {
46 "x": 0.35,
47 "y": 0.45
50 "x": 0.306,
51 "y": 0.77
48 52 },
49 53 {
50 "x": 0.55,
51 "y": 0.65
54 "x": 0.208,
55 "y": 0.695
52 56 },
53 57 {
54 "x": 0.75,
55 "y": 0.85
58 "x": 0.583,
59 "y": 0.422
56 60 },
57 61 {
58 "x": 0.95,
59 "y": 0.15
62 "x": 0.411,
63 "y": 0.451
60 64 },
61 65 {
62 "x": 0.25,
63 "y": 0.35
66 "x": 0.504,
67 "y": 0.237
64 68 }
65 69 ]
66 70 }
@@ -3,64 +3,68 @@
3 "description": "A controlled environment used for testing purposes.",
3 "description": "A controlled environment used for testing purposes.",
4 "koboldLocations": [
4 "koboldLocations": [
5 {
5 {
6 "x": 0.3,
6 "x": 0.146,
7 "y": 0.4
7 "y": 0.24
8 },
8 },
9 {
9 {
10 "x": 0.6,
10 "x": 0.138,
11 "y": 0.7
11 "y": 0.51
12 },
12 },
13 {
13 {
14 "x": 0.8,
14 "x": 0.508,
15 "y": 0.2
15 "y": 0.735
16 },
16 },
17 {
17 {
18 "x": 0.1,
18 "x": 0.87,
19 "y": 0.9
19 "y": 0.314
20 },
20 },
21 {
21 {
22 "x": 0.5,
22 "x": 0.712,
23 "y": 0.5
23 "y": 0.667
24 },
25 {
26 "x": 0.891,
27 "y": 0.695
24 },
28 },
25 {
29 {
26 "x": 0.4,
30 "x": 0.802,
27 "y": 0.3
31 "y": 0.758
28 },
32 },
29 {
33 {
30 "x": 0.7,
34 "x": 0.391,
31 "y": 0.8
35 "y": 0.518
32 },
36 },
33 {
37 {
34 "x": 0.2,
38 "x": 0.686,
35 "y": 0.1
39 "y": 0.5
36 },
40 },
37 {
41 {
38 "x": 0.9,
42 "x": 0.578,
39 "y": 0.6
43 "y": 0.346
40 },
44 },
41 {
45 {
42 "x": 0.15,
46 "x": 0.141,
43 "y": 0.25
47 "y": 0.775
44 },
48 },
45 {
49 {
46 "x": 0.35,
50 "x": 0.306,
47 "y": 0.45
51 "y": 0.77
48 },
52 },
49 {
53 {
50 "x": 0.55,
54 "x": 0.208,
51 "y": 0.65
55 "y": 0.695
52 },
56 },
53 {
57 {
54 "x": 0.75,
58 "x": 0.583,
55 "y": 0.85
59 "y": 0.422
56 },
60 },
57 {
61 {
58 "x": 0.95,
62 "x": 0.411,
59 "y": 0.15
63 "y": 0.451
60 },
64 },
61 {
65 {
62 "x": 0.25,
66 "x": 0.504,
63 "y": 0.35
67 "y": 0.237
64 }
68 }
65 ]
69 ]
66}
70}
web/assets/injuries/malnourished-brink.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Dying of Starvation",
3 "description": "This kobold is on the brink of death from starvation.",
4 "category": "malnourished",
5 "severity": 40,
6 "statModifications": {
7 "vitality": -25,
8 "intelligence": -4,
9 "medicine": -4,
10 "crafting": -5,
11 "personality": -10,
12 "will": -15,
13 "fighting": -20
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Dying of Starvation",
3 "description": "This kobold is on the brink of death from starvation.",
4 "category": "malnourished",
5 "severity": 40,
6 "statModifications": {
7 "vitality": -25,
8 "intelligence": -4,
9 "medicine": -4,
10 "crafting": -5,
11 "personality": -10,
12 "will": -15,
13 "fighting": -20
14 }
15}
web/assets/injuries/malnourished-mild.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Mildly Malnourished",
3 "description": "This kobold is underfed and noticeably weaker.",
4 "category": "malnourished",
5 "severity": 20,
6 "statModifications": {
7 "vitality": -10,
8 "intelligence": -1,
9 "medicine": 0,
10 "crafting": -2,
11 "personality": -3,
12 "will": -5,
13 "fighting": -7
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Mildly Malnourished",
3 "description": "This kobold is underfed and noticeably weaker.",
4 "category": "malnourished",
5 "severity": 20,
6 "statModifications": {
7 "vitality": -10,
8 "intelligence": -1,
9 "medicine": 0,
10 "crafting": -2,
11 "personality": -3,
12 "will": -5,
13 "fighting": -7
14 }
15}
web/assets/injuries/malnourished-severe.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Severely Malnourished",
3 "description": "This kobold is gravely malnourished and can barely function.",
4 "category": "malnourished",
5 "severity": 30,
6 "statModifications": {
7 "vitality": -18,
8 "intelligence": -2,
9 "medicine": -2,
10 "crafting": -3,
11 "personality": -6,
12 "will": -10,
13 "fighting": -14
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Severely Malnourished",
3 "description": "This kobold is gravely malnourished and can barely function.",
4 "category": "malnourished",
5 "severity": 30,
6 "statModifications": {
7 "vitality": -18,
8 "intelligence": -2,
9 "medicine": -2,
10 "crafting": -3,
11 "personality": -6,
12 "will": -10,
13 "fighting": -14
14 }
15}
web/assets/injuries/malnourished-slight.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Slightly Malnourished",
3 "description": "This kobold has gone hungry and is beginning to weaken.",
4 "category": "malnourished",
5 "severity": 10,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -1,
11 "personality": -1,
12 "will": -2,
13 "fighting": -3
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Slightly Malnourished",
3 "description": "This kobold has gone hungry and is beginning to weaken.",
4 "category": "malnourished",
5 "severity": 10,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -1,
11 "personality": -1,
12 "will": -2,
13 "fighting": -3
14 }
15}
web/assets/injuries/malnourished.json deleted +0 −15
@@ -1,15 +0,0 @@
1 {
2 "injuryType": "Malnourished",
3 "description": "This kobold did not receive enough food and is suffering from malnutrition.",
4 "category": "malnourished",
5 "severity": 5,
6 "statModifications": {
7 "vitality": -10,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -1,
11 "personality": -3,
12 "will": -5,
13 "fighting": -8
14 }
15 }
@@ -1,15 +0,0 @@
1{
2 "injuryType": "Malnourished",
3 "description": "This kobold did not receive enough food and is suffering from malnutrition.",
4 "category": "malnourished",
5 "severity": 5,
6 "statModifications": {
7 "vitality": -10,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -1,
11 "personality": -3,
12 "will": -5,
13 "fighting": -8
14 }
15}
web/css/style.css +65 −7
@@ -348,21 +348,42 @@ button {
348 348 flex-direction: column;
349 349 border-right: 2px solid #eee;
350 350 overflow-y: auto;
351 padding: 15px;
352 gap: 15px;
351 353 }
352 354
353 355 .environment {
354 flex: 1;
356 flex: 0 0 auto;
357 width: 100%;
358 aspect-ratio: 1 / 1;
355 359 background: linear-gradient(to bottom, #87ceeb, #90ee90);
360 background-size: 100% 100%;
361 background-repeat: no-repeat;
362 background-position: center;
356 363 position: relative;
357 overflow-y: auto;
364 overflow: hidden;
365 border: 1px solid #ddd;
366 border-radius: 8px;
358 367 }
359 368
360 369 .placements {
361 display: flex;
362 flex-wrap: wrap;
363 gap: 10px;
364 padding: 10px;
365 background: #f9f9f9;
370 position: absolute;
371 inset: 0;
372 pointer-events: auto;
373 }
374
375 .kobold-placement {
376 position: absolute;
377 width: 80px;
378 height: 80px;
379 transform: translate(-50%, -66.666%);
380 pointer-events: auto;
381 cursor: pointer;
382 image-rendering: pixelated;
383 }
384
385 .kobold-placement.flipped {
386 transform: translate(-50%, -66.666%) scaleX(-1);
366 387 }
367 388
368 389 .placement {
@@ -386,6 +407,43 @@ button {
386 407 transform: scale(1.05);
387 408 }
388 409
410 .environment-selection {
411 display: flex;
412 flex-direction: column;
413 gap: 12px;
414 margin-bottom: 20px;
415 }
416
417 .environment-select {
418 padding: 10px;
419 border: 1px solid #ddd;
420 border-radius: 6px;
421 font-size: 1em;
422 }
423
424 .environment-preview {
425 width: 50%;
426 aspect-ratio: 1 / 1;
427 border: 1px solid #ddd;
428 border-radius: 8px;
429 overflow: hidden;
430 background: #f9f9f9;
431 display: flex;
432 align-items: center;
433 justify-content: center;
434 }
435
436 .environment-preview img {
437 width: 100%;
438 height: 100%;
439 object-fit: cover;
440 }
441
442 .environment-description {
443 color: #666;
444 font-size: 0.95em;
445 }
446
389 447 .game-right {
390 448 width: 300px;
391 449 display: flex;
@@ -348,21 +348,42 @@ button {
348 flex-direction: column;
348 flex-direction: column;
349 border-right: 2px solid #eee;
349 border-right: 2px solid #eee;
350 overflow-y: auto;
350 overflow-y: auto;
351 padding: 15px;
352 gap: 15px;
351}
353}
352
354
353.environment {
355.environment {
354 flex: 1;
356 flex: 0 0 auto;
357 width: 100%;
358 aspect-ratio: 1 / 1;
355 background: linear-gradient(to bottom, #87ceeb, #90ee90);
359 background: linear-gradient(to bottom, #87ceeb, #90ee90);
360 background-size: 100% 100%;
361 background-repeat: no-repeat;
362 background-position: center;
356 position: relative;
363 position: relative;
357 overflow-y: auto;
364 overflow: hidden;
365 border: 1px solid #ddd;
366 border-radius: 8px;
358}
367}
359
368
360.placements {
369.placements {
361 display: flex;
370 position: absolute;
362 flex-wrap: wrap;
371 inset: 0;
363 gap: 10px;
372 pointer-events: auto;
364 padding: 10px;
373}
365 background: #f9f9f9;
374
375.kobold-placement {
376 position: absolute;
377 width: 80px;
378 height: 80px;
379 transform: translate(-50%, -66.666%);
380 pointer-events: auto;
381 cursor: pointer;
382 image-rendering: pixelated;
383}
384
385.kobold-placement.flipped {
386 transform: translate(-50%, -66.666%) scaleX(-1);
366}
387}
367
388
368.placement {
389.placement {
@@ -386,6 +407,43 @@ button {
386 transform: scale(1.05);
407 transform: scale(1.05);
387}
408}
388
409
410.environment-selection {
411 display: flex;
412 flex-direction: column;
413 gap: 12px;
414 margin-bottom: 20px;
415}
416
417.environment-select {
418 padding: 10px;
419 border: 1px solid #ddd;
420 border-radius: 6px;
421 font-size: 1em;
422}
423
424.environment-preview {
425 width: 50%;
426 aspect-ratio: 1 / 1;
427 border: 1px solid #ddd;
428 border-radius: 8px;
429 overflow: hidden;
430 background: #f9f9f9;
431 display: flex;
432 align-items: center;
433 justify-content: center;
434}
435
436.environment-preview img {
437 width: 100%;
438 height: 100%;
439 object-fit: cover;
440}
441
442.environment-description {
443 color: #666;
444 font-size: 0.95em;
445}
446
389.game-right {
447.game-right {
390 width: 300px;
448 width: 300px;
391 display: flex;
449 display: flex;
web/index.php +2 −0
@@ -49,6 +49,8 @@ if (strpos($path, '/api/') === 0) {
49 49 include __DIR__ . '/src/api/game.php';
50 50 } elseif ($apiPath === 'game/returnItem') {
51 51 include __DIR__ . '/src/api/game.php';
52 } elseif ($apiPath === 'game/environments') {
53 include __DIR__ . '/src/api/game.php';
52 54 } elseif ($apiPath === 'game/cureInjury') {
53 55 include __DIR__ . '/src/api/game.php';
54 56 } else {
@@ -49,6 +49,8 @@ if (strpos($path, '/api/') === 0) {
49 include __DIR__ . '/src/api/game.php';
49 include __DIR__ . '/src/api/game.php';
50 } elseif ($apiPath === 'game/returnItem') {
50 } elseif ($apiPath === 'game/returnItem') {
51 include __DIR__ . '/src/api/game.php';
51 include __DIR__ . '/src/api/game.php';
52 } elseif ($apiPath === 'game/environments') {
53 include __DIR__ . '/src/api/game.php';
52 } elseif ($apiPath === 'game/cureInjury') {
54 } elseif ($apiPath === 'game/cureInjury') {
53 include __DIR__ . '/src/api/game.php';
55 include __DIR__ . '/src/api/game.php';
54 } else {
56 } else {
web/indexHtml.html +18 −3
@@ -80,7 +80,21 @@
80 80 <p>Select 5 more tribe members:</p>
81 81 <div id="memberSelectionGrid" class="kobold-grid"></div>
82 82 <div id="memberCount" class="counter">0 / 5 selected</div>
83 <button id="finishTribeBtn" class="primary" disabled>Finish</button>
83 <button id="finishTribeBtn" class="primary" disabled>Choose Environment</button>
84 </div>
85
86 <div class="setup-step hidden" id="setupStep4">
87 <p>Select a tribe environment:</p>
88 <div class="environment-selection">
89 <select id="environmentSelect" class="environment-select">
90 <option value="">Select an environment...</option>
91 </select>
92 <div class="environment-preview">
93 <img id="environmentPreview" alt="Environment preview">
94 </div>
95 <div id="environmentDescription" class="environment-description"></div>
96 </div>
97 <button id="confirmEnvironmentBtn" class="primary" disabled>Start Game</button>
84 98 </div>
85 99 </div>
86 100 </div>
@@ -98,8 +112,9 @@
98 112
99 113 <div class="game-main">
100 114 <div class="game-left">
101 <div id="environment" class="environment"></div>
102 <div id="koboldPlacements" class="placements"></div>
115 <div id="environment" class="environment">
116 <div id="koboldPlacements" class="placements"></div>
117 </div>
103 118 </div>
104 119
105 120 <div class="game-right">
@@ -80,7 +80,21 @@
80 <p>Select 5 more tribe members:</p>
80 <p>Select 5 more tribe members:</p>
81 <div id="memberSelectionGrid" class="kobold-grid"></div>
81 <div id="memberSelectionGrid" class="kobold-grid"></div>
82 <div id="memberCount" class="counter">0 / 5 selected</div>
82 <div id="memberCount" class="counter">0 / 5 selected</div>
83 <button id="finishTribeBtn" class="primary" disabled>Finish</button>
83 <button id="finishTribeBtn" class="primary" disabled>Choose Environment</button>
84 </div>
85
86 <div class="setup-step hidden" id="setupStep4">
87 <p>Select a tribe environment:</p>
88 <div class="environment-selection">
89 <select id="environmentSelect" class="environment-select">
90 <option value="">Select an environment...</option>
91 </select>
92 <div class="environment-preview">
93 <img id="environmentPreview" alt="Environment preview">
94 </div>
95 <div id="environmentDescription" class="environment-description"></div>
96 </div>
97 <button id="confirmEnvironmentBtn" class="primary" disabled>Start Game</button>
84 </div>
98 </div>
85 </div>
99 </div>
86 </div>
100 </div>
@@ -98,8 +112,9 @@
98
112
99 <div class="game-main">
113 <div class="game-main">
100 <div class="game-left">
114 <div class="game-left">
101 <div id="environment" class="environment"></div>
115 <div id="environment" class="environment">
102 <div id="koboldPlacements" class="placements"></div>
116 <div id="koboldPlacements" class="placements"></div>
117 </div>
103 </div>
118 </div>
104
119
105 <div class="game-right">
120 <div class="game-right">
web/js/app.js +375 −4
@@ -9,6 +9,12 @@ class TribeGenApp
9 9 this.currentTribe = null;
10 10 this.availableEvents = [];
11 11 this.availableEventsByType = {};
12 this.environments = [];
13 this.environmentMap = {};
14 this.environmentPreviewTimer = null;
15 this.selectedEnvironmentId = null;
16 this.pendingSetup = null;
17 this.lastPlacementKey = null;
12 18 this.init();
13 19 }
14 20
@@ -38,9 +44,24 @@ class TribeGenApp
38 44 document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds());
39 45 document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader());
40 46 document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe());
47 const envSelect = document.getElementById('environmentSelect');
48 if (envSelect)
49 {
50 envSelect.addEventListener('change', () => this.handleEnvironmentSelection());
51 }
52 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
53 if (confirmEnvBtn)
54 {
55 confirmEnvBtn.addEventListener('click', () => this.confirmEnvironment());
56 }
41 57
42 58 // Game Screen
43 59 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
60 const environmentEl = document.getElementById('environment');
61 if (environmentEl)
62 {
63 environmentEl.addEventListener('click', (e) => this.logEnvironmentClick(e));
64 }
44 65
45 66 // Modal close buttons
46 67 document.querySelectorAll('.modal-close').forEach(btn =>
@@ -230,6 +251,9 @@ class TribeGenApp
230 251 document.getElementById('setupStep1').classList.remove('hidden');
231 252 document.getElementById('setupStep2').classList.add('hidden');
232 253 document.getElementById('setupStep3').classList.add('hidden');
254 document.getElementById('setupStep4').classList.add('hidden');
255 this.selectedEnvironmentId = null;
256 this.pendingSetup = null;
233 257 }
234 258
235 259 async generateKobolds ()
@@ -381,7 +405,171 @@ class TribeGenApp
381 405 return Array.from(card.parentElement.children).indexOf(card);
382 406 });
383 407
384 // Load the game
408 this.pendingSetup = {
409 leaderIndex: leaderIndex,
410 memberIndices: memberIndices,
411 leaderName: document.getElementById('leaderName').value
412 };
413
414 await this.showEnvironmentStep();
415 }
416
417 async showEnvironmentStep ()
418 {
419 await this.ensureEnvironmentsLoaded();
420 this.renderEnvironmentOptions();
421 const select = document.getElementById('environmentSelect');
422 if (select)
423 {
424 select.value = '';
425 }
426 document.getElementById('setupStep3').classList.add('hidden');
427 document.getElementById('setupStep4').classList.remove('hidden');
428 this.selectedEnvironmentId = null;
429 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
430 if (confirmEnvBtn)
431 {
432 confirmEnvBtn.disabled = true;
433 }
434 this.stopEnvironmentPreview();
435 const preview = document.getElementById('environmentPreview');
436 if (preview)
437 {
438 preview.removeAttribute('src');
439 }
440 const desc = document.getElementById('environmentDescription');
441 if (desc)
442 {
443 desc.textContent = '';
444 }
445 }
446
447 async ensureEnvironmentsLoaded ()
448 {
449 if (this.environments && this.environments.length > 0)
450 {
451 return;
452 }
453
454 await this.loadEnvironments();
455 }
456
457 async loadEnvironments ()
458 {
459 try
460 {
461 const response = await fetch('api/game/environments', {
462 method: 'GET'
463 });
464
465 const dataText = await response.text();
466 const data = JSON.parse(dataText);
467
468 if (data.success)
469 {
470 this.environments = data.environments || [];
471 this.environmentMap = {};
472 this.environments.forEach(env =>
473 {
474 if (env && env.id)
475 {
476 this.environmentMap[env.id] = env;
477 }
478 });
479 }
480 } catch (error)
481 {
482 console.error('Failed to load environments', error);
483 }
484 }
485
486 renderEnvironmentOptions ()
487 {
488 const select = document.getElementById('environmentSelect');
489 if (!select)
490 {
491 return;
492 }
493
494 select.innerHTML = '<option value="">Select an environment...</option>';
495 this.environments.forEach(env =>
496 {
497 const option = document.createElement('option');
498 option.value = env.id;
499 option.textContent = env.name || env.id;
500 select.appendChild(option);
501 });
502 }
503
504 handleEnvironmentSelection ()
505 {
506 const select = document.getElementById('environmentSelect');
507 const envId = select ? select.value : '';
508 this.selectedEnvironmentId = envId || null;
509
510 const env = this.environmentMap[envId];
511 const desc = document.getElementById('environmentDescription');
512 if (desc)
513 {
514 desc.textContent = env && env.description ? env.description : '';
515 }
516
517 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
518 if (confirmEnvBtn)
519 {
520 confirmEnvBtn.disabled = !envId;
521 }
522
523 if (env && Array.isArray(env.images))
524 {
525 this.startEnvironmentPreview(env.images);
526 } else
527 {
528 this.stopEnvironmentPreview();
529 }
530 }
531
532 startEnvironmentPreview (images)
533 {
534 this.stopEnvironmentPreview();
535 const preview = document.getElementById('environmentPreview');
536 if (!preview || !images || images.length === 0)
537 {
538 return;
539 }
540
541 let index = 0;
542 preview.src = images[index];
543 this.environmentPreviewTimer = setInterval(() =>
544 {
545 index = (index + 1) % images.length;
546 preview.src = images[index];
547 }, 2000);
548 }
549
550 stopEnvironmentPreview ()
551 {
552 if (this.environmentPreviewTimer)
553 {
554 clearInterval(this.environmentPreviewTimer);
555 this.environmentPreviewTimer = null;
556 }
557 }
558
559 async confirmEnvironment ()
560 {
561 if (!this.pendingSetup)
562 {
563 alert('Missing tribe setup data. Please start again.');
564 return;
565 }
566
567 if (!this.selectedEnvironmentId)
568 {
569 alert('Please select an environment');
570 return;
571 }
572
385 573 try
386 574 {
387 575 const response = await fetch('api/game/save', {
@@ -393,9 +581,10 @@ class TribeGenApp
393 581 body: JSON.stringify({
394 582 userId: this.currentUser.id,
395 583 saveId: this.currentSave.id,
396 leaderName: document.getElementById('leaderName').value,
397 memberIndices: memberIndices,
398 leaderId: leaderIndex
584 leaderName: this.pendingSetup.leaderName,
585 memberIndices: this.pendingSetup.memberIndices,
586 leaderId: this.pendingSetup.leaderIndex,
587 environmentId: this.selectedEnvironmentId
399 588 })
400 589 });
401 590
@@ -404,6 +593,7 @@ class TribeGenApp
404 593
405 594 if (data.success)
406 595 {
596 this.stopEnvironmentPreview();
407 597 this.loadGame(this.currentSave.id);
408 598 }
409 599 } catch (error)
@@ -429,6 +619,7 @@ class TribeGenApp
429 619 {
430 620 this.currentSave = data.save;
431 621 this.currentTribe = data.tribe;
622 await this.ensureEnvironmentsLoaded();
432 623 await this.fetchAvailableEvents();
433 624 this.showGameScreen();
434 625 }
@@ -452,11 +643,191 @@ class TribeGenApp
452 643 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
453 644 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
454 645
646 this.renderEnvironment();
455 647 this.renderStorage();
456 648 this.renderTribeList();
457 649 this.renderEvents();
458 650 }
459 651
652 renderEnvironment ()
653 {
654 const envElement = document.getElementById('environment');
655 if (!envElement)
656 {
657 return;
658 }
659
660 const envId = this.getActiveEnvironmentId();
661 if (!envId)
662 {
663 envElement.style.backgroundImage = '';
664 const placements = document.getElementById('koboldPlacements');
665 if (placements)
666 {
667 placements.innerHTML = '';
668 }
669 return;
670 }
671
672 const season = (this.currentSave.current_season || 'spring').toLowerCase();
673 let imageUrl = `assets/environments/${envId}/${season}.png`;
674 const env = this.environmentMap[envId];
675 if (env && Array.isArray(env.images) && env.images.length > 0)
676 {
677 const seasonMatch = env.images.find(img => img.includes(`/${season}.png`));
678 if (seasonMatch)
679 {
680 imageUrl = seasonMatch;
681 } else
682 {
683 imageUrl = env.images[0];
684 }
685 }
686
687 envElement.style.backgroundImage = `url('${imageUrl}')`;
688 this.renderEnvironmentPlacements(envId);
689 }
690
691 renderEnvironmentPlacements (envId)
692 {
693 const placements = document.getElementById('koboldPlacements');
694 if (!placements)
695 {
696 return;
697 }
698
699 const placementKey = `${this.currentSave?.id ?? 'save'}-${envId}-${this.currentSave?.current_month ?? 0}`;
700 if (this.lastPlacementKey === placementKey && placements.children.length > 0)
701 {
702 return;
703 }
704
705 this.lastPlacementKey = placementKey;
706 placements.innerHTML = '';
707 const env = this.environmentMap[envId];
708 if (!env || !Array.isArray(env.koboldLocations))
709 {
710 return;
711 }
712
713 const spots = env.koboldLocations
714 .map(loc => ({
715 x: loc ? Number(loc.x) : NaN,
716 y: loc ? Number(loc.y) : NaN
717 }))
718 .filter(loc => Number.isFinite(loc.x) && Number.isFinite(loc.y));
719
720 if (spots.length === 0 || !this.currentTribe || !Array.isArray(this.currentTribe.kobolds))
721 {
722 return;
723 }
724
725 let availableSpots = this.shuffleArray(spots.slice());
726 if (availableSpots.length > 30)
727 {
728 availableSpots = availableSpots.slice(0, 30);
729 }
730
731 let leader = this.currentTribe.kobolds.find(k => k.is_leader);
732 if (!leader)
733 {
734 leader = this.currentTribe.kobolds[0];
735 }
736
737 if (!leader)
738 {
739 return;
740 }
741
742 const leaderSpotIndex = Math.floor(Math.random() * availableSpots.length);
743 const leaderSpot = availableSpots.splice(leaderSpotIndex, 1)[0];
744 const placementList = [{ kobold: leader, spot: leaderSpot }];
745
746 const others = this.currentTribe.kobolds.filter(k => k.id !== leader.id);
747 const shuffledOthers = this.shuffleArray(others.slice());
748 const maxOthers = Math.min(availableSpots.length, 29, shuffledOthers.length);
749
750 for (let i = 0; i < maxOthers; i++)
751 {
752 placementList.push({ kobold: shuffledOthers[i], spot: availableSpots[i] });
753 }
754
755 placementList.sort((a, b) => a.spot.y - b.spot.y);
756
757 placementList.forEach(entry =>
758 {
759 const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${entry.kobold.id}&age=${entry.kobold.ageCategory}`;
760 const img = document.createElement('img');
761 img.src = spriteUrl;
762 img.alt = entry.kobold.name;
763 img.className = 'kobold-placement';
764 if (Math.random() < 0.5)
765 {
766 img.classList.add('flipped');
767 }
768 img.style.left = `${entry.spot.x * 100}%`;
769 img.style.top = `${entry.spot.y * 100}%`;
770 img.style.zIndex = Math.round(entry.spot.y * 1000).toString();
771 img.addEventListener('click', (event) =>
772 {
773 event.stopPropagation();
774 this.showKoboldModal(entry.kobold);
775 });
776 placements.appendChild(img);
777 });
778 }
779
780 getActiveEnvironmentId ()
781 {
782 if (this.currentSave && this.currentSave.environment_id)
783 {
784 return this.currentSave.environment_id;
785 }
786 if (this.selectedEnvironmentId)
787 {
788 return this.selectedEnvironmentId;
789 }
790 if (this.environments && this.environments.length > 0)
791 {
792 return this.environments[0].id;
793 }
794 return null;
795 }
796
797 logEnvironmentClick (event)
798 {
799 const envElement = document.getElementById('environment');
800 if (!envElement)
801 {
802 return;
803 }
804
805 if (event.target && event.target.closest && event.target.closest('.kobold-placement'))
806 {
807 return;
808 }
809
810 const rect = envElement.getBoundingClientRect();
811 const x = (event.clientX - rect.left) / rect.width;
812 const y = (event.clientY - rect.top) / rect.height;
813 const normalizedX = Math.max(0, Math.min(1, x));
814 const normalizedY = Math.max(0, Math.min(1, y));
815 console.log('Environment click:', {
816 x: Number(normalizedX.toFixed(3)),
817 y: Number(normalizedY.toFixed(3))
818 });
819 }
820
821 shuffleArray (array)
822 {
823 for (let i = array.length - 1; i > 0; i--)
824 {
825 const j = Math.floor(Math.random() * (i + 1));
826 [array[i], array[j]] = [array[j], array[i]];
827 }
828 return array;
829 }
830
460 831 renderTribeList ()
461 832 {
462 833 const list = document.getElementById('tribeList');
@@ -9,6 +9,12 @@ class TribeGenApp
9 this.currentTribe = null;
9 this.currentTribe = null;
10 this.availableEvents = [];
10 this.availableEvents = [];
11 this.availableEventsByType = {};
11 this.availableEventsByType = {};
12 this.environments = [];
13 this.environmentMap = {};
14 this.environmentPreviewTimer = null;
15 this.selectedEnvironmentId = null;
16 this.pendingSetup = null;
17 this.lastPlacementKey = null;
12 this.init();
18 this.init();
13 }
19 }
14
20
@@ -38,9 +44,24 @@ class TribeGenApp
38 document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds());
44 document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds());
39 document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader());
45 document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader());
40 document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe());
46 document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe());
47 const envSelect = document.getElementById('environmentSelect');
48 if (envSelect)
49 {
50 envSelect.addEventListener('change', () => this.handleEnvironmentSelection());
51 }
52 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
53 if (confirmEnvBtn)
54 {
55 confirmEnvBtn.addEventListener('click', () => this.confirmEnvironment());
56 }
41
57
42 // Game Screen
58 // Game Screen
43 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
59 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
60 const environmentEl = document.getElementById('environment');
61 if (environmentEl)
62 {
63 environmentEl.addEventListener('click', (e) => this.logEnvironmentClick(e));
64 }
44
65
45 // Modal close buttons
66 // Modal close buttons
46 document.querySelectorAll('.modal-close').forEach(btn =>
67 document.querySelectorAll('.modal-close').forEach(btn =>
@@ -230,6 +251,9 @@ class TribeGenApp
230 document.getElementById('setupStep1').classList.remove('hidden');
251 document.getElementById('setupStep1').classList.remove('hidden');
231 document.getElementById('setupStep2').classList.add('hidden');
252 document.getElementById('setupStep2').classList.add('hidden');
232 document.getElementById('setupStep3').classList.add('hidden');
253 document.getElementById('setupStep3').classList.add('hidden');
254 document.getElementById('setupStep4').classList.add('hidden');
255 this.selectedEnvironmentId = null;
256 this.pendingSetup = null;
233 }
257 }
234
258
235 async generateKobolds ()
259 async generateKobolds ()
@@ -381,7 +405,171 @@ class TribeGenApp
381 return Array.from(card.parentElement.children).indexOf(card);
405 return Array.from(card.parentElement.children).indexOf(card);
382 });
406 });
383
407
384 // Load the game
408 this.pendingSetup = {
409 leaderIndex: leaderIndex,
410 memberIndices: memberIndices,
411 leaderName: document.getElementById('leaderName').value
412 };
413
414 await this.showEnvironmentStep();
415 }
416
417 async showEnvironmentStep ()
418 {
419 await this.ensureEnvironmentsLoaded();
420 this.renderEnvironmentOptions();
421 const select = document.getElementById('environmentSelect');
422 if (select)
423 {
424 select.value = '';
425 }
426 document.getElementById('setupStep3').classList.add('hidden');
427 document.getElementById('setupStep4').classList.remove('hidden');
428 this.selectedEnvironmentId = null;
429 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
430 if (confirmEnvBtn)
431 {
432 confirmEnvBtn.disabled = true;
433 }
434 this.stopEnvironmentPreview();
435 const preview = document.getElementById('environmentPreview');
436 if (preview)
437 {
438 preview.removeAttribute('src');
439 }
440 const desc = document.getElementById('environmentDescription');
441 if (desc)
442 {
443 desc.textContent = '';
444 }
445 }
446
447 async ensureEnvironmentsLoaded ()
448 {
449 if (this.environments && this.environments.length > 0)
450 {
451 return;
452 }
453
454 await this.loadEnvironments();
455 }
456
457 async loadEnvironments ()
458 {
459 try
460 {
461 const response = await fetch('api/game/environments', {
462 method: 'GET'
463 });
464
465 const dataText = await response.text();
466 const data = JSON.parse(dataText);
467
468 if (data.success)
469 {
470 this.environments = data.environments || [];
471 this.environmentMap = {};
472 this.environments.forEach(env =>
473 {
474 if (env && env.id)
475 {
476 this.environmentMap[env.id] = env;
477 }
478 });
479 }
480 } catch (error)
481 {
482 console.error('Failed to load environments', error);
483 }
484 }
485
486 renderEnvironmentOptions ()
487 {
488 const select = document.getElementById('environmentSelect');
489 if (!select)
490 {
491 return;
492 }
493
494 select.innerHTML = '<option value="">Select an environment...</option>';
495 this.environments.forEach(env =>
496 {
497 const option = document.createElement('option');
498 option.value = env.id;
499 option.textContent = env.name || env.id;
500 select.appendChild(option);
501 });
502 }
503
504 handleEnvironmentSelection ()
505 {
506 const select = document.getElementById('environmentSelect');
507 const envId = select ? select.value : '';
508 this.selectedEnvironmentId = envId || null;
509
510 const env = this.environmentMap[envId];
511 const desc = document.getElementById('environmentDescription');
512 if (desc)
513 {
514 desc.textContent = env && env.description ? env.description : '';
515 }
516
517 const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn');
518 if (confirmEnvBtn)
519 {
520 confirmEnvBtn.disabled = !envId;
521 }
522
523 if (env && Array.isArray(env.images))
524 {
525 this.startEnvironmentPreview(env.images);
526 } else
527 {
528 this.stopEnvironmentPreview();
529 }
530 }
531
532 startEnvironmentPreview (images)
533 {
534 this.stopEnvironmentPreview();
535 const preview = document.getElementById('environmentPreview');
536 if (!preview || !images || images.length === 0)
537 {
538 return;
539 }
540
541 let index = 0;
542 preview.src = images[index];
543 this.environmentPreviewTimer = setInterval(() =>
544 {
545 index = (index + 1) % images.length;
546 preview.src = images[index];
547 }, 2000);
548 }
549
550 stopEnvironmentPreview ()
551 {
552 if (this.environmentPreviewTimer)
553 {
554 clearInterval(this.environmentPreviewTimer);
555 this.environmentPreviewTimer = null;
556 }
557 }
558
559 async confirmEnvironment ()
560 {
561 if (!this.pendingSetup)
562 {
563 alert('Missing tribe setup data. Please start again.');
564 return;
565 }
566
567 if (!this.selectedEnvironmentId)
568 {
569 alert('Please select an environment');
570 return;
571 }
572
385 try
573 try
386 {
574 {
387 const response = await fetch('api/game/save', {
575 const response = await fetch('api/game/save', {
@@ -393,9 +581,10 @@ class TribeGenApp
393 body: JSON.stringify({
581 body: JSON.stringify({
394 userId: this.currentUser.id,
582 userId: this.currentUser.id,
395 saveId: this.currentSave.id,
583 saveId: this.currentSave.id,
396 leaderName: document.getElementById('leaderName').value,
584 leaderName: this.pendingSetup.leaderName,
397 memberIndices: memberIndices,
585 memberIndices: this.pendingSetup.memberIndices,
398 leaderId: leaderIndex
586 leaderId: this.pendingSetup.leaderIndex,
587 environmentId: this.selectedEnvironmentId
399 })
588 })
400 });
589 });
401
590
@@ -404,6 +593,7 @@ class TribeGenApp
404
593
405 if (data.success)
594 if (data.success)
406 {
595 {
596 this.stopEnvironmentPreview();
407 this.loadGame(this.currentSave.id);
597 this.loadGame(this.currentSave.id);
408 }
598 }
409 } catch (error)
599 } catch (error)
@@ -429,6 +619,7 @@ class TribeGenApp
429 {
619 {
430 this.currentSave = data.save;
620 this.currentSave = data.save;
431 this.currentTribe = data.tribe;
621 this.currentTribe = data.tribe;
622 await this.ensureEnvironmentsLoaded();
432 await this.fetchAvailableEvents();
623 await this.fetchAvailableEvents();
433 this.showGameScreen();
624 this.showGameScreen();
434 }
625 }
@@ -452,11 +643,191 @@ class TribeGenApp
452 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
643 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
453 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
644 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
454
645
646 this.renderEnvironment();
455 this.renderStorage();
647 this.renderStorage();
456 this.renderTribeList();
648 this.renderTribeList();
457 this.renderEvents();
649 this.renderEvents();
458 }
650 }
459
651
652 renderEnvironment ()
653 {
654 const envElement = document.getElementById('environment');
655 if (!envElement)
656 {
657 return;
658 }
659
660 const envId = this.getActiveEnvironmentId();
661 if (!envId)
662 {
663 envElement.style.backgroundImage = '';
664 const placements = document.getElementById('koboldPlacements');
665 if (placements)
666 {
667 placements.innerHTML = '';
668 }
669 return;
670 }
671
672 const season = (this.currentSave.current_season || 'spring').toLowerCase();
673 let imageUrl = `assets/environments/${envId}/${season}.png`;
674 const env = this.environmentMap[envId];
675 if (env && Array.isArray(env.images) && env.images.length > 0)
676 {
677 const seasonMatch = env.images.find(img => img.includes(`/${season}.png`));
678 if (seasonMatch)
679 {
680 imageUrl = seasonMatch;
681 } else
682 {
683 imageUrl = env.images[0];
684 }
685 }
686
687 envElement.style.backgroundImage = `url('${imageUrl}')`;
688 this.renderEnvironmentPlacements(envId);
689 }
690
691 renderEnvironmentPlacements (envId)
692 {
693 const placements = document.getElementById('koboldPlacements');
694 if (!placements)
695 {
696 return;
697 }
698
699 const placementKey = `${this.currentSave?.id ?? 'save'}-${envId}-${this.currentSave?.current_month ?? 0}`;
700 if (this.lastPlacementKey === placementKey && placements.children.length > 0)
701 {
702 return;
703 }
704
705 this.lastPlacementKey = placementKey;
706 placements.innerHTML = '';
707 const env = this.environmentMap[envId];
708 if (!env || !Array.isArray(env.koboldLocations))
709 {
710 return;
711 }
712
713 const spots = env.koboldLocations
714 .map(loc => ({
715 x: loc ? Number(loc.x) : NaN,
716 y: loc ? Number(loc.y) : NaN
717 }))
718 .filter(loc => Number.isFinite(loc.x) && Number.isFinite(loc.y));
719
720 if (spots.length === 0 || !this.currentTribe || !Array.isArray(this.currentTribe.kobolds))
721 {
722 return;
723 }
724
725 let availableSpots = this.shuffleArray(spots.slice());
726 if (availableSpots.length > 30)
727 {
728 availableSpots = availableSpots.slice(0, 30);
729 }
730
731 let leader = this.currentTribe.kobolds.find(k => k.is_leader);
732 if (!leader)
733 {
734 leader = this.currentTribe.kobolds[0];
735 }
736
737 if (!leader)
738 {
739 return;
740 }
741
742 const leaderSpotIndex = Math.floor(Math.random() * availableSpots.length);
743 const leaderSpot = availableSpots.splice(leaderSpotIndex, 1)[0];
744 const placementList = [{ kobold: leader, spot: leaderSpot }];
745
746 const others = this.currentTribe.kobolds.filter(k => k.id !== leader.id);
747 const shuffledOthers = this.shuffleArray(others.slice());
748 const maxOthers = Math.min(availableSpots.length, 29, shuffledOthers.length);
749
750 for (let i = 0; i < maxOthers; i++)
751 {
752 placementList.push({ kobold: shuffledOthers[i], spot: availableSpots[i] });
753 }
754
755 placementList.sort((a, b) => a.spot.y - b.spot.y);
756
757 placementList.forEach(entry =>
758 {
759 const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${entry.kobold.id}&age=${entry.kobold.ageCategory}`;
760 const img = document.createElement('img');
761 img.src = spriteUrl;
762 img.alt = entry.kobold.name;
763 img.className = 'kobold-placement';
764 if (Math.random() < 0.5)
765 {
766 img.classList.add('flipped');
767 }
768 img.style.left = `${entry.spot.x * 100}%`;
769 img.style.top = `${entry.spot.y * 100}%`;
770 img.style.zIndex = Math.round(entry.spot.y * 1000).toString();
771 img.addEventListener('click', (event) =>
772 {
773 event.stopPropagation();
774 this.showKoboldModal(entry.kobold);
775 });
776 placements.appendChild(img);
777 });
778 }
779
780 getActiveEnvironmentId ()
781 {
782 if (this.currentSave && this.currentSave.environment_id)
783 {
784 return this.currentSave.environment_id;
785 }
786 if (this.selectedEnvironmentId)
787 {
788 return this.selectedEnvironmentId;
789 }
790 if (this.environments && this.environments.length > 0)
791 {
792 return this.environments[0].id;
793 }
794 return null;
795 }
796
797 logEnvironmentClick (event)
798 {
799 const envElement = document.getElementById('environment');
800 if (!envElement)
801 {
802 return;
803 }
804
805 if (event.target && event.target.closest && event.target.closest('.kobold-placement'))
806 {
807 return;
808 }
809
810 const rect = envElement.getBoundingClientRect();
811 const x = (event.clientX - rect.left) / rect.width;
812 const y = (event.clientY - rect.top) / rect.height;
813 const normalizedX = Math.max(0, Math.min(1, x));
814 const normalizedY = Math.max(0, Math.min(1, y));
815 console.log('Environment click:', {
816 x: Number(normalizedX.toFixed(3)),
817 y: Number(normalizedY.toFixed(3))
818 });
819 }
820
821 shuffleArray (array)
822 {
823 for (let i = array.length - 1; i > 0; i--)
824 {
825 const j = Math.floor(Math.random() * (i + 1));
826 [array[i], array[j]] = [array[j], array[i]];
827 }
828 return array;
829 }
830
460 renderTribeList ()
831 renderTribeList ()
461 {
832 {
462 const list = document.getElementById('tribeList');
833 const list = document.getElementById('tribeList');
web/src/Classes/Kobold.php +5 −0
@@ -102,6 +102,11 @@ class Kobold
102 102 $this->isLeader = true;
103 103 }
104 104
105 public function isLeader()
106 {
107 return $this->isLeader;
108 }
109
105 110 public static function generate($userId, $saveId, $age = null)
106 111 {
107 112 if ($age === null) {
@@ -102,6 +102,11 @@ class Kobold
102 $this->isLeader = true;
102 $this->isLeader = true;
103 }
103 }
104
104
105 public function isLeader()
106 {
107 return $this->isLeader;
108 }
109
105 public static function generate($userId, $saveId, $age = null)
110 public static function generate($userId, $saveId, $age = null)
106 {
111 {
107 if ($age === null) {
112 if ($age === null) {
web/src/Classes/Tribe.php +49 −14
@@ -13,6 +13,7 @@ class Tribe
13 13 private $currentMonth = 0;
14 14 private $currentSeason = 'spring';
15 15 private $foodCount = 0;
16 private $environmentId = null;
16 17 private $createdAt;
17 18 private $lastPlayed;
18 19 private $saveManager;
@@ -66,6 +67,7 @@ class Tribe
66 67 $this->currentMonth = $data['current_month'] ?? 0;
67 68 $this->currentSeason = $data['current_season'] ?? 'spring';
68 69 $this->foodCount = $data['food_count'] ?? 0;
70 $this->environmentId = $data['environment_id'] ?? null;
69 71 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
70 72 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
71 73 }
@@ -121,6 +123,7 @@ class Tribe
121 123 'current_season' => $this->currentSeason,
122 124 'food_count' => $this->foodCount,
123 125 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
126 'environment_id' => $this->environmentId,
124 127 'created_at' => $this->createdAt,
125 128 'last_played' => $this->lastPlayed
126 129 ];
@@ -195,6 +198,16 @@ class Tribe
195 198 $this->currentSeason = $season;
196 199 }
197 200
201 public function getEnvironmentId()
202 {
203 return $this->environmentId;
204 }
205
206 public function setEnvironmentId($environmentId)
207 {
208 $this->environmentId = $environmentId;
209 }
210
198 211 // Kobold management
199 212 public function getKobolds($includeDeadAndExpelled = false)
200 213 {
@@ -359,19 +372,27 @@ class Tribe
359 372 $starvedKobolds[$kobold->getId()] = $kobold;
360 373 $this->foodCount = 0; // Use remaining food
361 374
362 // Add malnourished injury if not already present
363 if (!$this->hasInjuryCategory($kobold, 'malnourished')) {
364 $kobold->addInjury('malnourished');
365 $story .= "{$kobold->getName()} went hungry and became malnourished.\n";
375
376 $malnourishedId = $this->getMalnourishedInjuryId($kobold);
377 if (!$malnourishedId) {
378 $kobold->addInjury('malnourished-slight');
379 $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
366 380 } else {
367 // Already malnourished - becomes more severe
368 $injuries = $kobold->getInjuries();
369 foreach ($injuries as $injury) {
370 if ($injury['category'] === 'malnourished') {
371 $injury['severity']++;
372 $story .= "{$kobold->getName()} remained hungry and suffered.\n";
373 break;
374 }
381 if ($malnourishedId === 'malnourished-slight') {
382 $kobold->removeInjury($malnourishedId);
383 $kobold->addInjury('malnourished-mild');
384 $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
385 } elseif ($malnourishedId === 'malnourished-mild') {
386 $kobold->removeInjury($malnourishedId);
387 $kobold->addInjury('malnourished-severe');
388 $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
389 } elseif ($malnourishedId === 'malnourished-severe') {
390 $kobold->removeInjury($malnourishedId);
391 $kobold->addInjury('malnourished-brink');
392 $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
393 } elseif ($malnourishedId === 'malnourished-brink') {
394 $kobold->die();
395 $story .= "{$kobold->getName()} succumbed to starvation.\n";
375 396 }
376 397 }
377 398 }
@@ -412,6 +433,20 @@ class Tribe
412 433 }
413 434 }
414 435
436 /**
437 * Get current malnourished injury id if present
438 */
439 private function getMalnourishedInjuryId(Kobold $kobold)
440 {
441 $injuries = $kobold->getInjuries();
442 foreach ($injuries as $injury) {
443 if (($injury['category'] ?? null) === 'malnourished') {
444 return $injury['id'] ?? null;
445 }
446 }
447 return null;
448 }
449
415 450 public function tryMate()
416 451 {
417 452 $kobolds = array_values($this->getKobolds());
@@ -462,7 +497,7 @@ class Tribe
462 497 [$male, $female] = $pair;
463 498
464 499 if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
465 return "{$male->getName()} and {$female->getName()} spent some of time together this month, but didn't quite hit it off.";
500 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
466 501 }
467 502
468 503 $child = Kobold::generate($this->userId, $this->saveId, -6);
@@ -611,7 +646,7 @@ class Tribe
611 646
612 647 foreach ($this->kobolds as $kobold) {
613 648 if ($kobold->isDead()) {
614 $story = $story . "\n" . $kobold->getName() . " has died.";
649 $foodStory = $foodStory . "\n" . $kobold->getName() . " has died.";
615 650 }
616 651 }
617 652
@@ -13,6 +13,7 @@ class Tribe
13 private $currentMonth = 0;
13 private $currentMonth = 0;
14 private $currentSeason = 'spring';
14 private $currentSeason = 'spring';
15 private $foodCount = 0;
15 private $foodCount = 0;
16 private $environmentId = null;
16 private $createdAt;
17 private $createdAt;
17 private $lastPlayed;
18 private $lastPlayed;
18 private $saveManager;
19 private $saveManager;
@@ -66,6 +67,7 @@ class Tribe
66 $this->currentMonth = $data['current_month'] ?? 0;
67 $this->currentMonth = $data['current_month'] ?? 0;
67 $this->currentSeason = $data['current_season'] ?? 'spring';
68 $this->currentSeason = $data['current_season'] ?? 'spring';
68 $this->foodCount = $data['food_count'] ?? 0;
69 $this->foodCount = $data['food_count'] ?? 0;
70 $this->environmentId = $data['environment_id'] ?? null;
69 $this->createdAt = $data['created_at'] ?? date('Y-m-d H:i:s');
71 $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');
72 $this->lastPlayed = $data['last_played'] ?? date('Y-m-d H:i:s');
71 }
73 }
@@ -121,6 +123,7 @@ class Tribe
121 'current_season' => $this->currentSeason,
123 'current_season' => $this->currentSeason,
122 'food_count' => $this->foodCount,
124 'food_count' => $this->foodCount,
123 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
125 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
126 'environment_id' => $this->environmentId,
124 'created_at' => $this->createdAt,
127 'created_at' => $this->createdAt,
125 'last_played' => $this->lastPlayed
128 'last_played' => $this->lastPlayed
126 ];
129 ];
@@ -195,6 +198,16 @@ class Tribe
195 $this->currentSeason = $season;
198 $this->currentSeason = $season;
196 }
199 }
197
200
201 public function getEnvironmentId()
202 {
203 return $this->environmentId;
204 }
205
206 public function setEnvironmentId($environmentId)
207 {
208 $this->environmentId = $environmentId;
209 }
210
198 // Kobold management
211 // Kobold management
199 public function getKobolds($includeDeadAndExpelled = false)
212 public function getKobolds($includeDeadAndExpelled = false)
200 {
213 {
@@ -359,19 +372,27 @@ class Tribe
359 $starvedKobolds[$kobold->getId()] = $kobold;
372 $starvedKobolds[$kobold->getId()] = $kobold;
360 $this->foodCount = 0; // Use remaining food
373 $this->foodCount = 0; // Use remaining food
361
374
362 // Add malnourished injury if not already present
375
363 if (!$this->hasInjuryCategory($kobold, 'malnourished')) {
376 $malnourishedId = $this->getMalnourishedInjuryId($kobold);
364 $kobold->addInjury('malnourished');
377 if (!$malnourishedId) {
365 $story .= "{$kobold->getName()} went hungry and became malnourished.\n";
378 $kobold->addInjury('malnourished-slight');
379 $story .= "{$kobold->getName()} went hungry and became slightly malnourished.\n";
366 } else {
380 } else {
367 // Already malnourished - becomes more severe
381 if ($malnourishedId === 'malnourished-slight') {
368 $injuries = $kobold->getInjuries();
382 $kobold->removeInjury($malnourishedId);
369 foreach ($injuries as $injury) {
383 $kobold->addInjury('malnourished-mild');
370 if ($injury['category'] === 'malnourished') {
384 $story .= "{$kobold->getName()} remained hungry and became mildly malnourished.\n";
371 $injury['severity']++;
385 } elseif ($malnourishedId === 'malnourished-mild') {
372 $story .= "{$kobold->getName()} remained hungry and suffered.\n";
386 $kobold->removeInjury($malnourishedId);
373 break;
387 $kobold->addInjury('malnourished-severe');
374 }
388 $story .= "{$kobold->getName()} remained hungry and became severely malnourished.\n";
389 } elseif ($malnourishedId === 'malnourished-severe') {
390 $kobold->removeInjury($malnourishedId);
391 $kobold->addInjury('malnourished-brink');
392 $story .= "{$kobold->getName()} is now on the brink of death from starvation.\n";
393 } elseif ($malnourishedId === 'malnourished-brink') {
394 $kobold->die();
395 $story .= "{$kobold->getName()} succumbed to starvation.\n";
375 }
396 }
376 }
397 }
377 }
398 }
@@ -412,6 +433,20 @@ class Tribe
412 }
433 }
413 }
434 }
414
435
436 /**
437 * Get current malnourished injury id if present
438 */
439 private function getMalnourishedInjuryId(Kobold $kobold)
440 {
441 $injuries = $kobold->getInjuries();
442 foreach ($injuries as $injury) {
443 if (($injury['category'] ?? null) === 'malnourished') {
444 return $injury['id'] ?? null;
445 }
446 }
447 return null;
448 }
449
415 public function tryMate()
450 public function tryMate()
416 {
451 {
417 $kobolds = array_values($this->getKobolds());
452 $kobolds = array_values($this->getKobolds());
@@ -462,7 +497,7 @@ class Tribe
462 [$male, $female] = $pair;
497 [$male, $female] = $pair;
463
498
464 if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
499 if (!$male->checkStat('personality') || !$female->checkStat('personality')) {
465 return "{$male->getName()} and {$female->getName()} spent some of time together this month, but didn't quite hit it off.";
500 return "{$male->getName()} and {$female->getName()} spent some time together this month, but didn't quite hit it off.";
466 }
501 }
467
502
468 $child = Kobold::generate($this->userId, $this->saveId, -6);
503 $child = Kobold::generate($this->userId, $this->saveId, -6);
@@ -611,7 +646,7 @@ class Tribe
611
646
612 foreach ($this->kobolds as $kobold) {
647 foreach ($this->kobolds as $kobold) {
613 if ($kobold->isDead()) {
648 if ($kobold->isDead()) {
614 $story = $story . "\n" . $kobold->getName() . " has died.";
649 $foodStory = $foodStory . "\n" . $kobold->getName() . " has died.";
615 }
650 }
616 }
651 }
617
652
web/src/api/game.php +63 −0
@@ -317,6 +317,7 @@ if ($method === 'POST') {
317 317 try {
318 318 $userId = $input['userId'] ?? null;
319 319 $saveId = $input['saveId'] ?? null;
320 $environmentId = $input['environmentId'] ?? null;
320 321
321 322 if (!$userId || !$saveId) {
322 323 throw new \Exception('User ID and Save ID required');
@@ -324,6 +325,10 @@ if ($method === 'POST') {
324 325
325 326 $tribe = Tribe::load($userId, $saveId);
326 327
328 if ($environmentId !== null) {
329 $tribe->setEnvironmentId($environmentId);
330 }
331
327 332 $leaderI = intval($input['leaderId']) ?? 0;
328 333
329 334 $keys = array_keys($tribe->kobolds);
@@ -500,6 +505,62 @@ if ($method === 'POST') {
500 505 'error' => $e->getMessage()
501 506 ]);
502 507 }
508 } elseif (strpos($apiPath, 'environments') !== false) {
509 // List available environments and metadata
510 try {
511 $basePath = __DIR__ . '/../../assets/environments';
512 if (!is_dir($basePath)) {
513 throw new \Exception('Environments directory not found');
514 }
515
516 $envs = [];
517 $dirs = array_filter(scandir($basePath), function ($dir) use ($basePath) {
518 return $dir[0] !== '.' && is_dir($basePath . '/' . $dir);
519 });
520
521 $seasons = ['spring', 'summer', 'autumn', 'winter'];
522
523 foreach ($dirs as $dir) {
524 $metaFile = $basePath . '/' . $dir . '/metadata.json';
525 $meta = [];
526 if (file_exists($metaFile)) {
527 $meta = json_decode(file_get_contents($metaFile), true) ?? [];
528 }
529
530 $images = [];
531 foreach ($seasons as $season) {
532 $imgPath = $basePath . '/' . $dir . '/' . $season . '.png';
533 if (file_exists($imgPath)) {
534 $images[] = 'assets/environments/' . $dir . '/' . $season . '.png';
535 }
536 }
537
538 if (empty($images)) {
539 foreach (glob($basePath . '/' . $dir . '/*.png') as $img) {
540 $images[] = 'assets/environments/' . $dir . '/' . basename($img);
541 }
542 }
543
544 $envs[] = [
545 'id' => $dir,
546 'name' => $meta['name'] ?? $dir,
547 'description' => $meta['description'] ?? '',
548 'koboldLocations' => $meta['koboldLocations'] ?? [],
549 'images' => $images
550 ];
551 }
552
553 echo json_encode([
554 'success' => true,
555 'environments' => $envs
556 ]);
557 } catch (\Exception $e) {
558 http_response_code(400);
559 echo json_encode([
560 'success' => false,
561 'error' => $e->getMessage()
562 ]);
563 }
503 564 } elseif (strpos($apiPath, 'list') !== false) {
504 565 // List saves for user
505 566 try {
@@ -566,6 +627,7 @@ if ($method === 'POST') {
566 627 'fatigue_label' => $kobold->getFatigueLabel(),
567 628 'items' => $kobold->getItems() ?? [],
568 629 'injuries' => $kInjuries,
630 'is_leader' => $kobold->isLeader(),
569 631 'male' => $kobold->getMale()
570 632 ];
571 633 }
@@ -580,6 +642,7 @@ if ($method === 'POST') {
580 642 'name' => $tribe->getName(),
581 643 'current_month' => $tribe->getCurrentMonth(),
582 644 'current_season' => $tribe->getCurrentSeason(),
645 'environment_id' => $tribe->getEnvironmentId(),
583 646 'food_count' => $tribe->getFoodCount(),
584 647 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
585 648 'created_at' => $tribe->getCreatedAt(),
@@ -317,6 +317,7 @@ if ($method === 'POST') {
317 try {
317 try {
318 $userId = $input['userId'] ?? null;
318 $userId = $input['userId'] ?? null;
319 $saveId = $input['saveId'] ?? null;
319 $saveId = $input['saveId'] ?? null;
320 $environmentId = $input['environmentId'] ?? null;
320
321
321 if (!$userId || !$saveId) {
322 if (!$userId || !$saveId) {
322 throw new \Exception('User ID and Save ID required');
323 throw new \Exception('User ID and Save ID required');
@@ -324,6 +325,10 @@ if ($method === 'POST') {
324
325
325 $tribe = Tribe::load($userId, $saveId);
326 $tribe = Tribe::load($userId, $saveId);
326
327
328 if ($environmentId !== null) {
329 $tribe->setEnvironmentId($environmentId);
330 }
331
327 $leaderI = intval($input['leaderId']) ?? 0;
332 $leaderI = intval($input['leaderId']) ?? 0;
328
333
329 $keys = array_keys($tribe->kobolds);
334 $keys = array_keys($tribe->kobolds);
@@ -500,6 +505,62 @@ if ($method === 'POST') {
500 'error' => $e->getMessage()
505 'error' => $e->getMessage()
501 ]);
506 ]);
502 }
507 }
508 } elseif (strpos($apiPath, 'environments') !== false) {
509 // List available environments and metadata
510 try {
511 $basePath = __DIR__ . '/../../assets/environments';
512 if (!is_dir($basePath)) {
513 throw new \Exception('Environments directory not found');
514 }
515
516 $envs = [];
517 $dirs = array_filter(scandir($basePath), function ($dir) use ($basePath) {
518 return $dir[0] !== '.' && is_dir($basePath . '/' . $dir);
519 });
520
521 $seasons = ['spring', 'summer', 'autumn', 'winter'];
522
523 foreach ($dirs as $dir) {
524 $metaFile = $basePath . '/' . $dir . '/metadata.json';
525 $meta = [];
526 if (file_exists($metaFile)) {
527 $meta = json_decode(file_get_contents($metaFile), true) ?? [];
528 }
529
530 $images = [];
531 foreach ($seasons as $season) {
532 $imgPath = $basePath . '/' . $dir . '/' . $season . '.png';
533 if (file_exists($imgPath)) {
534 $images[] = 'assets/environments/' . $dir . '/' . $season . '.png';
535 }
536 }
537
538 if (empty($images)) {
539 foreach (glob($basePath . '/' . $dir . '/*.png') as $img) {
540 $images[] = 'assets/environments/' . $dir . '/' . basename($img);
541 }
542 }
543
544 $envs[] = [
545 'id' => $dir,
546 'name' => $meta['name'] ?? $dir,
547 'description' => $meta['description'] ?? '',
548 'koboldLocations' => $meta['koboldLocations'] ?? [],
549 'images' => $images
550 ];
551 }
552
553 echo json_encode([
554 'success' => true,
555 'environments' => $envs
556 ]);
557 } catch (\Exception $e) {
558 http_response_code(400);
559 echo json_encode([
560 'success' => false,
561 'error' => $e->getMessage()
562 ]);
563 }
503 } elseif (strpos($apiPath, 'list') !== false) {
564 } elseif (strpos($apiPath, 'list') !== false) {
504 // List saves for user
565 // List saves for user
505 try {
566 try {
@@ -566,6 +627,7 @@ if ($method === 'POST') {
566 'fatigue_label' => $kobold->getFatigueLabel(),
627 'fatigue_label' => $kobold->getFatigueLabel(),
567 'items' => $kobold->getItems() ?? [],
628 'items' => $kobold->getItems() ?? [],
568 'injuries' => $kInjuries,
629 'injuries' => $kInjuries,
630 'is_leader' => $kobold->isLeader(),
569 'male' => $kobold->getMale()
631 'male' => $kobold->getMale()
570 ];
632 ];
571 }
633 }
@@ -580,6 +642,7 @@ if ($method === 'POST') {
580 'name' => $tribe->getName(),
642 'name' => $tribe->getName(),
581 'current_month' => $tribe->getCurrentMonth(),
643 'current_month' => $tribe->getCurrentMonth(),
582 'current_season' => $tribe->getCurrentSeason(),
644 'current_season' => $tribe->getCurrentSeason(),
645 'environment_id' => $tribe->getEnvironmentId(),
583 'food_count' => $tribe->getFoodCount(),
646 'food_count' => $tribe->getFoodCount(),
584 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
647 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
585 'created_at' => $tribe->getCreatedAt(),
648 'created_at' => $tribe->getCreatedAt(),