BlueGit

blue-star tribegen

farming

timfa Tim · pushed by timfa

Authored 2026-01-29 · 9 months ago

Hash
569cc9749308b1f5167252da121008c71a3a4a5f
Parent
80fa6e6e
35 files changed +459 −85
web/.github/copilot-instructions.md +2 −2
@@ -15,7 +15,7 @@
15 15
16 16 ### Core Entity Classes
17 17 1. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
18 2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, tinkering, medicine, crafting, personality, will), injuries, items, genetic lineage
18 2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage
19 19 3. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
20 20 4. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
21 21 5. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
@@ -108,7 +108,7 @@ All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `save
108 108
109 109 ### Core Entity Classes
110 110 1. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
111 2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, tinkering, medicine, crafting, personality, will), injuries, items, genetic lineage
111 2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage
112 112 3. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
113 113 4. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
114 114 5. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
@@ -15,7 +15,7 @@
15
15
16### Core Entity Classes
16### Core Entity Classes
171. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
171. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
182. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, tinkering, medicine, crafting, personality, will), injuries, items, genetic lineage
182. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage
193. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
193. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
204. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
204. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
215. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
215. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
@@ -108,7 +108,7 @@ All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `save
108
108
109### Core Entity Classes
109### Core Entity Classes
1101. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
1101. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
1112. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, tinkering, medicine, crafting, personality, will), injuries, items, genetic lineage
1112. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage
1123. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
1123. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
1134. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
1134. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
1145. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
1145. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
web/README.md +1 −1
@@ -50,7 +50,7 @@ tribegen/
50 50 - Per-user save files
51 51
52 52 ### Kobold System
53 - Random stat generation (7 stats: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will)
53 - Random stat generation (7 stats: Vitality, Intelligence, Fighting, Medicine, Crafting, Personality, Will)
54 54 - Age-based stat scaling and sprite progression
55 55 - Genetic inheritance (up to 3 levels: kobold, parents, grandparents)
56 56 - Injuries with severity system
@@ -50,7 +50,7 @@ tribegen/
50- Per-user save files
50- Per-user save files
51
51
52### Kobold System
52### Kobold System
53- Random stat generation (7 stats: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will)
53- Random stat generation (7 stats: Vitality, Intelligence, Fighting, Medicine, Crafting, Personality, Will)
54- Age-based stat scaling and sprite progression
54- Age-based stat scaling and sprite progression
55- Genetic inheritance (up to 3 levels: kobold, parents, grandparents)
55- Genetic inheritance (up to 3 levels: kobold, parents, grandparents)
56- Injuries with severity system
56- Injuries with severity system
web/assets/injuries/bad_back.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": -4,
8 8 "intelligence": 0,
9 "tinkering": -1,
10 9 "medicine": 0,
11 10 "crafting": -1,
12 11 "personality": -1,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": -4,
7 "vitality": -4,
8 "intelligence": 0,
8 "intelligence": 0,
9 "tinkering": -1,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": -1,
10 "crafting": -1,
12 "personality": -1,
11 "personality": -1,
web/assets/injuries/bad_liver.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": -5,
8 8 "intelligence": -1,
9 "tinkering": 0,
10 9 "medicine": 0,
11 10 "crafting": 0,
12 11 "personality": -1,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": -5,
7 "vitality": -5,
8 "intelligence": -1,
8 "intelligence": -1,
9 "tinkering": 0,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": 0,
10 "crafting": 0,
12 "personality": -1,
11 "personality": -1,
web/assets/injuries/brokenLeg.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": -4,
8 8 "intelligence": 0,
9 "tinkering": -2,
10 9 "medicine": 0,
11 10 "crafting": -3,
12 11 "personality": -1,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": -4,
7 "vitality": -4,
8 "intelligence": 0,
8 "intelligence": 0,
9 "tinkering": -2,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": -3,
10 "crafting": -3,
12 "personality": -1,
11 "personality": -1,
web/assets/injuries/chronic_fatigue.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": -4,
8 8 "intelligence": 0,
9 "tinkering": -2,
10 9 "medicine": 0,
11 10 "crafting": -2,
12 11 "personality": -1,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": -4,
7 "vitality": -4,
8 "intelligence": 0,
8 "intelligence": 0,
9 "tinkering": -2,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": -2,
10 "crafting": -2,
12 "personality": -1,
11 "personality": -1,
web/assets/injuries/dementia.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": 0,
8 8 "intelligence": -4,
9 "tinkering": -2,
10 9 "medicine": -2,
11 10 "crafting": -2,
12 11 "personality": -2,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": 0,
7 "vitality": 0,
8 "intelligence": -4,
8 "intelligence": -4,
9 "tinkering": -2,
10 "medicine": -2,
9 "medicine": -2,
11 "crafting": -2,
10 "crafting": -2,
12 "personality": -2,
11 "personality": -2,
web/assets/injuries/limp.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": -2,
8 8 "intelligence": 0,
9 "tinkering": 0,
10 9 "medicine": 0,
11 10 "crafting": 0,
12 11 "personality": 0,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": -2,
7 "vitality": -2,
8 "intelligence": 0,
8 "intelligence": 0,
9 "tinkering": 0,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": 0,
10 "crafting": 0,
12 "personality": 0,
11 "personality": 0,
web/assets/injuries/poor_eyesight.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": 0,
8 8 "intelligence": 0,
9 "tinkering": -2,
10 9 "medicine": 0,
11 10 "crafting": -2,
12 11 "personality": -2,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": 0,
7 "vitality": 0,
8 "intelligence": 0,
8 "intelligence": 0,
9 "tinkering": -2,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": -2,
10 "crafting": -2,
12 "personality": -2,
11 "personality": -2,
web/assets/injuries/poor_hearing.json +0 −1
@@ -6,7 +6,6 @@
6 6 "statModifications": {
7 7 "vitality": 0,
8 8 "intelligence": -1,
9 "tinkering": 0,
10 9 "medicine": 0,
11 10 "crafting": 0,
12 11 "personality": -3,
@@ -6,7 +6,6 @@
6 "statModifications": {
6 "statModifications": {
7 "vitality": 0,
7 "vitality": 0,
8 "intelligence": -1,
8 "intelligence": -1,
9 "tinkering": 0,
10 "medicine": 0,
9 "medicine": 0,
11 "crafting": 0,
10 "crafting": 0,
12 "personality": -3,
11 "personality": -3,
web/assets/injuries/smallCut.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Cut",
3 "description": "A small cut that causes minor bleeding and discomfort.",
4 "category": "cut",
5 "severity": 1,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -3,
11 "personality": -1,
12 "will": -2,
13 "fighting": -5
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Cut",
3 "description": "A small cut that causes minor bleeding and discomfort.",
4 "category": "cut",
5 "severity": 1,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "medicine": 0,
10 "crafting": -3,
11 "personality": -1,
12 "will": -2,
13 "fighting": -5
14 }
15}
web/assets/items/bone-setting.json +0 −1
@@ -5,7 +5,6 @@
5 5 "statModifications": {
6 6 "vitality": 0,
7 7 "intelligence": 0,
8 "tinkering": 0,
9 8 "medicine": 1,
10 9 "crafting": 0,
11 10 "personality": 0,
@@ -5,7 +5,6 @@
5 "statModifications": {
5 "statModifications": {
6 "vitality": 0,
6 "vitality": 0,
7 "intelligence": 0,
7 "intelligence": 0,
8 "tinkering": 0,
9 "medicine": 1,
8 "medicine": 1,
10 "crafting": 0,
9 "crafting": 0,
11 "personality": 0,
10 "personality": 0,
web/assets/items/book.json +0 −1
@@ -6,7 +6,6 @@
6 6 {
7 7 "vitality": 0,
8 8 "intelligence": 3,
9 "tinkering": 0,
10 9 "medicine": 2,
11 10 "crafting": 0,
12 11 "personality": -1,
@@ -6,7 +6,6 @@
6 {
6 {
7 "vitality": 0,
7 "vitality": 0,
8 "intelligence": 3,
8 "intelligence": 3,
9 "tinkering": 0,
10 "medicine": 2,
9 "medicine": 2,
11 "crafting": 0,
10 "crafting": 0,
12 "personality": -1,
11 "personality": -1,
web/assets/items/healing-herbs.json added +13 −0
@@ -0,0 +1,13 @@
1 {
2 "name": "Healing Herbs",
3 "description": "Special medicinal herbs that can help heal infections.",
4 "itemType": "medicine",
5 "statModifications": {
6 "vitality": 0,
7 "intelligence": 0,
8 "medicine": 3,
9 "crafting": 0,
10 "personality": 0,
11 "will": 0
12 }
13 }
@@ -0,0 +1,13 @@
1{
2 "name": "Healing Herbs",
3 "description": "Special medicinal herbs that can help heal infections.",
4 "itemType": "medicine",
5 "statModifications": {
6 "vitality": 0,
7 "intelligence": 0,
8 "medicine": 3,
9 "crafting": 0,
10 "personality": 0,
11 "will": 0
12 }
13}
web/css/style.css +2 −0
@@ -401,6 +401,7 @@ button {
401 401 border-radius: 5px;
402 402 padding: 15px;
403 403 overflow-y: auto;
404 min-height: 150px;
404 405 }
405 406
406 407 .panel h3 {
@@ -528,6 +529,7 @@ button {
528 529 gap: 8px;
529 530 max-height: 200px;
530 531 overflow-y: auto;
532 overflow-x: hidden;
531 533 }
532 534
533 535 .storage-item {
@@ -401,6 +401,7 @@ button {
401 border-radius: 5px;
401 border-radius: 5px;
402 padding: 15px;
402 padding: 15px;
403 overflow-y: auto;
403 overflow-y: auto;
404 min-height: 150px;
404}
405}
405
406
406.panel h3 {
407.panel h3 {
@@ -528,6 +529,7 @@ button {
528 gap: 8px;
529 gap: 8px;
529 max-height: 200px;
530 max-height: 200px;
530 overflow-y: auto;
531 overflow-y: auto;
532 overflow-x: hidden;
531}
533}
532
534
533.storage-item {
535.storage-item {
web/docs/API_REFERENCE.md +0 −2
@@ -108,7 +108,6 @@ Generate initial tribe setup (20 random kobolds).
108 108 "stats": {
109 109 "vitality": 45,
110 110 "intelligence": 52,
111 "tinkering": 38,
112 111 "medicine": 42,
113 112 "crafting": 61,
114 113 "personality": 48,
@@ -346,7 +345,6 @@ All stats are 0-100 internally but displayed as:
346 345 'stats' => [
347 346 'vitality' => int (0-100),
348 347 'intelligence' => int (0-100),
349 'tinkering' => int (0-100),
350 348 'medicine' => int (0-100),
351 349 'crafting' => int (0-100),
352 350 'personality' => int (0-100),
@@ -108,7 +108,6 @@ Generate initial tribe setup (20 random kobolds).
108 "stats": {
108 "stats": {
109 "vitality": 45,
109 "vitality": 45,
110 "intelligence": 52,
110 "intelligence": 52,
111 "tinkering": 38,
112 "medicine": 42,
111 "medicine": 42,
113 "crafting": 61,
112 "crafting": 61,
114 "personality": 48,
113 "personality": 48,
@@ -346,7 +345,6 @@ All stats are 0-100 internally but displayed as:
346 'stats' => [
345 'stats' => [
347 'vitality' => int (0-100),
346 'vitality' => int (0-100),
348 'intelligence' => int (0-100),
347 'intelligence' => int (0-100),
349 'tinkering' => int (0-100),
350 'medicine' => int (0-100),
348 'medicine' => int (0-100),
351 'crafting' => int (0-100),
349 'crafting' => int (0-100),
352 'personality' => int (0-100),
350 'personality' => int (0-100),
web/docs/ARCHITECTURE.md +1 −1
@@ -22,7 +22,7 @@
22 22 - `save_id` (FK)
23 23 - `name`
24 24 - `age`
25 - `vitality`, `intelligence`, `tinkering`, `medicine`, `crafting`, `personality`, `will`
25 - `vitality`, `intelligence`, `medicine`, `crafting`, `personality`, `will`
26 26 - `sprite_morph`
27 27 - `is_leader`
28 28 - `is_alive`
@@ -22,7 +22,7 @@
22- `save_id` (FK)
22- `save_id` (FK)
23- `name`
23- `name`
24- `age`
24- `age`
25- `vitality`, `intelligence`, `tinkering`, `medicine`, `crafting`, `personality`, `will`
25- `vitality`, `intelligence`, `medicine`, `crafting`, `personality`, `will`
26- `sprite_morph`
26- `sprite_morph`
27- `is_leader`
27- `is_leader`
28- `is_alive`
28- `is_alive`
web/docs/DESIGN.md +3 −3
@@ -57,7 +57,7 @@ tribegen/
57 57 - Per-user save files
58 58
59 59 ### 2. Kobold System ✓
60 - 7 base stats (expandable): Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
60 - 7 base stats (expandable): Vitality, Intelligence, Medicine, Crafting, Personality, Will
61 61 - Random stat generation (0-100)
62 62 - Age system (egg → baby → adult → old → very old)
63 63 - Age-based stat scaling (babies have reduced effective stats)
@@ -172,12 +172,12 @@ class MyEvent extends Event {
172 172 $this->story = "Opening narrative...\n\n";
173 173
174 174 foreach ($this->tribe->getAliveKobolds() as $kobold) {
175 if ($kobold->checkStat('tinkering')) {
175 if ($kobold->checkStat('crafting')) {
176 176 // Success
177 177 $this->story .= "{$kobold->getName()} succeeded!\n";
178 178 } else {
179 179 // Failure
180 $kobold->addInjury('wound', 'wound', 1);
180 $kobold->addInjury('wound-id');
181 181 $this->story .= "{$kobold->getName()} was injured!\n";
182 182 }
183 183 }
@@ -57,7 +57,7 @@ tribegen/
57- Per-user save files
57- Per-user save files
58
58
59### 2. Kobold System ✓
59### 2. Kobold System ✓
60- 7 base stats (expandable): Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
60- 7 base stats (expandable): Vitality, Intelligence, Medicine, Crafting, Personality, Will
61- Random stat generation (0-100)
61- Random stat generation (0-100)
62- Age system (egg → baby → adult → old → very old)
62- Age system (egg → baby → adult → old → very old)
63- Age-based stat scaling (babies have reduced effective stats)
63- Age-based stat scaling (babies have reduced effective stats)
@@ -172,12 +172,12 @@ class MyEvent extends Event {
172 $this->story = "Opening narrative...\n\n";
172 $this->story = "Opening narrative...\n\n";
173
173
174 foreach ($this->tribe->getAliveKobolds() as $kobold) {
174 foreach ($this->tribe->getAliveKobolds() as $kobold) {
175 if ($kobold->checkStat('tinkering')) {
175 if ($kobold->checkStat('crafting')) {
176 // Success
176 // Success
177 $this->story .= "{$kobold->getName()} succeeded!\n";
177 $this->story .= "{$kobold->getName()} succeeded!\n";
178 } else {
178 } else {
179 // Failure
179 // Failure
180 $kobold->addInjury('wound', 'wound', 1);
180 $kobold->addInjury('wound-id');
181 $this->story .= "{$kobold->getName()} was injured!\n";
181 $this->story .= "{$kobold->getName()} was injured!\n";
182 }
182 }
183 }
183 }
web/docs/FOOD_SYSTEM.md +1 −1
@@ -178,7 +178,7 @@ class HuntingEvent extends Event {
178 178
179 179 $success = 0;
180 180 foreach ($this->tribe->getAliveKobolds() as $kobold) {
181 if ($kobold->checkStat('tinkering')) { // Actually hunting skill
181 if ($kobold->checkStat('fighting')) { // Actually hunting skill
182 182 $success++;
183 183 }
184 184 }
@@ -178,7 +178,7 @@ class HuntingEvent extends Event {
178
178
179 $success = 0;
179 $success = 0;
180 foreach ($this->tribe->getAliveKobolds() as $kobold) {
180 foreach ($this->tribe->getAliveKobolds() as $kobold) {
181 if ($kobold->checkStat('tinkering')) { // Actually hunting skill
181 if ($kobold->checkStat('fighting')) { // Actually hunting skill
182 $success++;
182 $success++;
183 }
183 }
184 }
184 }
web/docs/INDEX.md +1 −1
@@ -136,7 +136,7 @@ Welcome to TribeGen! Here's what to read based on your needs.
136 136 ## Key Concepts
137 137
138 138 ### Stat System
139 - 7 stats: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
139 - 7 stats: Vitality, Intelligence, Medicine, Crafting, Personality, Will
140 140 - Range: 0-100
141 141 - Display: Text (terrible → godlike)
142 142 - Scaling: Babies have reduced effective stats
@@ -136,7 +136,7 @@ Welcome to TribeGen! Here's what to read based on your needs.
136## Key Concepts
136## Key Concepts
137
137
138### Stat System
138### Stat System
139- 7 stats: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
139- 7 stats: Vitality, Intelligence, Medicine, Crafting, Personality, Will
140- Range: 0-100
140- Range: 0-100
141- Display: Text (terrible → godlike)
141- Display: Text (terrible → godlike)
142- Scaling: Babies have reduced effective stats
142- Scaling: Babies have reduced effective stats
web/docs/PROJECT_SUMMARY.md +1 −1
@@ -96,7 +96,7 @@ tribegen/
96 96 - Per-user save files
97 97
98 98 ### ✅ Kobold System (Complete)
99 - **7 Stats**: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
99 - **7 Stats**: Vitality, Intelligence, Medicine, Crafting, Personality, Will
100 100 - **Random Generation**: 0-100 range
101 101 - **Age System**: Egg → Baby → Adult → Old → Very Old
102 102 - **Age Scaling**: Babies have reduced effective stats
@@ -96,7 +96,7 @@ tribegen/
96- Per-user save files
96- Per-user save files
97
97
98### ✅ Kobold System (Complete)
98### ✅ Kobold System (Complete)
99- **7 Stats**: Vitality, Intelligence, Tinkering, Medicine, Crafting, Personality, Will
99- **7 Stats**: Vitality, Intelligence, Medicine, Crafting, Personality, Will
100- **Random Generation**: 0-100 range
100- **Random Generation**: 0-100 range
101- **Age System**: Egg → Baby → Adult → Old → Very Old
101- **Age System**: Egg → Baby → Adult → Old → Very Old
102- **Age Scaling**: Babies have reduced effective stats
102- **Age Scaling**: Babies have reduced effective stats
web/docs/QUICKSTART.md +1 −1
@@ -29,7 +29,7 @@ Configure your web server to serve the `public/` directory as the document root.
29 29 ### Kobold Stats
30 30 - **Vitality**: Health and resistance to injury/disease
31 31 - **Intelligence**: Problem-solving and learning
32 - **Tinkering**: Crafting and repair ability
32 - **Fighting**: Combat and hunting
33 33 - **Medicine**: Healing and medical knowledge
34 34 - **Crafting**: Creation of items and goods
35 35 - **Personality**: Social interactions and morale
@@ -29,7 +29,7 @@ Configure your web server to serve the `public/` directory as the document root.
29### Kobold Stats
29### Kobold Stats
30- **Vitality**: Health and resistance to injury/disease
30- **Vitality**: Health and resistance to injury/disease
31- **Intelligence**: Problem-solving and learning
31- **Intelligence**: Problem-solving and learning
32- **Tinkering**: Crafting and repair ability
32- **Fighting**: Combat and hunting
33- **Medicine**: Healing and medical knowledge
33- **Medicine**: Healing and medical knowledge
34- **Crafting**: Creation of items and goods
34- **Crafting**: Creation of items and goods
35- **Personality**: Social interactions and morale
35- **Personality**: Social interactions and morale
web/docs/REFACTORING_COMPLETE.md +0 −1
@@ -314,7 +314,6 @@ Injury ─┘ ├──► [JSON Files]
314 314 "stats": {
315 315 "vitality": 75,
316 316 "intelligence": 60,
317 "tinkering": 45,
318 317 "medicine": 50,
319 318 "crafting": 65,
320 319 "personality": 70,
@@ -314,7 +314,6 @@ Injury ─┘ ├──► [JSON Files]
314 "stats": {
314 "stats": {
315 "vitality": 75,
315 "vitality": 75,
316 "intelligence": 60,
316 "intelligence": 60,
317 "tinkering": 45,
318 "medicine": 50,
317 "medicine": 50,
319 "crafting": 65,
318 "crafting": 65,
320 "personality": 70,
319 "personality": 70,
web/index.php +2 −0
@@ -37,6 +37,8 @@ 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/events') {
41 include __DIR__ . '/src/api/game.php';
40 42 } elseif ($apiPath === 'game/sprite') {
41 43 include __DIR__ . '/src/api/game.php';
42 44 } elseif ($apiPath === 'game/list') {
@@ -37,6 +37,8 @@ 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/events') {
41 include __DIR__ . '/src/api/game.php';
40 } elseif ($apiPath === 'game/sprite') {
42 } elseif ($apiPath === 'game/sprite') {
41 include __DIR__ . '/src/api/game.php';
43 include __DIR__ . '/src/api/game.php';
42 } elseif ($apiPath === 'game/list') {
44 } elseif ($apiPath === 'game/list') {
web/js/app.js +101 −25
@@ -2,11 +2,13 @@ var doneTyping = true;
2 2 // Main Game App
3 3 class TribeGenApp
4 4 {
5 constructor()
5 constructor ()
6 6 {
7 7 this.currentUser = null;
8 8 this.currentSave = null;
9 9 this.currentTribe = null;
10 this.availableEvents = [];
11 this.availableEventsByType = {};
10 12 this.init();
11 13 }
12 14
@@ -188,7 +190,7 @@ class TribeGenApp
188 190 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
189 191 });
190 192
191 const dataText = await response.text()
193 const dataText = await response.text();
192 194 const data = JSON.parse(dataText);
193 195
194 196 const savesList = document.getElementById('savesList');
@@ -391,7 +393,7 @@ class TribeGenApp
391 393 })
392 394 });
393 395
394 const dataText = await response.text()
396 const dataText = await response.text();
395 397 const data = JSON.parse(dataText);
396 398
397 399 if (data.success)
@@ -414,13 +416,14 @@ class TribeGenApp
414 416 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
415 417 });
416 418
417 const dataText = await response.text()
419 const dataText = await response.text();
418 420 const data = JSON.parse(dataText);
419 421
420 422 if (data.success)
421 423 {
422 424 this.currentSave = data.save;
423 425 this.currentTribe = data.tribe;
426 await this.fetchAvailableEvents();
424 427 this.showGameScreen();
425 428 }
426 429 } catch (error)
@@ -482,18 +485,63 @@ class TribeGenApp
482 485 const list = document.getElementById('eventsList');
483 486 list.innerHTML = '';
484 487
485 const events = ['Hunting', 'Exploration', 'Farming'];
488 if (!this.availableEvents || this.availableEvents.length === 0)
489 {
490 const empty = document.createElement('div');
491 empty.className = 'event-item disabled';
492 empty.textContent = 'No events available';
493 list.appendChild(empty);
494 return;
495 }
486 496
487 events.forEach(evt =>
497 this.availableEvents.forEach(evt =>
488 498 {
489 499 const item = document.createElement('div');
490 item.className = 'event-item';
491 item.textContent = evt;
492 item.addEventListener('click', () => this.showParticipantModal(evt));
500 const isAvailable = !!evt.available;
501 item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim();
502 const costText = Number.isFinite(Number(evt.cost)) ? ` (Cost: ${evt.cost})` : '';
503 item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`;
504 if (isAvailable)
505 {
506 item.addEventListener('click', () => this.showParticipantModal(evt.type));
507 }
493 508 list.appendChild(item);
494 509 });
495 510 }
496 511
512 async fetchAvailableEvents ()
513 {
514 this.availableEvents = [];
515 this.availableEventsByType = {};
516
517 if (!this.currentUser || !this.currentSave)
518 return;
519
520 try
521 {
522 const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.id}`, {
523 method: 'GET',
524 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
525 });
526
527 const dataText = await response.text();
528 const data = JSON.parse(dataText);
529
530 if (data.success && Array.isArray(data.events))
531 {
532 this.availableEvents = data.events;
533 data.events.forEach(evt =>
534 {
535 if (evt && evt.type)
536 this.availableEventsByType[evt.type] = evt;
537 });
538 }
539 } catch (error)
540 {
541 console.error('Failed to load events:', error);
542 }
543 }
544
497 545 async executeEvent (eventType)
498 546 {
499 547 // Deprecated direct execution; use participant modal instead
@@ -504,21 +552,17 @@ class TribeGenApp
504 552 {
505 553 this.currentEventType = eventType;
506 554 const modal = document.getElementById('participantModal');
507 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventType}`;
555 const eventData = this.availableEventsByType[eventType] || {};
556 const eventLabel = eventData.name || eventType;
557 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`;
508 558
509 559 const list = document.getElementById('participantsList');
510 560 list.innerHTML = '';
511 561
512 // Default limits and minimum age (server also enforces). Adjust per event if needed.
513 const eventConfig = {
514 'Exploration': { min: 1, max: 3, minAge: 0 },
515 'Hunting': { min: 1, max: 3, minAge: 0 },
516 'Farming': { min: 1, max: 3, minAge: 0 }
517 };
518 const config = eventConfig[eventType] || { min: 1, max: 3, minAge: 0 };
519 this.participantMin = config.min;
520 this.participantMax = config.max;
521 this.participantMinAge = config.minAge;
562 this.participantMin = eventData.min_participants ?? 1;
563 this.participantMax = eventData.max_participants ?? 3;
564 this.participantMinAge = eventData.min_age ?? 0;
565 this.participantCost = eventData.cost || 0;
522 566
523 567 // Helper: check if kobold is eligible
524 568 const isEligible = (kobold) =>
@@ -527,6 +571,9 @@ class TribeGenApp
527 571 if (ageCategory === 'egg') return false; // eggs cannot participate
528 572 if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend)
529 573 if (kobold.age < this.participantMinAge) return false; // too young
574 const fatigue = Number(kobold.fatigue || 0);
575 const vitality = Number(kobold.stats?.vitality || 0);
576 if ((fatigue + this.participantCost) > vitality) return false;
530 577 return true;
531 578 };
532 579
@@ -541,6 +588,10 @@ class TribeGenApp
541 588 reason = '(eggs cannot participate)';
542 589 else if (kobold.age < this.participantMinAge)
543 590 reason = `(too young, needs age ${this.participantMinAge}+)`;
591 else if (this.participantCost > Number(kobold.stats?.vitality || 0))
592 reason = '(too weak)';
593 else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0))
594 reason = '(too tired)';
544 595
545 596 const row = document.createElement('div');
546 597 row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`;
@@ -616,7 +667,7 @@ class TribeGenApp
616 667 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected })
617 668 });
618 669
619 const dataText = await resp.text()
670 const dataText = await resp.text();
620 671 const data = JSON.parse(dataText);
621 672
622 673 if (data.success)
@@ -659,6 +710,7 @@ class TribeGenApp
659 710 this.currentSave = data.save;
660 711 typeText(document.getElementById('eventStory'), data.monthStory);
661 712 this.showEventModal();
713 await this.loadGame(this.currentSave.id);
662 714 }
663 715 } catch (error)
664 716 {
@@ -776,7 +828,7 @@ class TribeGenApp
776 828 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
777 829 });
778 830
779 const dataText = await resp.text()
831 const dataText = await resp.text();
780 832 const data = JSON.parse(dataText);
781 833 if (data.success)
782 834 {
@@ -855,7 +907,7 @@ class TribeGenApp
855 907 const statsGrid = document.getElementById('koboldStats');
856 908 statsGrid.innerHTML = '';
857 909
858 const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
910 const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
859 911 stats.forEach(stat =>
860 912 {
861 913 const value = kobold.stats[stat];
@@ -868,6 +920,17 @@ class TribeGenApp
868 920 `;
869 921 statsGrid.appendChild(statEl);
870 922 });
923
924 const fatigueValue = Number(kobold.fatigue || 0);
925 const vitalityValue = Number(kobold.stats?.vitality || 0);
926 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
927 const fatigueEl = document.createElement('div');
928 fatigueEl.className = 'stat-item';
929 fatigueEl.innerHTML = `
930 <div class="stat-name">energy</div>
931 <div class="stat-value">${fatigueLabel}</div>
932 `;
933 statsGrid.appendChild(fatigueEl);
871 934 }
872 935
873 936 renderKoboldInventory (kobold)
@@ -957,7 +1020,7 @@ class TribeGenApp
957 1020 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
958 1021 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
959 1022 });
960 const dataText = await resp.text()
1023 const dataText = await resp.text();
961 1024 const data = JSON.parse(dataText);
962 1025 if (data.success)
963 1026 {
@@ -1047,7 +1110,7 @@ class TribeGenApp
1047 1110 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
1048 1111 });
1049 1112
1050 const dataText = await resp.text()
1113 const dataText = await resp.text();
1051 1114 const data = JSON.parse(dataText);
1052 1115 if (data.success)
1053 1116 {
@@ -1096,6 +1159,19 @@ class TribeGenApp
1096 1159 return 'terrible';
1097 1160 }
1098 1161
1162 getFatigueLabel (fatigue, vitality)
1163 {
1164 const vit = Number(vitality || 0);
1165 const fat = Number(fatigue || 0);
1166 if (vit <= 0) return 'exhausted';
1167 if (fat <= 0) return 'energetic';
1168 const ratio = fat / Math.max(1, vit);
1169 if (ratio < 0.3) return 'fresh';
1170 if (ratio < 0.6) return 'tired';
1171 if (ratio < 0.85) return 'weary';
1172 return 'exhausted';
1173 }
1174
1099 1175 hideAll ()
1100 1176 {
1101 1177 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
@@ -2,11 +2,13 @@ var doneTyping = true;
2// Main Game App
2// Main Game App
3class TribeGenApp
3class TribeGenApp
4{
4{
5 constructor()
5 constructor ()
6 {
6 {
7 this.currentUser = null;
7 this.currentUser = null;
8 this.currentSave = null;
8 this.currentSave = null;
9 this.currentTribe = null;
9 this.currentTribe = null;
10 this.availableEvents = [];
11 this.availableEventsByType = {};
10 this.init();
12 this.init();
11 }
13 }
12
14
@@ -188,7 +190,7 @@ class TribeGenApp
188 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
190 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
189 });
191 });
190
192
191 const dataText = await response.text()
193 const dataText = await response.text();
192 const data = JSON.parse(dataText);
194 const data = JSON.parse(dataText);
193
195
194 const savesList = document.getElementById('savesList');
196 const savesList = document.getElementById('savesList');
@@ -391,7 +393,7 @@ class TribeGenApp
391 })
393 })
392 });
394 });
393
395
394 const dataText = await response.text()
396 const dataText = await response.text();
395 const data = JSON.parse(dataText);
397 const data = JSON.parse(dataText);
396
398
397 if (data.success)
399 if (data.success)
@@ -414,13 +416,14 @@ class TribeGenApp
414 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
416 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
415 });
417 });
416
418
417 const dataText = await response.text()
419 const dataText = await response.text();
418 const data = JSON.parse(dataText);
420 const data = JSON.parse(dataText);
419
421
420 if (data.success)
422 if (data.success)
421 {
423 {
422 this.currentSave = data.save;
424 this.currentSave = data.save;
423 this.currentTribe = data.tribe;
425 this.currentTribe = data.tribe;
426 await this.fetchAvailableEvents();
424 this.showGameScreen();
427 this.showGameScreen();
425 }
428 }
426 } catch (error)
429 } catch (error)
@@ -482,18 +485,63 @@ class TribeGenApp
482 const list = document.getElementById('eventsList');
485 const list = document.getElementById('eventsList');
483 list.innerHTML = '';
486 list.innerHTML = '';
484
487
485 const events = ['Hunting', 'Exploration', 'Farming'];
488 if (!this.availableEvents || this.availableEvents.length === 0)
489 {
490 const empty = document.createElement('div');
491 empty.className = 'event-item disabled';
492 empty.textContent = 'No events available';
493 list.appendChild(empty);
494 return;
495 }
486
496
487 events.forEach(evt =>
497 this.availableEvents.forEach(evt =>
488 {
498 {
489 const item = document.createElement('div');
499 const item = document.createElement('div');
490 item.className = 'event-item';
500 const isAvailable = !!evt.available;
491 item.textContent = evt;
501 item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim();
492 item.addEventListener('click', () => this.showParticipantModal(evt));
502 const costText = Number.isFinite(Number(evt.cost)) ? ` (Cost: ${evt.cost})` : '';
503 item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`;
504 if (isAvailable)
505 {
506 item.addEventListener('click', () => this.showParticipantModal(evt.type));
507 }
493 list.appendChild(item);
508 list.appendChild(item);
494 });
509 });
495 }
510 }
496
511
512 async fetchAvailableEvents ()
513 {
514 this.availableEvents = [];
515 this.availableEventsByType = {};
516
517 if (!this.currentUser || !this.currentSave)
518 return;
519
520 try
521 {
522 const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.id}`, {
523 method: 'GET',
524 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
525 });
526
527 const dataText = await response.text();
528 const data = JSON.parse(dataText);
529
530 if (data.success && Array.isArray(data.events))
531 {
532 this.availableEvents = data.events;
533 data.events.forEach(evt =>
534 {
535 if (evt && evt.type)
536 this.availableEventsByType[evt.type] = evt;
537 });
538 }
539 } catch (error)
540 {
541 console.error('Failed to load events:', error);
542 }
543 }
544
497 async executeEvent (eventType)
545 async executeEvent (eventType)
498 {
546 {
499 // Deprecated direct execution; use participant modal instead
547 // Deprecated direct execution; use participant modal instead
@@ -504,21 +552,17 @@ class TribeGenApp
504 {
552 {
505 this.currentEventType = eventType;
553 this.currentEventType = eventType;
506 const modal = document.getElementById('participantModal');
554 const modal = document.getElementById('participantModal');
507 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventType}`;
555 const eventData = this.availableEventsByType[eventType] || {};
556 const eventLabel = eventData.name || eventType;
557 document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`;
508
558
509 const list = document.getElementById('participantsList');
559 const list = document.getElementById('participantsList');
510 list.innerHTML = '';
560 list.innerHTML = '';
511
561
512 // Default limits and minimum age (server also enforces). Adjust per event if needed.
562 this.participantMin = eventData.min_participants ?? 1;
513 const eventConfig = {
563 this.participantMax = eventData.max_participants ?? 3;
514 'Exploration': { min: 1, max: 3, minAge: 0 },
564 this.participantMinAge = eventData.min_age ?? 0;
515 'Hunting': { min: 1, max: 3, minAge: 0 },
565 this.participantCost = eventData.cost || 0;
516 'Farming': { min: 1, max: 3, minAge: 0 }
517 };
518 const config = eventConfig[eventType] || { min: 1, max: 3, minAge: 0 };
519 this.participantMin = config.min;
520 this.participantMax = config.max;
521 this.participantMinAge = config.minAge;
522
566
523 // Helper: check if kobold is eligible
567 // Helper: check if kobold is eligible
524 const isEligible = (kobold) =>
568 const isEligible = (kobold) =>
@@ -527,6 +571,9 @@ class TribeGenApp
527 if (ageCategory === 'egg') return false; // eggs cannot participate
571 if (ageCategory === 'egg') return false; // eggs cannot participate
528 if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend)
572 if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend)
529 if (kobold.age < this.participantMinAge) return false; // too young
573 if (kobold.age < this.participantMinAge) return false; // too young
574 const fatigue = Number(kobold.fatigue || 0);
575 const vitality = Number(kobold.stats?.vitality || 0);
576 if ((fatigue + this.participantCost) > vitality) return false;
530 return true;
577 return true;
531 };
578 };
532
579
@@ -541,6 +588,10 @@ class TribeGenApp
541 reason = '(eggs cannot participate)';
588 reason = '(eggs cannot participate)';
542 else if (kobold.age < this.participantMinAge)
589 else if (kobold.age < this.participantMinAge)
543 reason = `(too young, needs age ${this.participantMinAge}+)`;
590 reason = `(too young, needs age ${this.participantMinAge}+)`;
591 else if (this.participantCost > Number(kobold.stats?.vitality || 0))
592 reason = '(too weak)';
593 else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0))
594 reason = '(too tired)';
544
595
545 const row = document.createElement('div');
596 const row = document.createElement('div');
546 row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`;
597 row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`;
@@ -616,7 +667,7 @@ class TribeGenApp
616 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected })
667 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected })
617 });
668 });
618
669
619 const dataText = await resp.text()
670 const dataText = await resp.text();
620 const data = JSON.parse(dataText);
671 const data = JSON.parse(dataText);
621
672
622 if (data.success)
673 if (data.success)
@@ -659,6 +710,7 @@ class TribeGenApp
659 this.currentSave = data.save;
710 this.currentSave = data.save;
660 typeText(document.getElementById('eventStory'), data.monthStory);
711 typeText(document.getElementById('eventStory'), data.monthStory);
661 this.showEventModal();
712 this.showEventModal();
713 await this.loadGame(this.currentSave.id);
662 }
714 }
663 } catch (error)
715 } catch (error)
664 {
716 {
@@ -776,7 +828,7 @@ class TribeGenApp
776 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
828 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
777 });
829 });
778
830
779 const dataText = await resp.text()
831 const dataText = await resp.text();
780 const data = JSON.parse(dataText);
832 const data = JSON.parse(dataText);
781 if (data.success)
833 if (data.success)
782 {
834 {
@@ -855,7 +907,7 @@ class TribeGenApp
855 const statsGrid = document.getElementById('koboldStats');
907 const statsGrid = document.getElementById('koboldStats');
856 statsGrid.innerHTML = '';
908 statsGrid.innerHTML = '';
857
909
858 const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
910 const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
859 stats.forEach(stat =>
911 stats.forEach(stat =>
860 {
912 {
861 const value = kobold.stats[stat];
913 const value = kobold.stats[stat];
@@ -868,6 +920,17 @@ class TribeGenApp
868 `;
920 `;
869 statsGrid.appendChild(statEl);
921 statsGrid.appendChild(statEl);
870 });
922 });
923
924 const fatigueValue = Number(kobold.fatigue || 0);
925 const vitalityValue = Number(kobold.stats?.vitality || 0);
926 const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue);
927 const fatigueEl = document.createElement('div');
928 fatigueEl.className = 'stat-item';
929 fatigueEl.innerHTML = `
930 <div class="stat-name">energy</div>
931 <div class="stat-value">${fatigueLabel}</div>
932 `;
933 statsGrid.appendChild(fatigueEl);
871 }
934 }
872
935
873 renderKoboldInventory (kobold)
936 renderKoboldInventory (kobold)
@@ -957,7 +1020,7 @@ class TribeGenApp
957 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
1020 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
958 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
1021 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
959 });
1022 });
960 const dataText = await resp.text()
1023 const dataText = await resp.text();
961 const data = JSON.parse(dataText);
1024 const data = JSON.parse(dataText);
962 if (data.success)
1025 if (data.success)
963 {
1026 {
@@ -1047,7 +1110,7 @@ class TribeGenApp
1047 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
1110 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
1048 });
1111 });
1049
1112
1050 const dataText = await resp.text()
1113 const dataText = await resp.text();
1051 const data = JSON.parse(dataText);
1114 const data = JSON.parse(dataText);
1052 if (data.success)
1115 if (data.success)
1053 {
1116 {
@@ -1096,6 +1159,19 @@ class TribeGenApp
1096 return 'terrible';
1159 return 'terrible';
1097 }
1160 }
1098
1161
1162 getFatigueLabel (fatigue, vitality)
1163 {
1164 const vit = Number(vitality || 0);
1165 const fat = Number(fatigue || 0);
1166 if (vit <= 0) return 'exhausted';
1167 if (fat <= 0) return 'energetic';
1168 const ratio = fat / Math.max(1, vit);
1169 if (ratio < 0.3) return 'fresh';
1170 if (ratio < 0.6) return 'tired';
1171 if (ratio < 0.85) return 'weary';
1172 return 'exhausted';
1173 }
1174
1099 hideAll ()
1175 hideAll ()
1100 {
1176 {
1101 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
1177 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
web/src/Classes/Injury.php +5 −3
@@ -5,11 +5,13 @@ require_once __DIR__ . '/../../src/Database/Database.php';
5 5 class Injury
6 6 {
7 7 private static $cureMap = [
8 'wound' => 'basic_medicine',
8 'disease' => 'medicine',
9 'cut' => 'bandage',
10 'bruise' => 'bruise-salve',
9 11 'fracture' => 'bone-setting',
10 'infection' => 'healing_herbs',
12 'infection' => 'healing-herbs',
11 13 'poison' => 'antidote',
12 'burn' => 'burn_salve',
14 'burn' => 'burn-salve',
13 15 'malnourished' => 'food', // Cured by having enough food
14 16 'old-age' => null // Cannot be cured
15 17 ];
@@ -5,11 +5,13 @@ require_once __DIR__ . '/../../src/Database/Database.php';
5class Injury
5class Injury
6{
6{
7 private static $cureMap = [
7 private static $cureMap = [
8 'wound' => 'basic_medicine',
8 'disease' => 'medicine',
9 'cut' => 'bandage',
10 'bruise' => 'bruise-salve',
9 'fracture' => 'bone-setting',
11 'fracture' => 'bone-setting',
10 'infection' => 'healing_herbs',
12 'infection' => 'healing-herbs',
11 'poison' => 'antidote',
13 'poison' => 'antidote',
12 'burn' => 'burn_salve',
14 'burn' => 'burn-salve',
13 'malnourished' => 'food', // Cured by having enough food
15 'malnourished' => 'food', // Cured by having enough food
14 'old-age' => null // Cannot be cured
16 'old-age' => null // Cannot be cured
15 ];
17 ];
web/src/Classes/Kobold.php +49 −1
@@ -17,6 +17,7 @@ class Kobold
17 17 private $isExpelled = false;
18 18 private $injuries = [];
19 19 private $items = [];
20 private $fatigue = 0;
20 21 private $fatherId;
21 22 private $motherId;
22 23 private $saveManager;
@@ -30,7 +31,6 @@ class Kobold
30 31 private static $statNames = [
31 32 'vitality',
32 33 'intelligence',
33 'tinkering',
34 34 'medicine',
35 35 'crafting',
36 36 'personality',
@@ -48,6 +48,7 @@ class Kobold
48 48 $this->spriteMorph = $spriteMorph;
49 49 $this->isLeader = $isLeader;
50 50 $this->male = rand(0, 100) > 50;
51 $this->fatigue = 0;
51 52
52 53 $min = 120;
53 54 $mx = 240;
@@ -222,6 +223,7 @@ class Kobold
222 223 $kobold->isExpelled = $data['is_expelled'] ?? false;
223 224 $kobold->injuries = $data['injuries'] ?? [];
224 225 $kobold->items = $data['items'] ?? [];
226 $kobold->fatigue = $data['fatigue'] ?? 0;
225 227 $kobold->fatherId = $data['father_id'] ?? null;
226 228 $kobold->motherId = $data['mother_id'] ?? null;
227 229 $kobold->male = $data['male'] ?? rand(0, 100) > 50;
@@ -247,6 +249,8 @@ class Kobold
247 249 'is_expelled' => $this->isExpelled,
248 250 'injuries' => $this->injuries,
249 251 'items' => $this->items,
252 'fatigue' => $this->fatigue,
253 'fatigue_label' => $this->getFatigueLabel(),
250 254 'father_id' => $this->fatherId,
251 255 'mother_id' => $this->motherId,
252 256 'colour_primary' => $this->colourPrimary,
@@ -476,6 +480,50 @@ class Kobold
476 480 return $this->injuries;
477 481 }
478 482
483 public function getFatigue()
484 {
485 return $this->fatigue;
486 }
487
488 public function setFatigue($value)
489 {
490 $this->fatigue = max(0, (int) $value);
491 }
492
493 public function addFatigue($amount)
494 {
495 $this->fatigue = max(0, $this->fatigue + (int) $amount);
496 }
497
498 public function resetFatigue()
499 {
500 $this->fatigue = 0;
501 }
502
503 public function getFatigueLabel()
504 {
505 $vitality = (int) ($this->getStat('vitality') ?? 0);
506 if ($vitality <= 0) {
507 return 'exhausted';
508 }
509
510 $ratio = $this->fatigue / max(1, $vitality);
511
512 if ($this->fatigue <= 0) {
513 return 'energetic';
514 }
515 if ($ratio < 0.3) {
516 return 'fresh';
517 }
518 if ($ratio < 0.6) {
519 return 'tired';
520 }
521 if ($ratio < 0.85) {
522 return 'weary';
523 }
524 return 'exhausted';
525 }
526
479 527 public function getTotalInjurySeverity()
480 528 {
481 529 $sum = 0;
@@ -17,6 +17,7 @@ class Kobold
17 private $isExpelled = false;
17 private $isExpelled = false;
18 private $injuries = [];
18 private $injuries = [];
19 private $items = [];
19 private $items = [];
20 private $fatigue = 0;
20 private $fatherId;
21 private $fatherId;
21 private $motherId;
22 private $motherId;
22 private $saveManager;
23 private $saveManager;
@@ -30,7 +31,6 @@ class Kobold
30 private static $statNames = [
31 private static $statNames = [
31 'vitality',
32 'vitality',
32 'intelligence',
33 'intelligence',
33 'tinkering',
34 'medicine',
34 'medicine',
35 'crafting',
35 'crafting',
36 'personality',
36 'personality',
@@ -48,6 +48,7 @@ class Kobold
48 $this->spriteMorph = $spriteMorph;
48 $this->spriteMorph = $spriteMorph;
49 $this->isLeader = $isLeader;
49 $this->isLeader = $isLeader;
50 $this->male = rand(0, 100) > 50;
50 $this->male = rand(0, 100) > 50;
51 $this->fatigue = 0;
51
52
52 $min = 120;
53 $min = 120;
53 $mx = 240;
54 $mx = 240;
@@ -222,6 +223,7 @@ class Kobold
222 $kobold->isExpelled = $data['is_expelled'] ?? false;
223 $kobold->isExpelled = $data['is_expelled'] ?? false;
223 $kobold->injuries = $data['injuries'] ?? [];
224 $kobold->injuries = $data['injuries'] ?? [];
224 $kobold->items = $data['items'] ?? [];
225 $kobold->items = $data['items'] ?? [];
226 $kobold->fatigue = $data['fatigue'] ?? 0;
225 $kobold->fatherId = $data['father_id'] ?? null;
227 $kobold->fatherId = $data['father_id'] ?? null;
226 $kobold->motherId = $data['mother_id'] ?? null;
228 $kobold->motherId = $data['mother_id'] ?? null;
227 $kobold->male = $data['male'] ?? rand(0, 100) > 50;
229 $kobold->male = $data['male'] ?? rand(0, 100) > 50;
@@ -247,6 +249,8 @@ class Kobold
247 'is_expelled' => $this->isExpelled,
249 'is_expelled' => $this->isExpelled,
248 'injuries' => $this->injuries,
250 'injuries' => $this->injuries,
249 'items' => $this->items,
251 'items' => $this->items,
252 'fatigue' => $this->fatigue,
253 'fatigue_label' => $this->getFatigueLabel(),
250 'father_id' => $this->fatherId,
254 'father_id' => $this->fatherId,
251 'mother_id' => $this->motherId,
255 'mother_id' => $this->motherId,
252 'colour_primary' => $this->colourPrimary,
256 'colour_primary' => $this->colourPrimary,
@@ -476,6 +480,50 @@ class Kobold
476 return $this->injuries;
480 return $this->injuries;
477 }
481 }
478
482
483 public function getFatigue()
484 {
485 return $this->fatigue;
486 }
487
488 public function setFatigue($value)
489 {
490 $this->fatigue = max(0, (int) $value);
491 }
492
493 public function addFatigue($amount)
494 {
495 $this->fatigue = max(0, $this->fatigue + (int) $amount);
496 }
497
498 public function resetFatigue()
499 {
500 $this->fatigue = 0;
501 }
502
503 public function getFatigueLabel()
504 {
505 $vitality = (int) ($this->getStat('vitality') ?? 0);
506 if ($vitality <= 0) {
507 return 'exhausted';
508 }
509
510 $ratio = $this->fatigue / max(1, $vitality);
511
512 if ($this->fatigue <= 0) {
513 return 'energetic';
514 }
515 if ($ratio < 0.3) {
516 return 'fresh';
517 }
518 if ($ratio < 0.6) {
519 return 'tired';
520 }
521 if ($ratio < 0.85) {
522 return 'weary';
523 }
524 return 'exhausted';
525 }
526
479 public function getTotalInjurySeverity()
527 public function getTotalInjurySeverity()
480 {
528 {
481 $sum = 0;
529 $sum = 0;
web/src/Classes/Tribe.php +30 −9
@@ -18,12 +18,12 @@ class Tribe
18 18 private $saveManager;
19 19
20 20 // Food requirement by age tier (portion units)
21 private $foodRequirements = [
22 'egg' => 0, // Eggs don't eat
23 'baby' => 0.5, // Babies eat less
24 'adult' => 1.0, // Adults eat standard amount
25 'old' => 0.6, // Elderly eat less
26 'very_old' => 0.4 // Very old eat even less
21 public $foodRequirements = [
22 'egg' => 0,
23 'baby' => 1,
24 'young' => 2,
25 'adult' => 3,
26 'old' => 2
27 27 ];
28 28
29 29 public function __construct($userId, $saveId, $name = '')
@@ -120,6 +120,7 @@ class Tribe
120 120 'current_month' => $this->currentMonth,
121 121 'current_season' => $this->currentSeason,
122 122 'food_count' => $this->foodCount,
123 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
123 124 'created_at' => $this->createdAt,
124 125 'last_played' => $this->lastPlayed
125 126 ];
@@ -228,7 +229,7 @@ class Tribe
228 229 }
229 230
230 231 // Storage management
231 public function addToStorage($item)
232 public function addToStorage(Item $item, int $count = 1): array
232 233 {
233 234 // Accept either Item object or array
234 235 if (is_object($item) && method_exists($item, 'toArray')) {
@@ -238,7 +239,8 @@ class Tribe
238 239 if (!isset($item['id'])) {
239 240 $item['id'] = uniqid('itm_');
240 241 }
241 $this->storage[] = $item;
242 for ($i = 0; $i < $count; $i++)
243 $this->storage[] = $item;
242 244 }
243 245 return $this->storage;
244 246 }
@@ -267,7 +269,7 @@ class Tribe
267 269 }
268 270
269 271 /**
270 * Calculate total food needed for all alive kobolds
272 * Calculate total food needed for all alive kobolds for one month
271 273 */
272 274 public function calculateFoodNeeded()
273 275 {
@@ -282,6 +284,21 @@ class Tribe
282 284 return $needed;
283 285 }
284 286
287 /**
288 * Calculate how many full months the current kobolds can be fed
289 * with the provided amount of food.
290 */
291 public function foodMonthsLeft($amount)
292 {
293 $foodPerMonth = $this->calculateFoodNeeded();
294 if ($foodPerMonth <= 0) {
295 return 0;
296 }
297
298 $available = max(0, (float) $amount);
299 return (int) floor($available / $foodPerMonth);
300 }
301
285 302 /**
286 303 * Get food requirement for a specific kobold
287 304 */
@@ -399,6 +416,10 @@ class Tribe
399 416 {
400 417 $this->currentMonth++;
401 418
419 foreach ($this->kobolds as $kobold) {
420 $kobold->resetFatigue();
421 }
422
402 423 $seasons = ['spring', 'summer', 'autumn', 'winter'];
403 424
404 425 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
@@ -18,12 +18,12 @@ class Tribe
18 private $saveManager;
18 private $saveManager;
19
19
20 // Food requirement by age tier (portion units)
20 // Food requirement by age tier (portion units)
21 private $foodRequirements = [
21 public $foodRequirements = [
22 'egg' => 0, // Eggs don't eat
22 'egg' => 0,
23 'baby' => 0.5, // Babies eat less
23 'baby' => 1,
24 'adult' => 1.0, // Adults eat standard amount
24 'young' => 2,
25 'old' => 0.6, // Elderly eat less
25 'adult' => 3,
26 'very_old' => 0.4 // Very old eat even less
26 'old' => 2
27 ];
27 ];
28
28
29 public function __construct($userId, $saveId, $name = '')
29 public function __construct($userId, $saveId, $name = '')
@@ -120,6 +120,7 @@ class Tribe
120 'current_month' => $this->currentMonth,
120 'current_month' => $this->currentMonth,
121 'current_season' => $this->currentSeason,
121 'current_season' => $this->currentSeason,
122 'food_count' => $this->foodCount,
122 'food_count' => $this->foodCount,
123 'food_months_left' => $this->foodMonthsLeft($this->foodCount),
123 'created_at' => $this->createdAt,
124 'created_at' => $this->createdAt,
124 'last_played' => $this->lastPlayed
125 'last_played' => $this->lastPlayed
125 ];
126 ];
@@ -228,7 +229,7 @@ class Tribe
228 }
229 }
229
230
230 // Storage management
231 // Storage management
231 public function addToStorage($item)
232 public function addToStorage(Item $item, int $count = 1): array
232 {
233 {
233 // Accept either Item object or array
234 // Accept either Item object or array
234 if (is_object($item) && method_exists($item, 'toArray')) {
235 if (is_object($item) && method_exists($item, 'toArray')) {
@@ -238,7 +239,8 @@ class Tribe
238 if (!isset($item['id'])) {
239 if (!isset($item['id'])) {
239 $item['id'] = uniqid('itm_');
240 $item['id'] = uniqid('itm_');
240 }
241 }
241 $this->storage[] = $item;
242 for ($i = 0; $i < $count; $i++)
243 $this->storage[] = $item;
242 }
244 }
243 return $this->storage;
245 return $this->storage;
244 }
246 }
@@ -267,7 +269,7 @@ class Tribe
267 }
269 }
268
270
269 /**
271 /**
270 * Calculate total food needed for all alive kobolds
272 * Calculate total food needed for all alive kobolds for one month
271 */
273 */
272 public function calculateFoodNeeded()
274 public function calculateFoodNeeded()
273 {
275 {
@@ -282,6 +284,21 @@ class Tribe
282 return $needed;
284 return $needed;
283 }
285 }
284
286
287 /**
288 * Calculate how many full months the current kobolds can be fed
289 * with the provided amount of food.
290 */
291 public function foodMonthsLeft($amount)
292 {
293 $foodPerMonth = $this->calculateFoodNeeded();
294 if ($foodPerMonth <= 0) {
295 return 0;
296 }
297
298 $available = max(0, (float) $amount);
299 return (int) floor($available / $foodPerMonth);
300 }
301
285 /**
302 /**
286 * Get food requirement for a specific kobold
303 * Get food requirement for a specific kobold
287 */
304 */
@@ -399,6 +416,10 @@ class Tribe
399 {
416 {
400 $this->currentMonth++;
417 $this->currentMonth++;
401
418
419 foreach ($this->kobolds as $kobold) {
420 $kobold->resetFatigue();
421 }
422
402 $seasons = ['spring', 'summer', 'autumn', 'winter'];
423 $seasons = ['spring', 'summer', 'autumn', 'winter'];
403
424
404 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
425 $monthOfYear = (($this->currentMonth - 1) % 12) + 1;
web/src/Events/Event.php +9 −10
@@ -7,8 +7,6 @@ abstract class Event
7 7 protected $tribe;
8 8 protected $story = '';
9 9 protected $participants = []; // array of kobold ids
10 protected $minParticipants = 1;
11 protected $maxParticipants = 3;
12 10
13 11 public function __construct(Tribe $tribe)
14 12 {
@@ -17,6 +15,13 @@ abstract class Event
17 15
18 16 abstract public function execute();
19 17
18 abstract public function getCost();
19
20 public function isAvailable()
21 {
22 return true;
23 }
24
20 25 public function setParticipants(array $koboldIds)
21 26 {
22 27 $this->participants = $koboldIds;
@@ -27,15 +32,9 @@ abstract class Event
27 32 return $this->participants;
28 33 }
29 34
30 public function getMinParticipants()
31 {
32 return $this->minParticipants;
33 }
35 abstract function getMinParticipants();
34 36
35 public function getMaxParticipants()
36 {
37 return $this->maxParticipants;
38 }
37 abstract function getMaxParticipants();
39 38
40 39 public function getStory()
41 40 {
@@ -7,8 +7,6 @@ abstract class Event
7 protected $tribe;
7 protected $tribe;
8 protected $story = '';
8 protected $story = '';
9 protected $participants = []; // array of kobold ids
9 protected $participants = []; // array of kobold ids
10 protected $minParticipants = 1;
11 protected $maxParticipants = 3;
12
10
13 public function __construct(Tribe $tribe)
11 public function __construct(Tribe $tribe)
14 {
12 {
@@ -17,6 +15,13 @@ abstract class Event
17
15
18 abstract public function execute();
16 abstract public function execute();
19
17
18 abstract public function getCost();
19
20 public function isAvailable()
21 {
22 return true;
23 }
24
20 public function setParticipants(array $koboldIds)
25 public function setParticipants(array $koboldIds)
21 {
26 {
22 $this->participants = $koboldIds;
27 $this->participants = $koboldIds;
@@ -27,15 +32,9 @@ abstract class Event
27 return $this->participants;
32 return $this->participants;
28 }
33 }
29
34
30 public function getMinParticipants()
35 abstract function getMinParticipants();
31 {
32 return $this->minParticipants;
33 }
34
36
35 public function getMaxParticipants()
37 abstract function getMaxParticipants();
36 {
37 return $this->maxParticipants;
38 }
39
38
40 public function getStory()
39 public function getStory()
41 {
40 {
web/src/Events/ExplorationEvent.php +20 −0
@@ -6,6 +6,26 @@ require_once __DIR__ . '/../../src/Classes/Kobold.php';
6 6
7 7 class ExplorationEvent extends Event
8 8 {
9 public function getMinParticipants()
10 {
11 return 1;
12 }
13
14 public function getMaxParticipants()
15 {
16 return 10;
17 }
18
19 public function getCost()
20 {
21 return 12;
22 }
23
24 public function isAvailable()
25 {
26 return true;
27 }
28
9 29 public function execute()
10 30 {
11 31 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
@@ -6,6 +6,26 @@ require_once __DIR__ . '/../../src/Classes/Kobold.php';
6
6
7class ExplorationEvent extends Event
7class ExplorationEvent extends Event
8{
8{
9 public function getMinParticipants()
10 {
11 return 1;
12 }
13
14 public function getMaxParticipants()
15 {
16 return 10;
17 }
18
19 public function getCost()
20 {
21 return 12;
22 }
23
24 public function isAvailable()
25 {
26 return true;
27 }
28
9 public function execute()
29 public function execute()
10 {
30 {
11 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
31 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
web/src/Events/FarmingEvent.php +103 −5
@@ -1,18 +1,116 @@
1 1 <?php
2 2
3 3 require_once __DIR__ . '/../../src/Events/Event.php';
4 require_once __DIR__ . '/../../src/Utilities/GameHelper.php';
4 5
5 6 class FarmingEvent extends Event
6 7 {
8 public function getMinParticipants()
9 {
10 return 2;
11 }
12
13 public function getMaxParticipants()
14 {
15 return 10;
16 }
17
18 public function getCost()
19 {
20 switch ($this->tribe->getCurrentSeason()) {
21 case 'spring':
22 return 30;
23 case 'summer':
24 return 35;
25 case 'autumn':
26 return 40;
27 case 'winter':
28 return 90;
29 default:
30 return 60;
31 }
32 }
33
34 public function isAvailable()
35 {
36 return $this->tribe->getCurrentSeason() !== 'winter';
37 }
38
7 39 public function execute()
8 40 {
9 $this->story = "The farmers tended to their crops...\n\n";
41 $participantIds = $this->getParticipants();
42 $explorers = [];
43 foreach ($participantIds as $pid) {
44 $k = $this->tribe->getKobold($pid);
45 if ($k && !$k->isDead())
46 $explorers[] = $k;
47 }
48
49 $leader = GameHelper::findBestKoboldForStat($explorers, "intelligence");
50 $hardestWorker = GameHelper::findBestKoboldForStat($explorers, "vitality");
51
52 $this->story = "The farmers tended to their crops. {$leader->getName()} took the lead.\n";
53
54 for ($i = 0; $i < count($explorers); $i++) {
55 $farmer = $explorers[$i];
56
57 if (!$farmer->checkStat('will')) {
58 $farmer->addInjury("cut");
59 $this->story .= "{$farmer->getName()} had an accident plowing the field, cutting {$farmer->his()} leg with the hoe.\n";
60 break;
61 }
62 }
63
64 for ($i = 0; $i < count($explorers); $i++) {
65 $farmer = $explorers[$i];
66
67 if ($farmer->checkStat('intelligence')) {
68 $herbs = GameHelper::loadItem('healing-herbs');
69 $this->tribe->addToStorage($herbs, rand(1, 3));
70 $this->story .= "{$farmer->getName()} managed to grow some useful healing herbs while tending the crops.\n";
71 break;
72 }
73 }
74
75 if (!$leader->checkStat('intelligence')) {
76 $this->story .= "Unfortunately, {$leader->getName()} made several mistakes in planting and caring for the crops.\n";
77 $this->story .= "Despite {$hardestWorker->getName()}'s best efforts, the crops had rotten and were lost.\n";
78 return $this->story;
79 } else {
80 $totalFood = 0;
81 $mostFood = 0;
82 $mostFarmedBy = '';
83
84 for ($i = 0; $i < count($explorers); $i++) {
85 $farmer = $explorers[$i];
86
87 $farmed = rand(0, $this->tribe->foodRequirements[$farmer->getAgeCategory()] * 3);
88 $totalFood += $farmed;
89
90 if ($farmed > $mostFood) {
91 $mostFood = $farmed;
92 $mostFarmedBy = $farmer->getName();
93 }
94 }
10 95
11 // TODO: Implement farming logic
12 // Can produce food, can fail, injure kobolds, etc.
96 if ($mostFarmedBy == $hardestWorker->getName()) {
97 $this->story .= "{$hardestWorker->getName()} worked the hardest and managed to produce the most food for the tribe!\n";
98 } else {
99 $this->story .= "Despite {$hardestWorker->getName()} working the hardest out of everyone, it was {$mostFarmedBy} who produced the most food for the tribe.\n";
100 }
13 101
14 $this->story .= "The fields yielded a modest harvest.";
102 $months = $this->tribe->foodMonthsLeft($totalFood);
103 $this->tribe->addFood($totalFood);
15 104
16 return $this->story;
105 if ($months < 1)
106 $this->story .= "The tribe gained less than a month worth of food from the harvest.\n";
107 else {
108 if ($months == 1)
109 $this->story .= "The tribe gained a month worth of food from the harvest.\n";
110 else
111 $this->story .= "The tribe gained " . $months . " months worth of food from the harvest!\n";
112 }
113 return $this->story;
114 }
17 115 }
18 116 }
@@ -1,18 +1,116 @@
1<?php
1<?php
2
2
3require_once __DIR__ . '/../../src/Events/Event.php';
3require_once __DIR__ . '/../../src/Events/Event.php';
4require_once __DIR__ . '/../../src/Utilities/GameHelper.php';
4
5
5class FarmingEvent extends Event
6class FarmingEvent extends Event
6{
7{
8 public function getMinParticipants()
9 {
10 return 2;
11 }
12
13 public function getMaxParticipants()
14 {
15 return 10;
16 }
17
18 public function getCost()
19 {
20 switch ($this->tribe->getCurrentSeason()) {
21 case 'spring':
22 return 30;
23 case 'summer':
24 return 35;
25 case 'autumn':
26 return 40;
27 case 'winter':
28 return 90;
29 default:
30 return 60;
31 }
32 }
33
34 public function isAvailable()
35 {
36 return $this->tribe->getCurrentSeason() !== 'winter';
37 }
38
7 public function execute()
39 public function execute()
8 {
40 {
9 $this->story = "The farmers tended to their crops...\n\n";
41 $participantIds = $this->getParticipants();
42 $explorers = [];
43 foreach ($participantIds as $pid) {
44 $k = $this->tribe->getKobold($pid);
45 if ($k && !$k->isDead())
46 $explorers[] = $k;
47 }
48
49 $leader = GameHelper::findBestKoboldForStat($explorers, "intelligence");
50 $hardestWorker = GameHelper::findBestKoboldForStat($explorers, "vitality");
51
52 $this->story = "The farmers tended to their crops. {$leader->getName()} took the lead.\n";
53
54 for ($i = 0; $i < count($explorers); $i++) {
55 $farmer = $explorers[$i];
56
57 if (!$farmer->checkStat('will')) {
58 $farmer->addInjury("cut");
59 $this->story .= "{$farmer->getName()} had an accident plowing the field, cutting {$farmer->his()} leg with the hoe.\n";
60 break;
61 }
62 }
63
64 for ($i = 0; $i < count($explorers); $i++) {
65 $farmer = $explorers[$i];
66
67 if ($farmer->checkStat('intelligence')) {
68 $herbs = GameHelper::loadItem('healing-herbs');
69 $this->tribe->addToStorage($herbs, rand(1, 3));
70 $this->story .= "{$farmer->getName()} managed to grow some useful healing herbs while tending the crops.\n";
71 break;
72 }
73 }
74
75 if (!$leader->checkStat('intelligence')) {
76 $this->story .= "Unfortunately, {$leader->getName()} made several mistakes in planting and caring for the crops.\n";
77 $this->story .= "Despite {$hardestWorker->getName()}'s best efforts, the crops had rotten and were lost.\n";
78 return $this->story;
79 } else {
80 $totalFood = 0;
81 $mostFood = 0;
82 $mostFarmedBy = '';
83
84 for ($i = 0; $i < count($explorers); $i++) {
85 $farmer = $explorers[$i];
86
87 $farmed = rand(0, $this->tribe->foodRequirements[$farmer->getAgeCategory()] * 3);
88 $totalFood += $farmed;
89
90 if ($farmed > $mostFood) {
91 $mostFood = $farmed;
92 $mostFarmedBy = $farmer->getName();
93 }
94 }
10
95
11 // TODO: Implement farming logic
96 if ($mostFarmedBy == $hardestWorker->getName()) {
12 // Can produce food, can fail, injure kobolds, etc.
97 $this->story .= "{$hardestWorker->getName()} worked the hardest and managed to produce the most food for the tribe!\n";
98 } else {
99 $this->story .= "Despite {$hardestWorker->getName()} working the hardest out of everyone, it was {$mostFarmedBy} who produced the most food for the tribe.\n";
100 }
13
101
14 $this->story .= "The fields yielded a modest harvest.";
102 $months = $this->tribe->foodMonthsLeft($totalFood);
103 $this->tribe->addFood($totalFood);
15
104
16 return $this->story;
105 if ($months < 1)
106 $this->story .= "The tribe gained less than a month worth of food from the harvest.\n";
107 else {
108 if ($months == 1)
109 $this->story .= "The tribe gained a month worth of food from the harvest.\n";
110 else
111 $this->story .= "The tribe gained " . $months . " months worth of food from the harvest!\n";
112 }
113 return $this->story;
114 }
17 }
115 }
18}
116}
web/src/Events/HuntingEvent.php +20 −0
@@ -5,6 +5,26 @@ require_once __DIR__ . '/../../src/Classes/Kobold.php';
5 5
6 6 class HuntingEvent extends Event
7 7 {
8 public function getMinParticipants()
9 {
10 return 2;
11 }
12
13 public function getMaxParticipants()
14 {
15 return 5;
16 }
17
18 public function getCost()
19 {
20 return 25;
21 }
22
23 public function isAvailable()
24 {
25 return true;
26 }
27
8 28 public function execute()
9 29 {
10 30 $this->story = "The hunting party set out into the wilderness...\n\n";
@@ -5,6 +5,26 @@ require_once __DIR__ . '/../../src/Classes/Kobold.php';
5
5
6class HuntingEvent extends Event
6class HuntingEvent extends Event
7{
7{
8 public function getMinParticipants()
9 {
10 return 2;
11 }
12
13 public function getMaxParticipants()
14 {
15 return 5;
16 }
17
18 public function getCost()
19 {
20 return 25;
21 }
22
23 public function isAvailable()
24 {
25 return true;
26 }
27
8 public function execute()
28 public function execute()
9 {
29 {
10 $this->story = "The hunting party set out into the wilderness...\n\n";
30 $this->story = "The hunting party set out into the wilderness...\n\n";
web/src/System/SaveManager.php +1 −1
@@ -78,7 +78,7 @@ class SaveManager
78 78 }
79 79 }
80 80
81 $path = $kobold ? $kobold->getSpritePath($age) : $this->getKoboldSpritePathBase($userId, $koboldId, $age);
81 $path = $kobold->getSpritePath($age);
82 82
83 83 return $path;
84 84 }
@@ -78,7 +78,7 @@ class SaveManager
78 }
78 }
79 }
79 }
80
80
81 $path = $kobold ? $kobold->getSpritePath($age) : $this->getKoboldSpritePathBase($userId, $koboldId, $age);
81 $path = $kobold->getSpritePath($age);
82
82
83 return $path;
83 return $path;
84 }
84 }
web/src/Utilities/GameHelper.php +1 −1
@@ -227,7 +227,7 @@ class GameHelper
227 227 public static function generateRandomStats()
228 228 {
229 229 $stats = [];
230 $statNames = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
230 $statNames = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
231 231
232 232 foreach ($statNames as $stat) {
233 233 $stats[$stat] = rand(0, 100);
@@ -227,7 +227,7 @@ class GameHelper
227 public static function generateRandomStats()
227 public static function generateRandomStats()
228 {
228 {
229 $stats = [];
229 $stats = [];
230 $statNames = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
230 $statNames = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting'];
231
231
232 foreach ($statNames as $stat) {
232 foreach ($statNames as $stat) {
233 $stats[$stat] = rand(0, 100);
233 $stats[$stat] = rand(0, 100);
web/src/api/game.php +77 −6
@@ -43,13 +43,14 @@ if ($method === 'POST') {
43 43 'stats' => [
44 44 'vitality' => $kobold->getStat('vitality'),
45 45 'intelligence' => $kobold->getStat('intelligence'),
46 'tinkering' => $kobold->getStat('tinkering'),
47 46 'medicine' => $kobold->getStat('medicine'),
48 47 'crafting' => $kobold->getStat('crafting'),
49 48 'personality' => $kobold->getStat('personality'),
50 49 'will' => $kobold->getStat('will'),
51 50 'fighting' => $kobold->getStat('fighting')
52 ]
51 ],
52 'fatigue' => $kobold->getFatigue(),
53 'fatigue_label' => $kobold->getFatigueLabel()
53 54 ];
54 55 }
55 56
@@ -376,6 +377,10 @@ if ($method === 'POST') {
376 377 throw new \Exception('Unknown event type');
377 378 $event = new $className($tribe);
378 379
380 if (method_exists($event, 'isAvailable') && !$event->isAvailable()) {
381 throw new \Exception('That event is not available right now.');
382 }
383
379 384 // Player-started events MUST provide participants (array of kobold IDs)
380 385 $participants = $input['participants'] ?? null;
381 386 if (empty($participants) || !is_array($participants)) {
@@ -390,14 +395,36 @@ if ($method === 'POST') {
390 395 throw new \Exception("Participants must be between {$min} and {$max}");
391 396 }
392 397
398 $cost = $event->getCost();
399 $participantKobolds = [];
400 $ineligible = [];
401 foreach ($participants as $pid) {
402 $kobold = $tribe->getKobold($pid);
403 if (!$kobold || $kobold->isDead()) {
404 throw new \Exception('One or more selected kobolds are unavailable.');
405 }
406
407 if (($kobold->getFatigue() + $cost) > $kobold->getStat('vitality')) {
408 $ineligible[] = $kobold->getName();
409 } else {
410 $participantKobolds[] = $kobold;
411 }
412 }
413
414 if (!empty($ineligible)) {
415 $names = implode(', ', $ineligible);
416 throw new \Exception("These kobolds are too fatigued for this event: {$names}");
417 }
418
393 419 $event->setParticipants($participants);
394 420
395 421 $event?->execute();
396 422 $story = $event?->getStory() ?? 'No event occurred.';
397 423
398 foreach ($participants as $participant) {
399 if ($participant->isDead()) {
400 $story = $story . "\n" . $participant->getName() . " has died.";
424 foreach ($participantKobolds as $kobold) {
425 $kobold->addFatigue($cost);
426 if ($kobold->isDead()) {
427 $story = $story . "\n" . $kobold->getName() . " has died.";
401 428 }
402 429 }
403 430
@@ -535,13 +562,14 @@ if ($method === 'POST') {
535 562 'stats' => [
536 563 'vitality' => $kobold->getStat('vitality'),
537 564 'intelligence' => $kobold->getStat('intelligence'),
538 'tinkering' => $kobold->getStat('tinkering'),
539 565 'medicine' => $kobold->getStat('medicine'),
540 566 'crafting' => $kobold->getStat('crafting'),
541 567 'personality' => $kobold->getStat('personality'),
542 568 'will' => $kobold->getStat('will'),
543 569 'fighting' => $kobold->getStat('fighting')
544 570 ],
571 'fatigue' => $kobold->getFatigue(),
572 'fatigue_label' => $kobold->getFatigueLabel(),
545 573 'items' => $kobold->getItems() ?? [],
546 574 'injuries' => $kInjuries,
547 575 'male' => $kobold->getMale()
@@ -559,6 +587,7 @@ if ($method === 'POST') {
559 587 'current_month' => $tribe->getCurrentMonth(),
560 588 'current_season' => $tribe->getCurrentSeason(),
561 589 'food_count' => $tribe->getFoodCount(),
590 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
562 591 'created_at' => $tribe->getCreatedAt(),
563 592 'last_played' => $tribe->getLastPlayed()
564 593 ],
@@ -574,6 +603,48 @@ if ($method === 'POST') {
574 603 'error' => $e->getMessage()
575 604 ]);
576 605 }
606 } elseif (strpos($apiPath, 'events') !== false) {
607 // List available events and their costs
608 try {
609 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
610 $saveId = $_GET['saveId'] ?? null;
611
612 if (!$userId || !$saveId) {
613 throw new \Exception('User ID and Save ID required');
614 }
615
616 $tribe = Tribe::load($userId, $saveId);
617
618 $events = [];
619 foreach (get_declared_classes() as $className) {
620 if (!is_subclass_of($className, 'Event')) {
621 continue;
622 }
623
624 $event = new $className($tribe);
625 $type = preg_replace('/Event$/', '', $className);
626
627 $events[] = [
628 'type' => $type,
629 'name' => $type,
630 'cost' => $event->getCost(),
631 'available' => $event->isAvailable(),
632 'min_participants' => $event->getMinParticipants(),
633 'max_participants' => $event->getMaxParticipants()
634 ];
635 }
636
637 echo json_encode([
638 'success' => true,
639 'events' => $events
640 ]);
641 } catch (\Exception $e) {
642 http_response_code(400);
643 echo json_encode([
644 'success' => false,
645 'error' => $e->getMessage()
646 ]);
647 }
577 648 }
578 649 }
579 650
@@ -43,13 +43,14 @@ if ($method === 'POST') {
43 'stats' => [
43 'stats' => [
44 'vitality' => $kobold->getStat('vitality'),
44 'vitality' => $kobold->getStat('vitality'),
45 'intelligence' => $kobold->getStat('intelligence'),
45 'intelligence' => $kobold->getStat('intelligence'),
46 'tinkering' => $kobold->getStat('tinkering'),
47 'medicine' => $kobold->getStat('medicine'),
46 'medicine' => $kobold->getStat('medicine'),
48 'crafting' => $kobold->getStat('crafting'),
47 'crafting' => $kobold->getStat('crafting'),
49 'personality' => $kobold->getStat('personality'),
48 'personality' => $kobold->getStat('personality'),
50 'will' => $kobold->getStat('will'),
49 'will' => $kobold->getStat('will'),
51 'fighting' => $kobold->getStat('fighting')
50 'fighting' => $kobold->getStat('fighting')
52 ]
51 ],
52 'fatigue' => $kobold->getFatigue(),
53 'fatigue_label' => $kobold->getFatigueLabel()
53 ];
54 ];
54 }
55 }
55
56
@@ -376,6 +377,10 @@ if ($method === 'POST') {
376 throw new \Exception('Unknown event type');
377 throw new \Exception('Unknown event type');
377 $event = new $className($tribe);
378 $event = new $className($tribe);
378
379
380 if (method_exists($event, 'isAvailable') && !$event->isAvailable()) {
381 throw new \Exception('That event is not available right now.');
382 }
383
379 // Player-started events MUST provide participants (array of kobold IDs)
384 // Player-started events MUST provide participants (array of kobold IDs)
380 $participants = $input['participants'] ?? null;
385 $participants = $input['participants'] ?? null;
381 if (empty($participants) || !is_array($participants)) {
386 if (empty($participants) || !is_array($participants)) {
@@ -390,14 +395,36 @@ if ($method === 'POST') {
390 throw new \Exception("Participants must be between {$min} and {$max}");
395 throw new \Exception("Participants must be between {$min} and {$max}");
391 }
396 }
392
397
398 $cost = $event->getCost();
399 $participantKobolds = [];
400 $ineligible = [];
401 foreach ($participants as $pid) {
402 $kobold = $tribe->getKobold($pid);
403 if (!$kobold || $kobold->isDead()) {
404 throw new \Exception('One or more selected kobolds are unavailable.');
405 }
406
407 if (($kobold->getFatigue() + $cost) > $kobold->getStat('vitality')) {
408 $ineligible[] = $kobold->getName();
409 } else {
410 $participantKobolds[] = $kobold;
411 }
412 }
413
414 if (!empty($ineligible)) {
415 $names = implode(', ', $ineligible);
416 throw new \Exception("These kobolds are too fatigued for this event: {$names}");
417 }
418
393 $event->setParticipants($participants);
419 $event->setParticipants($participants);
394
420
395 $event?->execute();
421 $event?->execute();
396 $story = $event?->getStory() ?? 'No event occurred.';
422 $story = $event?->getStory() ?? 'No event occurred.';
397
423
398 foreach ($participants as $participant) {
424 foreach ($participantKobolds as $kobold) {
399 if ($participant->isDead()) {
425 $kobold->addFatigue($cost);
400 $story = $story . "\n" . $participant->getName() . " has died.";
426 if ($kobold->isDead()) {
427 $story = $story . "\n" . $kobold->getName() . " has died.";
401 }
428 }
402 }
429 }
403
430
@@ -535,13 +562,14 @@ if ($method === 'POST') {
535 'stats' => [
562 'stats' => [
536 'vitality' => $kobold->getStat('vitality'),
563 'vitality' => $kobold->getStat('vitality'),
537 'intelligence' => $kobold->getStat('intelligence'),
564 'intelligence' => $kobold->getStat('intelligence'),
538 'tinkering' => $kobold->getStat('tinkering'),
539 'medicine' => $kobold->getStat('medicine'),
565 'medicine' => $kobold->getStat('medicine'),
540 'crafting' => $kobold->getStat('crafting'),
566 'crafting' => $kobold->getStat('crafting'),
541 'personality' => $kobold->getStat('personality'),
567 'personality' => $kobold->getStat('personality'),
542 'will' => $kobold->getStat('will'),
568 'will' => $kobold->getStat('will'),
543 'fighting' => $kobold->getStat('fighting')
569 'fighting' => $kobold->getStat('fighting')
544 ],
570 ],
571 'fatigue' => $kobold->getFatigue(),
572 'fatigue_label' => $kobold->getFatigueLabel(),
545 'items' => $kobold->getItems() ?? [],
573 'items' => $kobold->getItems() ?? [],
546 'injuries' => $kInjuries,
574 'injuries' => $kInjuries,
547 'male' => $kobold->getMale()
575 'male' => $kobold->getMale()
@@ -559,6 +587,7 @@ if ($method === 'POST') {
559 'current_month' => $tribe->getCurrentMonth(),
587 'current_month' => $tribe->getCurrentMonth(),
560 'current_season' => $tribe->getCurrentSeason(),
588 'current_season' => $tribe->getCurrentSeason(),
561 'food_count' => $tribe->getFoodCount(),
589 'food_count' => $tribe->getFoodCount(),
590 'food_months_remaining' => $tribe->foodMonthsLeft($tribe->getFoodCount()),
562 'created_at' => $tribe->getCreatedAt(),
591 'created_at' => $tribe->getCreatedAt(),
563 'last_played' => $tribe->getLastPlayed()
592 'last_played' => $tribe->getLastPlayed()
564 ],
593 ],
@@ -574,6 +603,48 @@ if ($method === 'POST') {
574 'error' => $e->getMessage()
603 'error' => $e->getMessage()
575 ]);
604 ]);
576 }
605 }
606 } elseif (strpos($apiPath, 'events') !== false) {
607 // List available events and their costs
608 try {
609 $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
610 $saveId = $_GET['saveId'] ?? null;
611
612 if (!$userId || !$saveId) {
613 throw new \Exception('User ID and Save ID required');
614 }
615
616 $tribe = Tribe::load($userId, $saveId);
617
618 $events = [];
619 foreach (get_declared_classes() as $className) {
620 if (!is_subclass_of($className, 'Event')) {
621 continue;
622 }
623
624 $event = new $className($tribe);
625 $type = preg_replace('/Event$/', '', $className);
626
627 $events[] = [
628 'type' => $type,
629 'name' => $type,
630 'cost' => $event->getCost(),
631 'available' => $event->isAvailable(),
632 'min_participants' => $event->getMinParticipants(),
633 'max_participants' => $event->getMaxParticipants()
634 ];
635 }
636
637 echo json_encode([
638 'success' => true,
639 'events' => $events
640 ]);
641 } catch (\Exception $e) {
642 http_response_code(400);
643 echo json_encode([
644 'success' => false,
645 'error' => $e->getMessage()
646 ]);
647 }
577 }
648 }
578}
649}
579
650