BlueGit

blue-star tribegen

injuries, cures, event edits

timfa Tim Falken · pushed by timfa

Authored 2026-01-28 · 9 months ago

Hash
146dd34281d0847065499dba39551fb95d06095d
Parent
c9349784
15 files changed +1447 −83
web/.github/copilot-instructions.md +94 −0
@@ -1,3 +1,97 @@
1 ```instructions
2 # TribeGen - AI Coding Agent Instructions
3
4 ## Architecture Overview
5
6 **TribeGen** is a browser-based strategy game where players manage a Kobold tribe. The codebase uses **file-based JSON storage** (refactored from SQLite) with PHP backends and vanilla JavaScript frontend.
7
8 ### Storage Architecture
9 - **Authentication**: SQLite database (users table only) — see [src/Database/Database.php](src/Database/Database.php)
10 - **Game State**: JSON files organized by user → save → entities (tribe, kobolds, items, NPCs)
11 - **SaveManager**: Single abstraction for all file I/O — see [src/System/SaveManager.php](src/System/SaveManager.php)
12 - Path pattern: `data/saves/{userId}/{saveId}/` containing `save.json`, `kobolds.json`, `items.json`, `npcs.json`
13
14 **Critical Pattern**: All game classes use `fromArray()/toArray()` for JSON serialization. Changes to class properties require updating both methods.
15
16 ### Core Entity Classes
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
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 4. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
21 5. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
22
23 ### Event System
24 - **Base Class**: `Event` — abstract execute() method that modifies tribe state and sets `$this->story`
25 - **EventManager** ([src/Events/EventManager.php](src/Events/EventManager.php)): Loads enabled events per save, executes them
26 - **Implementations**: [HuntingEvent](src/Events/HuntingEvent.php), [ExplorationEvent](src/Events/ExplorationEvent.php), [FarmingEvent](src/Events/FarmingEvent.php)
27 - **Creating New Events**: Extend `Event`, implement `execute()`, return narrative story via `$this->story`
28 - **Example**: [ExplorationEvent](src/Events/ExplorationEvent.php) — shows stat-based mechanics (intelligence affects food discovery, vitality reduces injury chance), food addition via `$tribe->addFood()`, and injury creation as array appended to kobold's injuries list
29
30 ## API Endpoints
31
32 All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `saveId` in POST body:
33
34 - **POST `/api/game/generation`**: Create new tribe with 20 random kobolds
35 - **POST `/api/game/load?saveId=X`**: Load tribe state
36 - **POST `/api/game/save`**: Save tribe setup (currently a TODO)
37 - **POST `/api/game/event`**: Execute single event
38 - **POST `/api/game/endMonth`**: Progress month, age kobolds, apply injuries, execute month events
39
40 **Pattern**: All responses use `{ success: boolean, error?: string, ...data }`
41
42 ## Key Conventions
43
44 ### IDs and Naming
45 - **User IDs**: Database `user.id` (integer)
46 - **Save IDs**: Numeric string generated by `SaveManager::generateSaveId()`
47 - **Kobold IDs**: Prefixed with `kob_` + uniqid (example: `kob_678abc123`)
48 - **Method Names**: Use camelCase, boolean getters are `is*()` or `get*()` followed by value
49
50 ### Stats System
51 - All stats are 0-100 internally, displayed as text ranges (0-10: "terrible", 90-100: "godlike")
52 - Stat checks: Get base value → apply item modifications → check result
53 - Items can boost/reduce any stat independently
54
55 ### Kobold Lifecycle
56 - **Age Tiers**: egg → baby → adult → old → very_old (affects food consumption and sprite)
57 - **Sprite Morphs**: Loaded from `assets/sprites/{morph}/` directory, copied to save folder on generation
58 - **Genetic Inheritance**: Each kobold tracks `fatherId`, `motherId` for generation tracking
59
60 ### Food System
61 - `Tribe::foodCount` tracks stored food
62 - Age tiers have food requirements (egg: 0, baby: 0.5, adult: 1.0, old: 0.6, very_old: 0.4 units)
63 - `endMonth()` deducts food and reports shortage via story
64
65 ## Development Workflow
66
67 1. **Loading Data**: `$tribe = Tribe::load($userId, $saveId);` — automatically loads kobolds, storage, items
68 2. **Modifying Tribe**: Add kobolds with `$tribe->addKobold($kobold)`, modify state, then `$tribe->save()` writes all JSON
69 3. **Adding Features**: Update entity class → add `fromArray()/toArray()` support → update API endpoint
70 4. **Testing Events**: Create event class extending `Event`, test via EventManager or direct instantiation
71
72 ## Common File Locations
73
74 | Purpose | File |
75 |---------|------|
76 | Database setup | [src/Database/Database.php](src/Database/Database.php) |
77 | User auth | [src/Classes/User.php](src/Classes/User.php), [src/api/auth.php](src/api/auth.php) |
78 | Game state | [src/Classes/Tribe.php](src/Classes/Tribe.php) |
79 | Kobold logic | [src/Classes/Kobold.php](src/Classes/Kobold.php) |
80 | Storage abstraction | [src/System/SaveManager.php](src/System/SaveManager.php) |
81 | Game routes | [src/api/game.php](src/api/game.php) |
82 | Frontend | [public/js/app.js](public/js/app.js), [public/index.html](public/index.html) |
83
84 ## Documentation References
85
86 - **Architecture Details**: [ARCHITECTURE.md](ARCHITECTURE.md) — database schema, class hierarchy, API flow
87 - **Quick Reference**: [QUICK_REFERENCE.md](QUICK_REFERENCE.md) — refactoring summary, file changes
88 - **Getting Started**: [README.md](README.md) — installation, features, event creation guide
89
90 ## Important Storage Policy
91
92 - **Only user accounts are stored in the database.** All other game data (saves, kobolds, items, NPCs, injuries, etc.) MUST be stored as JSON files under `data/saves/{userId}/{saveId}`. If any code creates or attempts to use database tables other than `users`, that is a bug and should be changed to use the file-based JSON storage.
93
94 ```
1 95 # TribeGen - AI Coding Agent Instructions
2 96
3 97 ## Architecture Overview
@@ -1,3 +1,97 @@
1```instructions
2# TribeGen - AI Coding Agent Instructions
3
4## Architecture Overview
5
6**TribeGen** is a browser-based strategy game where players manage a Kobold tribe. The codebase uses **file-based JSON storage** (refactored from SQLite) with PHP backends and vanilla JavaScript frontend.
7
8### Storage Architecture
9- **Authentication**: SQLite database (users table only) — see [src/Database/Database.php](src/Database/Database.php)
10- **Game State**: JSON files organized by user → save → entities (tribe, kobolds, items, NPCs)
11- **SaveManager**: Single abstraction for all file I/O — see [src/System/SaveManager.php](src/System/SaveManager.php)
12 - Path pattern: `data/saves/{userId}/{saveId}/` containing `save.json`, `kobolds.json`, `items.json`, `npcs.json`
13
14**Critical Pattern**: All game classes use `fromArray()/toArray()` for JSON serialization. Changes to class properties require updating both methods.
15
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
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
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)
215. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
22
23### Event System
24- **Base Class**: `Event` — abstract execute() method that modifies tribe state and sets `$this->story`
25- **EventManager** ([src/Events/EventManager.php](src/Events/EventManager.php)): Loads enabled events per save, executes them
26- **Implementations**: [HuntingEvent](src/Events/HuntingEvent.php), [ExplorationEvent](src/Events/ExplorationEvent.php), [FarmingEvent](src/Events/FarmingEvent.php)
27- **Creating New Events**: Extend `Event`, implement `execute()`, return narrative story via `$this->story`
28- **Example**: [ExplorationEvent](src/Events/ExplorationEvent.php) — shows stat-based mechanics (intelligence affects food discovery, vitality reduces injury chance), food addition via `$tribe->addFood()`, and injury creation as array appended to kobold's injuries list
29
30## API Endpoints
31
32All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `saveId` in POST body:
33
34- **POST `/api/game/generation`**: Create new tribe with 20 random kobolds
35- **POST `/api/game/load?saveId=X`**: Load tribe state
36- **POST `/api/game/save`**: Save tribe setup (currently a TODO)
37- **POST `/api/game/event`**: Execute single event
38- **POST `/api/game/endMonth`**: Progress month, age kobolds, apply injuries, execute month events
39
40**Pattern**: All responses use `{ success: boolean, error?: string, ...data }`
41
42## Key Conventions
43
44### IDs and Naming
45- **User IDs**: Database `user.id` (integer)
46- **Save IDs**: Numeric string generated by `SaveManager::generateSaveId()`
47- **Kobold IDs**: Prefixed with `kob_` + uniqid (example: `kob_678abc123`)
48- **Method Names**: Use camelCase, boolean getters are `is*()` or `get*()` followed by value
49
50### Stats System
51- All stats are 0-100 internally, displayed as text ranges (0-10: "terrible", 90-100: "godlike")
52- Stat checks: Get base value → apply item modifications → check result
53- Items can boost/reduce any stat independently
54
55### Kobold Lifecycle
56- **Age Tiers**: egg → baby → adult → old → very_old (affects food consumption and sprite)
57- **Sprite Morphs**: Loaded from `assets/sprites/{morph}/` directory, copied to save folder on generation
58- **Genetic Inheritance**: Each kobold tracks `fatherId`, `motherId` for generation tracking
59
60### Food System
61- `Tribe::foodCount` tracks stored food
62- Age tiers have food requirements (egg: 0, baby: 0.5, adult: 1.0, old: 0.6, very_old: 0.4 units)
63- `endMonth()` deducts food and reports shortage via story
64
65## Development Workflow
66
671. **Loading Data**: `$tribe = Tribe::load($userId, $saveId);` — automatically loads kobolds, storage, items
682. **Modifying Tribe**: Add kobolds with `$tribe->addKobold($kobold)`, modify state, then `$tribe->save()` writes all JSON
693. **Adding Features**: Update entity class → add `fromArray()/toArray()` support → update API endpoint
704. **Testing Events**: Create event class extending `Event`, test via EventManager or direct instantiation
71
72## Common File Locations
73
74| Purpose | File |
75|---------|------|
76| Database setup | [src/Database/Database.php](src/Database/Database.php) |
77| User auth | [src/Classes/User.php](src/Classes/User.php), [src/api/auth.php](src/api/auth.php) |
78| Game state | [src/Classes/Tribe.php](src/Classes/Tribe.php) |
79| Kobold logic | [src/Classes/Kobold.php](src/Classes/Kobold.php) |
80| Storage abstraction | [src/System/SaveManager.php](src/System/SaveManager.php) |
81| Game routes | [src/api/game.php](src/api/game.php) |
82| Frontend | [public/js/app.js](public/js/app.js), [public/index.html](public/index.html) |
83
84## Documentation References
85
86- **Architecture Details**: [ARCHITECTURE.md](ARCHITECTURE.md) — database schema, class hierarchy, API flow
87- **Quick Reference**: [QUICK_REFERENCE.md](QUICK_REFERENCE.md) — refactoring summary, file changes
88- **Getting Started**: [README.md](README.md) — installation, features, event creation guide
89
90## Important Storage Policy
91
92- **Only user accounts are stored in the database.** All other game data (saves, kobolds, items, NPCs, injuries, etc.) MUST be stored as JSON files under `data/saves/{userId}/{saveId}`. If any code creates or attempts to use database tables other than `users`, that is a bug and should be changed to use the file-based JSON storage.
93
94```
1# TribeGen - AI Coding Agent Instructions
95# TribeGen - AI Coding Agent Instructions
2
96
3## Architecture Overview
97## Architecture Overview
web/assets/injuries/brokenLeg.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "injuryType": "Broken Leg",
3 "description": "The bone in its leg is fractured, hindering movement and causing pain.",
4 "category": "fracture",
5 "severity": 4,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "tinkering": -2,
10 "medicine": 0,
11 "crafting": -3,
12 "personality": -1,
13 "will": -2
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "injuryType": "Broken Leg",
3 "description": "The bone in its leg is fractured, hindering movement and causing pain.",
4 "category": "fracture",
5 "severity": 4,
6 "statModifications": {
7 "vitality": -4,
8 "intelligence": 0,
9 "tinkering": -2,
10 "medicine": 0,
11 "crafting": -3,
12 "personality": -1,
13 "will": -2
14 }
15}
web/assets/items/bone-setting.json added +14 −0
@@ -0,0 +1,14 @@
1 {
2 "name": "Splint",
3 "description": "A wooden item that can help set bones to cure fractures.",
4 "itemType": "medicine",
5 "statModifications": {
6 "vitality": 0,
7 "intelligence": 0,
8 "tinkering": 0,
9 "medicine": 1,
10 "crafting": 0,
11 "personality": 0,
12 "will": 0
13 }
14 }
@@ -0,0 +1,14 @@
1{
2 "name": "Splint",
3 "description": "A wooden item that can help set bones to cure fractures.",
4 "itemType": "medicine",
5 "statModifications": {
6 "vitality": 0,
7 "intelligence": 0,
8 "tinkering": 0,
9 "medicine": 1,
10 "crafting": 0,
11 "personality": 0,
12 "will": 0
13 }
14}
web/assets/items/book.json added +15 −0
@@ -0,0 +1,15 @@
1 {
2 "name": "Encyclopedia",
3 "description": "A large book containing information about flora and fauna, which can help with exploration and hunting.",
4 "itemType": "book",
5 "statModifications":
6 {
7 "vitality": 0,
8 "intelligence": 3,
9 "tinkering": 0,
10 "medicine": 2,
11 "crafting": 0,
12 "personality": -1,
13 "will": 0
14 }
15 }
@@ -0,0 +1,15 @@
1{
2 "name": "Encyclopedia",
3 "description": "A large book containing information about flora and fauna, which can help with exploration and hunting.",
4 "itemType": "book",
5 "statModifications":
6 {
7 "vitality": 0,
8 "intelligence": 3,
9 "tinkering": 0,
10 "medicine": 2,
11 "crafting": 0,
12 "personality": -1,
13 "will": 0
14 }
15}
web/css/style.css +260 −0
@@ -499,6 +499,266 @@ button {
499 499 white-space: pre-wrap;
500 500 }
501 501
502 /* Storage Window */
503 .storage-header {
504 margin-bottom: 15px;
505 padding-bottom: 10px;
506 border-bottom: 1px solid #eee;
507 }
508
509 .food-display {
510 font-size: 1.1em;
511 font-weight: bold;
512 color: #667eea;
513 }
514
515 .storage-items {
516 display: flex;
517 flex-direction: column;
518 gap: 8px;
519 max-height: 200px;
520 overflow-y: auto;
521 }
522
523 .storage-item {
524 padding: 10px;
525 background: #f9f9f9;
526 border-radius: 5px;
527 cursor: pointer;
528 transition: all 0.2s;
529 }
530
531 .storage-item:hover {
532 background: #efe;
533 transform: translateX(5px);
534 }
535
536 .storage-item-name {
537 font-weight: bold;
538 color: #333;
539 }
540
541 /* Item Modal */
542 .item-modal {
543 max-width: 400px;
544 }
545
546 .item-modal-header {
547 margin-bottom: 15px;
548 border-bottom: 2px solid #667eea;
549 padding-bottom: 10px;
550 }
551
552 .item-modal-header h2 {
553 color: #667eea;
554 margin: 0;
555 }
556
557 .item-description {
558 margin-bottom: 15px;
559 line-height: 1.5;
560 color: #555;
561 }
562
563 .item-stat-mods {
564 margin-bottom: 15px;
565 padding: 10px;
566 background: #f5f5f5;
567 border-radius: 5px;
568 }
569
570 .stat-mod {
571 display: flex;
572 justify-content: space-between;
573 padding: 5px 0;
574 font-size: 0.9em;
575 }
576
577 .stat-mod.positive {
578 color: #28a745;
579 }
580
581 .stat-mod.negative {
582 color: #dc3545;
583 }
584
585 .stat-mod.neutral {
586 color: #999;
587 }
588
589 .item-modal-actions {
590 display: flex;
591 flex-direction: column;
592 gap: 10px;
593 }
594
595 .kobold-select {
596 padding: 10px;
597 border: 1px solid #ddd;
598 border-radius: 5px;
599 font-size: 1em;
600 }
601
602 #giveItemBtn:disabled {
603 opacity: 0.5;
604 cursor: not-allowed;
605 }
606
607 /* Kobold Modal */
608 .kobold-modal {
609 max-width: 500px;
610 max-height: 80vh;
611 overflow-y: auto;
612 }
613
614 .kobold-modal-header {
615 margin-bottom: 15px;
616 border-bottom: 2px solid #667eea;
617 padding-bottom: 10px;
618 }
619
620 .kobold-modal-header h2 {
621 color: #667eea;
622 margin: 0 0 5px 0;
623 }
624
625 .kobold-age {
626 color: #999;
627 margin: 0;
628 font-size: 0.9em;
629 }
630
631 .kobold-description {
632 margin-bottom: 15px;
633 line-height: 1.5;
634 color: #555;
635 }
636
637 .kobold-tabs {
638 display: flex;
639 gap: 10px;
640 margin-bottom: 15px;
641 border-bottom: 1px solid #eee;
642 }
643
644 .kobold-tab-btn {
645 padding: 10px 15px;
646 background: none;
647 border: none;
648 cursor: pointer;
649 font-size: 1em;
650 color: #999;
651 border-bottom: 3px solid transparent;
652 transition: all 0.3s;
653 }
654
655 .kobold-tab-btn.active {
656 color: #667eea;
657 border-bottom-color: #667eea;
658 }
659
660 .kobold-tab-btn:hover {
661 color: #667eea;
662 }
663
664 .kobold-tab-content {
665 display: none;
666 }
667
668 .kobold-tab-content.active {
669 display: block;
670 }
671
672 .kobold-stats-grid {
673 display: grid;
674 grid-template-columns: 1fr 1fr;
675 gap: 10px;
676 }
677
678 .stat-item {
679 padding: 10px;
680 background: #f9f9f9;
681 border-radius: 5px;
682 }
683
684 .stat-name {
685 font-weight: bold;
686 color: #333;
687 font-size: 0.85em;
688 text-transform: capitalize;
689 }
690
691 .stat-value {
692 color: #667eea;
693 font-size: 1.2em;
694 margin-top: 5px;
695 }
696
697 .stat-label {
698 color: #999;
699 font-size: 0.75em;
700 }
701
702 .kobold-inventory-list {
703 display: flex;
704 flex-direction: column;
705 gap: 8px;
706 }
707
708 .kobold-inventory-item {
709 padding: 10px;
710 background: #f9f9f9;
711 border-radius: 5px;
712 cursor: pointer;
713 transition: all 0.2s;
714 }
715
716 .kobold-inventory-item:hover {
717 background: #fef;
718 transform: translateX(5px);
719 }
720
721 .kobold-item-name {
722 font-weight: bold;
723 color: #333;
724 }
725
726 .kobold-inventory-empty {
727 padding: 20px;
728 text-align: center;
729 color: #999;
730 font-style: italic;
731 }
732
733 .kobold-injuries-list {
734 display: flex;
735 flex-direction: column;
736 gap: 8px;
737 }
738
739 .injury-item {
740 padding: 10px;
741 background: #fff7f7;
742 border: 1px solid #f2dede;
743 border-radius: 5px;
744 }
745
746 .injury-name {
747 font-weight: bold;
748 color: #b94a48;
749 }
750
751 .injury-desc {
752 color: #666;
753 font-size: 0.95em;
754 }
755
756 .injury-actions {
757 margin-top: 8px;
758 display: flex;
759 gap: 8px;
760 }
761
502 762 /* Config Screen */
503 763 .config-container {
504 764 background: white;
@@ -499,6 +499,266 @@ button {
499 white-space: pre-wrap;
499 white-space: pre-wrap;
500}
500}
501
501
502/* Storage Window */
503.storage-header {
504 margin-bottom: 15px;
505 padding-bottom: 10px;
506 border-bottom: 1px solid #eee;
507}
508
509.food-display {
510 font-size: 1.1em;
511 font-weight: bold;
512 color: #667eea;
513}
514
515.storage-items {
516 display: flex;
517 flex-direction: column;
518 gap: 8px;
519 max-height: 200px;
520 overflow-y: auto;
521}
522
523.storage-item {
524 padding: 10px;
525 background: #f9f9f9;
526 border-radius: 5px;
527 cursor: pointer;
528 transition: all 0.2s;
529}
530
531.storage-item:hover {
532 background: #efe;
533 transform: translateX(5px);
534}
535
536.storage-item-name {
537 font-weight: bold;
538 color: #333;
539}
540
541/* Item Modal */
542.item-modal {
543 max-width: 400px;
544}
545
546.item-modal-header {
547 margin-bottom: 15px;
548 border-bottom: 2px solid #667eea;
549 padding-bottom: 10px;
550}
551
552.item-modal-header h2 {
553 color: #667eea;
554 margin: 0;
555}
556
557.item-description {
558 margin-bottom: 15px;
559 line-height: 1.5;
560 color: #555;
561}
562
563.item-stat-mods {
564 margin-bottom: 15px;
565 padding: 10px;
566 background: #f5f5f5;
567 border-radius: 5px;
568}
569
570.stat-mod {
571 display: flex;
572 justify-content: space-between;
573 padding: 5px 0;
574 font-size: 0.9em;
575}
576
577.stat-mod.positive {
578 color: #28a745;
579}
580
581.stat-mod.negative {
582 color: #dc3545;
583}
584
585.stat-mod.neutral {
586 color: #999;
587}
588
589.item-modal-actions {
590 display: flex;
591 flex-direction: column;
592 gap: 10px;
593}
594
595.kobold-select {
596 padding: 10px;
597 border: 1px solid #ddd;
598 border-radius: 5px;
599 font-size: 1em;
600}
601
602#giveItemBtn:disabled {
603 opacity: 0.5;
604 cursor: not-allowed;
605}
606
607/* Kobold Modal */
608.kobold-modal {
609 max-width: 500px;
610 max-height: 80vh;
611 overflow-y: auto;
612}
613
614.kobold-modal-header {
615 margin-bottom: 15px;
616 border-bottom: 2px solid #667eea;
617 padding-bottom: 10px;
618}
619
620.kobold-modal-header h2 {
621 color: #667eea;
622 margin: 0 0 5px 0;
623}
624
625.kobold-age {
626 color: #999;
627 margin: 0;
628 font-size: 0.9em;
629}
630
631.kobold-description {
632 margin-bottom: 15px;
633 line-height: 1.5;
634 color: #555;
635}
636
637.kobold-tabs {
638 display: flex;
639 gap: 10px;
640 margin-bottom: 15px;
641 border-bottom: 1px solid #eee;
642}
643
644.kobold-tab-btn {
645 padding: 10px 15px;
646 background: none;
647 border: none;
648 cursor: pointer;
649 font-size: 1em;
650 color: #999;
651 border-bottom: 3px solid transparent;
652 transition: all 0.3s;
653}
654
655.kobold-tab-btn.active {
656 color: #667eea;
657 border-bottom-color: #667eea;
658}
659
660.kobold-tab-btn:hover {
661 color: #667eea;
662}
663
664.kobold-tab-content {
665 display: none;
666}
667
668.kobold-tab-content.active {
669 display: block;
670}
671
672.kobold-stats-grid {
673 display: grid;
674 grid-template-columns: 1fr 1fr;
675 gap: 10px;
676}
677
678.stat-item {
679 padding: 10px;
680 background: #f9f9f9;
681 border-radius: 5px;
682}
683
684.stat-name {
685 font-weight: bold;
686 color: #333;
687 font-size: 0.85em;
688 text-transform: capitalize;
689}
690
691.stat-value {
692 color: #667eea;
693 font-size: 1.2em;
694 margin-top: 5px;
695}
696
697.stat-label {
698 color: #999;
699 font-size: 0.75em;
700}
701
702.kobold-inventory-list {
703 display: flex;
704 flex-direction: column;
705 gap: 8px;
706}
707
708.kobold-inventory-item {
709 padding: 10px;
710 background: #f9f9f9;
711 border-radius: 5px;
712 cursor: pointer;
713 transition: all 0.2s;
714}
715
716.kobold-inventory-item:hover {
717 background: #fef;
718 transform: translateX(5px);
719}
720
721.kobold-item-name {
722 font-weight: bold;
723 color: #333;
724}
725
726.kobold-inventory-empty {
727 padding: 20px;
728 text-align: center;
729 color: #999;
730 font-style: italic;
731}
732
733.kobold-injuries-list {
734 display: flex;
735 flex-direction: column;
736 gap: 8px;
737}
738
739.injury-item {
740 padding: 10px;
741 background: #fff7f7;
742 border: 1px solid #f2dede;
743 border-radius: 5px;
744}
745
746.injury-name {
747 font-weight: bold;
748 color: #b94a48;
749}
750
751.injury-desc {
752 color: #666;
753 font-size: 0.95em;
754}
755
756.injury-actions {
757 margin-top: 8px;
758 display: flex;
759 gap: 8px;
760}
761
502/* Config Screen */
762/* Config Screen */
503.config-container {
763.config-container {
504 background: white;
764 background: white;
web/indexHtml.html +52 −0
@@ -108,6 +108,14 @@
108 108 <div id="eventsList" class="events-list"></div>
109 109 </div>
110 110
111 <div class="panel">
112 <h3>Tribe Storage</h3>
113 <div class="storage-header">
114 <div id="foodDisplay" class="food-display">Food: 0</div>
115 </div>
116 <div id="storageItems" class="storage-items"></div>
117 </div>
118
111 119 <div class="panel">
112 120 <h3>Tribe Members</h3>
113 121 <div id="tribeList" class="tribe-list"></div>
@@ -125,6 +133,50 @@
125 133 <button id="eventContinueBtn" class="primary">Continue</button>
126 134 </div>
127 135 </div>
136
137 <!-- Item Modal -->
138 <div id="itemModal" class="modal hidden">
139 <div class="modal-content item-modal">
140 <button class="modal-close">&times;</button>
141 <div class="item-modal-header">
142 <h2 id="itemModalName"></h2>
143 </div>
144 <div id="itemModalDescription" class="item-description"></div>
145 <div id="itemModalStatMods" class="item-stat-mods"></div>
146 <div class="item-modal-actions">
147 <select id="itemKoboldSelect" class="kobold-select">
148 <option value="">Select a Kobold...</option>
149 </select>
150 <button id="giveItemBtn" class="primary" disabled>Give Item</button>
151 </div>
152 </div>
153 </div>
154
155 <!-- Kobold Detail Modal -->
156 <div id="koboldModal" class="modal hidden">
157 <div class="modal-content kobold-modal">
158 <button class="modal-close">&times;</button>
159 <div class="kobold-modal-header">
160 <h2 id="koboldModalName"></h2>
161 <p id="koboldModalAge" class="kobold-age"></p>
162 </div>
163 <div id="koboldModalDescription" class="kobold-description"></div>
164 <div class="kobold-tabs">
165 <button class="kobold-tab-btn active" data-tab="stats">Stats</button>
166 <button class="kobold-tab-btn" data-tab="inventory">Inventory</button>
167 <button class="kobold-tab-btn" data-tab="injuries">Injuries</button>
168 </div>
169 <div id="koboldStatsTab" class="kobold-tab-content active">
170 <div id="koboldStats" class="kobold-stats-grid"></div>
171 </div>
172 <div id="koboldInventoryTab" class="kobold-tab-content">
173 <div id="koboldInventory" class="kobold-inventory-list"></div>
174 </div>
175 <div id="koboldInjuriesTab" class="kobold-tab-content">
176 <div id="koboldInjuries" class="kobold-injuries-list"></div>
177 </div>
178 </div>
179 </div>
128 180 </div>
129 181
130 182 <!-- Config Screen -->
@@ -108,6 +108,14 @@
108 <div id="eventsList" class="events-list"></div>
108 <div id="eventsList" class="events-list"></div>
109 </div>
109 </div>
110
110
111 <div class="panel">
112 <h3>Tribe Storage</h3>
113 <div class="storage-header">
114 <div id="foodDisplay" class="food-display">Food: 0</div>
115 </div>
116 <div id="storageItems" class="storage-items"></div>
117 </div>
118
111 <div class="panel">
119 <div class="panel">
112 <h3>Tribe Members</h3>
120 <h3>Tribe Members</h3>
113 <div id="tribeList" class="tribe-list"></div>
121 <div id="tribeList" class="tribe-list"></div>
@@ -125,6 +133,50 @@
125 <button id="eventContinueBtn" class="primary">Continue</button>
133 <button id="eventContinueBtn" class="primary">Continue</button>
126 </div>
134 </div>
127 </div>
135 </div>
136
137 <!-- Item Modal -->
138 <div id="itemModal" class="modal hidden">
139 <div class="modal-content item-modal">
140 <button class="modal-close">&times;</button>
141 <div class="item-modal-header">
142 <h2 id="itemModalName"></h2>
143 </div>
144 <div id="itemModalDescription" class="item-description"></div>
145 <div id="itemModalStatMods" class="item-stat-mods"></div>
146 <div class="item-modal-actions">
147 <select id="itemKoboldSelect" class="kobold-select">
148 <option value="">Select a Kobold...</option>
149 </select>
150 <button id="giveItemBtn" class="primary" disabled>Give Item</button>
151 </div>
152 </div>
153 </div>
154
155 <!-- Kobold Detail Modal -->
156 <div id="koboldModal" class="modal hidden">
157 <div class="modal-content kobold-modal">
158 <button class="modal-close">&times;</button>
159 <div class="kobold-modal-header">
160 <h2 id="koboldModalName"></h2>
161 <p id="koboldModalAge" class="kobold-age"></p>
162 </div>
163 <div id="koboldModalDescription" class="kobold-description"></div>
164 <div class="kobold-tabs">
165 <button class="kobold-tab-btn active" data-tab="stats">Stats</button>
166 <button class="kobold-tab-btn" data-tab="inventory">Inventory</button>
167 <button class="kobold-tab-btn" data-tab="injuries">Injuries</button>
168 </div>
169 <div id="koboldStatsTab" class="kobold-tab-content active">
170 <div id="koboldStats" class="kobold-stats-grid"></div>
171 </div>
172 <div id="koboldInventoryTab" class="kobold-tab-content">
173 <div id="koboldInventory" class="kobold-inventory-list"></div>
174 </div>
175 <div id="koboldInjuriesTab" class="kobold-tab-content">
176 <div id="koboldInjuries" class="kobold-injuries-list"></div>
177 </div>
178 </div>
179 </div>
128 </div>
180 </div>
129
181
130 <!-- Config Screen -->
182 <!-- Config Screen -->
web/js/app.js +396 −4
@@ -2,7 +2,7 @@ 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;
@@ -40,8 +40,16 @@ class TribeGenApp
40 40 // Game Screen
41 41 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
42 42
43 // Modal
44 document.querySelector('.modal-close').addEventListener('click', () => this.hideEventModal());
43 // Modal close buttons
44 document.querySelectorAll('.modal-close').forEach(btn =>
45 {
46 btn.addEventListener('click', (e) =>
47 {
48 const modal = e.target.closest('.modal');
49 if (modal) modal.classList.add('hidden');
50 });
51 });
52
45 53 document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal());
46 54 }
47 55
@@ -391,7 +399,7 @@ class TribeGenApp
391 399 {
392 400 try
393 401 {
394 const response = await fetch(`api/game/load?saveId=${saveId}`, {
402 const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, {
395 403 method: 'GET',
396 404 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
397 405 });
@@ -424,6 +432,7 @@ class TribeGenApp
424 432 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
425 433 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
426 434
435 this.renderStorage();
427 436 this.renderTribeList();
428 437 this.renderEvents();
429 438 }
@@ -443,6 +452,7 @@ class TribeGenApp
443 452 <div class="tribe-item-age">${kobold.age} years</div>
444 453 </div>
445 454 `;
455 item.addEventListener('click', () => this.showKoboldModal(kobold));
446 456 list.appendChild(item);
447 457 });
448 458 }
@@ -538,6 +548,388 @@ class TribeGenApp
538 548 this.renderGame();
539 549 }
540 550
551 renderStorage ()
552 {
553 const foodDisplay = document.getElementById('foodDisplay');
554 foodDisplay.textContent = `Food: ${this.currentSave.food_count}`;
555
556 const storageItems = document.getElementById('storageItems');
557 storageItems.innerHTML = '';
558
559 if (!this.currentTribe.storage || this.currentTribe.storage.length === 0)
560 {
561 storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>';
562 return;
563 }
564
565 this.currentTribe.storage.forEach(item =>
566 {
567 const itemEl = document.createElement('div');
568 itemEl.className = 'storage-item';
569 itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`;
570 itemEl.addEventListener('click', () => this.showItemModal(item));
571 storageItems.appendChild(itemEl);
572 });
573 }
574
575 showItemModal (item)
576 {
577 const modal = document.getElementById('itemModal');
578 document.getElementById('itemModalName').textContent = item.name;
579 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
580
581 // Show stat modifications (handle both camelCase and snake_case)
582 const statMods = document.getElementById('itemModalStatMods');
583 statMods.innerHTML = '';
584
585 const modifications = item.stat_modifications || item.statModifications || {};
586 if (Object.keys(modifications).length > 0)
587 {
588 Object.entries(modifications).forEach(([stat, value]) =>
589 {
590 if (value !== 0)
591 {
592 const modEl = document.createElement('div');
593 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
594 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
595 statMods.appendChild(modEl);
596 }
597 });
598 } else
599 {
600 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
601 }
602
603 // Restore item modal actions to storage version
604 const actions = document.querySelector('.item-modal-actions');
605 actions.innerHTML = '';
606
607 const select = document.createElement('select');
608 select.id = 'itemKoboldSelect';
609 select.className = 'kobold-select';
610 select.innerHTML = '<option value="">Select a Kobold...</option>';
611 this.currentTribe.kobolds.forEach(kobold =>
612 {
613 const option = document.createElement('option');
614 option.value = kobold.id;
615 option.textContent = kobold.name;
616 select.appendChild(option);
617 });
618
619 const giveBtn = document.createElement('button');
620 giveBtn.id = 'giveItemBtn';
621 giveBtn.className = 'primary';
622 giveBtn.textContent = 'Give Item';
623 giveBtn.disabled = true;
624
625 select.addEventListener('change', (e) =>
626 {
627 giveBtn.disabled = !e.target.value;
628 });
629
630 giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value));
631
632 actions.appendChild(select);
633 actions.appendChild(giveBtn);
634
635 modal.classList.remove('hidden');
636 }
637
638 async giveItemToKobold (item, koboldId)
639 {
640 try
641 {
642 const resp = await fetch('api/game/giveItem', {
643 method: 'POST',
644 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
645 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
646 });
647
648 const data = await resp.json();
649 if (data.success)
650 {
651 typeText(document.getElementById('eventStory'), data.story);
652 this.showEventModal();
653 // Refresh game state
654 await this.loadGame(this.currentSave.id);
655 const kob = this.currentTribe.kobolds.find(k => k.id === koboldId);
656 if (kob) this.showKoboldModal(kob);
657 } else
658 {
659 alert(data.error || 'Failed to give item');
660 }
661 } catch (err)
662 {
663 console.error(err);
664 alert('Failed to give item');
665 } finally
666 {
667 this.hideItemModal();
668 }
669 }
670
671 hideItemModal ()
672 {
673 document.getElementById('itemModal').classList.add('hidden');
674 }
675
676 showKoboldModal (kobold)
677 {
678 const modal = document.getElementById('koboldModal');
679 document.getElementById('koboldModalName').textContent = kobold.name;
680 document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`;
681 document.getElementById('koboldModalDescription').textContent = `A ${kobold.ageCategory} Kobold`;
682
683 this.renderKoboldStats(kobold);
684 this.renderKoboldInventory(kobold);
685 this.renderKoboldInjuries(kobold);
686
687 // Setup tab buttons
688 document.querySelectorAll('.kobold-tab-btn').forEach(btn =>
689 {
690 btn.classList.remove('active');
691 btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab));
692 });
693 document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active');
694
695 // Hide all tabs
696 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
697 document.getElementById('koboldStatsTab').classList.add('active');
698
699 // Store current kobold for inventory actions
700 this.selectedKobold = kobold;
701
702 modal.classList.remove('hidden');
703 }
704
705 renderKoboldStats (kobold)
706 {
707 const statsGrid = document.getElementById('koboldStats');
708 statsGrid.innerHTML = '';
709
710 const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will'];
711 stats.forEach(stat =>
712 {
713 const value = kobold.stats[stat];
714 const label = this.getStatLabel(value);
715 const statEl = document.createElement('div');
716 statEl.className = 'stat-item';
717 statEl.innerHTML = `
718 <div class="stat-name">${stat}</div>
719 <div class="stat-value">${value}</div>
720 <div class="stat-label">${label}</div>
721 `;
722 statsGrid.appendChild(statEl);
723 });
724 }
725
726 renderKoboldInventory (kobold)
727 {
728 const inventory = document.getElementById('koboldInventory');
729 inventory.innerHTML = '';
730
731 if (!kobold.items || kobold.items.length === 0)
732 {
733 inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>';
734 return;
735 }
736
737 kobold.items.forEach(item =>
738 {
739 const itemEl = document.createElement('div');
740 itemEl.className = 'kobold-inventory-item';
741 itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`;
742 itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold));
743 inventory.appendChild(itemEl);
744 });
745 }
746
747 renderKoboldInjuries (kobold)
748 {
749 const container = document.getElementById('koboldInjuries');
750 container.innerHTML = '';
751
752 if (!kobold.injuries || kobold.injuries.length === 0)
753 {
754 container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>';
755 return;
756 }
757
758 kobold.injuries.forEach(injury =>
759 {
760 const el = document.createElement('div');
761 el.className = 'injury-item';
762 const name = injury.injury_type || injury.injuryType || 'Injury';
763 const desc = injury.description || '';
764 const severity = injury.severity ?? injury.severity ?? 1;
765
766 el.innerHTML = `
767 <div class="injury-name">${name} (Severity: ${severity})</div>
768 <div class="injury-desc">${desc}</div>
769 `;
770
771 const actions = document.createElement('div');
772 actions.className = 'injury-actions';
773
774 // malnourished has no cure button here
775 if (injury.category !== 'malnourished')
776 {
777 const required = injury.required_medicine || injury.requiredMedicine || null;
778 if (required)
779 {
780 // check if kobold has item with this id
781 const hasItem = (kobold.items || []).some(it => it.id === required);
782 if (hasItem)
783 {
784 const btn = document.createElement('button');
785 btn.className = 'primary';
786 btn.textContent = `Cure using ${required}`;
787 btn.addEventListener('click', async () =>
788 {
789 try
790 {
791 const resp = await fetch('api/game/cureInjury', {
792 method: 'POST',
793 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
794 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
795 });
796 const data = await resp.json();
797 if (data.success)
798 {
799 typeText(document.getElementById('eventStory'), data.story);
800 this.showEventModal();
801 // Refresh game state
802 await this.loadGame(this.currentSave.id);
803 // reopen kobold modal after refresh
804 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
805 if (refreshed) this.showKoboldModal(refreshed);
806 } else
807 {
808 alert(data.error || 'Failed to cure injury');
809 }
810 } catch (err)
811 {
812 console.error(err);
813 alert('Failed to cure injury');
814 }
815 });
816 actions.appendChild(btn);
817 } else
818 {
819 const note = document.createElement('div');
820 note.style.color = '#999';
821 note.textContent = `Needs: ${required}`;
822 actions.appendChild(note);
823 }
824 }
825 }
826
827 el.appendChild(actions);
828 container.appendChild(el);
829 });
830 }
831
832 showKoboldItemModal (item, kobold)
833 {
834 const modal = document.getElementById('itemModal');
835 document.getElementById('itemModalName').textContent = item.name;
836 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
837
838 // Show stat modifications (handle both camelCase and snake_case)
839 const statMods = document.getElementById('itemModalStatMods');
840 statMods.innerHTML = '';
841
842 const modifications = item.stat_modifications || item.statModifications || {};
843 if (Object.keys(modifications).length > 0)
844 {
845 Object.entries(modifications).forEach(([stat, value]) =>
846 {
847 if (value !== 0)
848 {
849 const modEl = document.createElement('div');
850 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
851 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
852 statMods.appendChild(modEl);
853 }
854 });
855 } else
856 {
857 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
858 }
859
860 // Change button to return item
861 const actions = document.querySelector('.item-modal-actions');
862 actions.innerHTML = '';
863
864 const returnBtn = document.createElement('button');
865 returnBtn.className = 'secondary';
866 returnBtn.textContent = 'Return to Storage';
867 returnBtn.addEventListener('click', () => this.returnItemToStorage(item, kobold));
868 actions.appendChild(returnBtn);
869
870 modal.classList.remove('hidden');
871 this.selectedKobold = kobold;
872 }
873
874 async returnItemToStorage (item, kobold)
875 {
876 try
877 {
878 const resp = await fetch('api/game/returnItem', {
879 method: 'POST',
880 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
881 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
882 });
883
884 const data = await resp.json();
885 if (data.success)
886 {
887 typeText(document.getElementById('eventStory'), data.story);
888 this.showEventModal();
889 // Refresh game state
890 await this.loadGame(this.currentSave.id);
891 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
892 if (refreshed) this.showKoboldModal(refreshed);
893 } else
894 {
895 alert(data.error || 'Failed to return item');
896 }
897 } catch (err)
898 {
899 console.error(err);
900 alert('Failed to return item');
901 } finally
902 {
903 this.hideItemModal();
904 }
905 }
906
907 switchKoboldTab (tabName)
908 {
909 // Hide all tabs
910 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
911 document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active'));
912
913 // Show selected tab
914 const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab';
915 document.getElementById(tabId).classList.add('active');
916 document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
917 }
918
919 getStatLabel (statValue)
920 {
921 if (statValue >= 90) return 'godlike';
922 if (statValue >= 80) return 'divine';
923 if (statValue >= 70) return 'master';
924 if (statValue >= 60) return 'fantastic';
925 if (statValue >= 50) return 'excellent';
926 if (statValue >= 40) return 'good';
927 if (statValue >= 30) return 'decent';
928 if (statValue >= 20) return 'unskilled';
929 if (statValue >= 10) return 'bad';
930 return 'terrible';
931 }
932
541 933 hideAll ()
542 934 {
543 935 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
@@ -2,7 +2,7 @@ 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;
@@ -40,8 +40,16 @@ class TribeGenApp
40 // Game Screen
40 // Game Screen
41 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
41 document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth());
42
42
43 // Modal
43 // Modal close buttons
44 document.querySelector('.modal-close').addEventListener('click', () => this.hideEventModal());
44 document.querySelectorAll('.modal-close').forEach(btn =>
45 {
46 btn.addEventListener('click', (e) =>
47 {
48 const modal = e.target.closest('.modal');
49 if (modal) modal.classList.add('hidden');
50 });
51 });
52
45 document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal());
53 document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal());
46 }
54 }
47
55
@@ -391,7 +399,7 @@ class TribeGenApp
391 {
399 {
392 try
400 try
393 {
401 {
394 const response = await fetch(`api/game/load?saveId=${saveId}`, {
402 const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, {
395 method: 'GET',
403 method: 'GET',
396 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
404 headers: { 'Authorization': `Bearer ${this.currentUser.token}` }
397 });
405 });
@@ -424,6 +432,7 @@ class TribeGenApp
424 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
432 document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`;
425 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
433 document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season);
426
434
435 this.renderStorage();
427 this.renderTribeList();
436 this.renderTribeList();
428 this.renderEvents();
437 this.renderEvents();
429 }
438 }
@@ -443,6 +452,7 @@ class TribeGenApp
443 <div class="tribe-item-age">${kobold.age} years</div>
452 <div class="tribe-item-age">${kobold.age} years</div>
444 </div>
453 </div>
445 `;
454 `;
455 item.addEventListener('click', () => this.showKoboldModal(kobold));
446 list.appendChild(item);
456 list.appendChild(item);
447 });
457 });
448 }
458 }
@@ -538,6 +548,388 @@ class TribeGenApp
538 this.renderGame();
548 this.renderGame();
539 }
549 }
540
550
551 renderStorage ()
552 {
553 const foodDisplay = document.getElementById('foodDisplay');
554 foodDisplay.textContent = `Food: ${this.currentSave.food_count}`;
555
556 const storageItems = document.getElementById('storageItems');
557 storageItems.innerHTML = '';
558
559 if (!this.currentTribe.storage || this.currentTribe.storage.length === 0)
560 {
561 storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>';
562 return;
563 }
564
565 this.currentTribe.storage.forEach(item =>
566 {
567 const itemEl = document.createElement('div');
568 itemEl.className = 'storage-item';
569 itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`;
570 itemEl.addEventListener('click', () => this.showItemModal(item));
571 storageItems.appendChild(itemEl);
572 });
573 }
574
575 showItemModal (item)
576 {
577 const modal = document.getElementById('itemModal');
578 document.getElementById('itemModalName').textContent = item.name;
579 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
580
581 // Show stat modifications (handle both camelCase and snake_case)
582 const statMods = document.getElementById('itemModalStatMods');
583 statMods.innerHTML = '';
584
585 const modifications = item.stat_modifications || item.statModifications || {};
586 if (Object.keys(modifications).length > 0)
587 {
588 Object.entries(modifications).forEach(([stat, value]) =>
589 {
590 if (value !== 0)
591 {
592 const modEl = document.createElement('div');
593 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
594 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
595 statMods.appendChild(modEl);
596 }
597 });
598 } else
599 {
600 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
601 }
602
603 // Restore item modal actions to storage version
604 const actions = document.querySelector('.item-modal-actions');
605 actions.innerHTML = '';
606
607 const select = document.createElement('select');
608 select.id = 'itemKoboldSelect';
609 select.className = 'kobold-select';
610 select.innerHTML = '<option value="">Select a Kobold...</option>';
611 this.currentTribe.kobolds.forEach(kobold =>
612 {
613 const option = document.createElement('option');
614 option.value = kobold.id;
615 option.textContent = kobold.name;
616 select.appendChild(option);
617 });
618
619 const giveBtn = document.createElement('button');
620 giveBtn.id = 'giveItemBtn';
621 giveBtn.className = 'primary';
622 giveBtn.textContent = 'Give Item';
623 giveBtn.disabled = true;
624
625 select.addEventListener('change', (e) =>
626 {
627 giveBtn.disabled = !e.target.value;
628 });
629
630 giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value));
631
632 actions.appendChild(select);
633 actions.appendChild(giveBtn);
634
635 modal.classList.remove('hidden');
636 }
637
638 async giveItemToKobold (item, koboldId)
639 {
640 try
641 {
642 const resp = await fetch('api/game/giveItem', {
643 method: 'POST',
644 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
645 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id })
646 });
647
648 const data = await resp.json();
649 if (data.success)
650 {
651 typeText(document.getElementById('eventStory'), data.story);
652 this.showEventModal();
653 // Refresh game state
654 await this.loadGame(this.currentSave.id);
655 const kob = this.currentTribe.kobolds.find(k => k.id === koboldId);
656 if (kob) this.showKoboldModal(kob);
657 } else
658 {
659 alert(data.error || 'Failed to give item');
660 }
661 } catch (err)
662 {
663 console.error(err);
664 alert('Failed to give item');
665 } finally
666 {
667 this.hideItemModal();
668 }
669 }
670
671 hideItemModal ()
672 {
673 document.getElementById('itemModal').classList.add('hidden');
674 }
675
676 showKoboldModal (kobold)
677 {
678 const modal = document.getElementById('koboldModal');
679 document.getElementById('koboldModalName').textContent = kobold.name;
680 document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`;
681 document.getElementById('koboldModalDescription').textContent = `A ${kobold.ageCategory} Kobold`;
682
683 this.renderKoboldStats(kobold);
684 this.renderKoboldInventory(kobold);
685 this.renderKoboldInjuries(kobold);
686
687 // Setup tab buttons
688 document.querySelectorAll('.kobold-tab-btn').forEach(btn =>
689 {
690 btn.classList.remove('active');
691 btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab));
692 });
693 document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active');
694
695 // Hide all tabs
696 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
697 document.getElementById('koboldStatsTab').classList.add('active');
698
699 // Store current kobold for inventory actions
700 this.selectedKobold = kobold;
701
702 modal.classList.remove('hidden');
703 }
704
705 renderKoboldStats (kobold)
706 {
707 const statsGrid = document.getElementById('koboldStats');
708 statsGrid.innerHTML = '';
709
710 const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will'];
711 stats.forEach(stat =>
712 {
713 const value = kobold.stats[stat];
714 const label = this.getStatLabel(value);
715 const statEl = document.createElement('div');
716 statEl.className = 'stat-item';
717 statEl.innerHTML = `
718 <div class="stat-name">${stat}</div>
719 <div class="stat-value">${value}</div>
720 <div class="stat-label">${label}</div>
721 `;
722 statsGrid.appendChild(statEl);
723 });
724 }
725
726 renderKoboldInventory (kobold)
727 {
728 const inventory = document.getElementById('koboldInventory');
729 inventory.innerHTML = '';
730
731 if (!kobold.items || kobold.items.length === 0)
732 {
733 inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>';
734 return;
735 }
736
737 kobold.items.forEach(item =>
738 {
739 const itemEl = document.createElement('div');
740 itemEl.className = 'kobold-inventory-item';
741 itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`;
742 itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold));
743 inventory.appendChild(itemEl);
744 });
745 }
746
747 renderKoboldInjuries (kobold)
748 {
749 const container = document.getElementById('koboldInjuries');
750 container.innerHTML = '';
751
752 if (!kobold.injuries || kobold.injuries.length === 0)
753 {
754 container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>';
755 return;
756 }
757
758 kobold.injuries.forEach(injury =>
759 {
760 const el = document.createElement('div');
761 el.className = 'injury-item';
762 const name = injury.injury_type || injury.injuryType || 'Injury';
763 const desc = injury.description || '';
764 const severity = injury.severity ?? injury.severity ?? 1;
765
766 el.innerHTML = `
767 <div class="injury-name">${name} (Severity: ${severity})</div>
768 <div class="injury-desc">${desc}</div>
769 `;
770
771 const actions = document.createElement('div');
772 actions.className = 'injury-actions';
773
774 // malnourished has no cure button here
775 if (injury.category !== 'malnourished')
776 {
777 const required = injury.required_medicine || injury.requiredMedicine || null;
778 if (required)
779 {
780 // check if kobold has item with this id
781 const hasItem = (kobold.items || []).some(it => it.id === required);
782 if (hasItem)
783 {
784 const btn = document.createElement('button');
785 btn.className = 'primary';
786 btn.textContent = `Cure using ${required}`;
787 btn.addEventListener('click', async () =>
788 {
789 try
790 {
791 const resp = await fetch('api/game/cureInjury', {
792 method: 'POST',
793 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
794 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required })
795 });
796 const data = await resp.json();
797 if (data.success)
798 {
799 typeText(document.getElementById('eventStory'), data.story);
800 this.showEventModal();
801 // Refresh game state
802 await this.loadGame(this.currentSave.id);
803 // reopen kobold modal after refresh
804 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
805 if (refreshed) this.showKoboldModal(refreshed);
806 } else
807 {
808 alert(data.error || 'Failed to cure injury');
809 }
810 } catch (err)
811 {
812 console.error(err);
813 alert('Failed to cure injury');
814 }
815 });
816 actions.appendChild(btn);
817 } else
818 {
819 const note = document.createElement('div');
820 note.style.color = '#999';
821 note.textContent = `Needs: ${required}`;
822 actions.appendChild(note);
823 }
824 }
825 }
826
827 el.appendChild(actions);
828 container.appendChild(el);
829 });
830 }
831
832 showKoboldItemModal (item, kobold)
833 {
834 const modal = document.getElementById('itemModal');
835 document.getElementById('itemModalName').textContent = item.name;
836 document.getElementById('itemModalDescription').textContent = item.description || 'No description';
837
838 // Show stat modifications (handle both camelCase and snake_case)
839 const statMods = document.getElementById('itemModalStatMods');
840 statMods.innerHTML = '';
841
842 const modifications = item.stat_modifications || item.statModifications || {};
843 if (Object.keys(modifications).length > 0)
844 {
845 Object.entries(modifications).forEach(([stat, value]) =>
846 {
847 if (value !== 0)
848 {
849 const modEl = document.createElement('div');
850 modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`;
851 modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`;
852 statMods.appendChild(modEl);
853 }
854 });
855 } else
856 {
857 statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>';
858 }
859
860 // Change button to return item
861 const actions = document.querySelector('.item-modal-actions');
862 actions.innerHTML = '';
863
864 const returnBtn = document.createElement('button');
865 returnBtn.className = 'secondary';
866 returnBtn.textContent = 'Return to Storage';
867 returnBtn.addEventListener('click', () => this.returnItemToStorage(item, kobold));
868 actions.appendChild(returnBtn);
869
870 modal.classList.remove('hidden');
871 this.selectedKobold = kobold;
872 }
873
874 async returnItemToStorage (item, kobold)
875 {
876 try
877 {
878 const resp = await fetch('api/game/returnItem', {
879 method: 'POST',
880 headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` },
881 body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id })
882 });
883
884 const data = await resp.json();
885 if (data.success)
886 {
887 typeText(document.getElementById('eventStory'), data.story);
888 this.showEventModal();
889 // Refresh game state
890 await this.loadGame(this.currentSave.id);
891 const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id);
892 if (refreshed) this.showKoboldModal(refreshed);
893 } else
894 {
895 alert(data.error || 'Failed to return item');
896 }
897 } catch (err)
898 {
899 console.error(err);
900 alert('Failed to return item');
901 } finally
902 {
903 this.hideItemModal();
904 }
905 }
906
907 switchKoboldTab (tabName)
908 {
909 // Hide all tabs
910 document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active'));
911 document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active'));
912
913 // Show selected tab
914 const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab';
915 document.getElementById(tabId).classList.add('active');
916 document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
917 }
918
919 getStatLabel (statValue)
920 {
921 if (statValue >= 90) return 'godlike';
922 if (statValue >= 80) return 'divine';
923 if (statValue >= 70) return 'master';
924 if (statValue >= 60) return 'fantastic';
925 if (statValue >= 50) return 'excellent';
926 if (statValue >= 40) return 'good';
927 if (statValue >= 30) return 'decent';
928 if (statValue >= 20) return 'unskilled';
929 if (statValue >= 10) return 'bad';
930 return 'terrible';
931 }
932
541 hideAll ()
933 hideAll ()
542 {
934 {
543 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
935 document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden'));
web/src/Classes/Injury.php +10 −3
@@ -5,10 +5,11 @@ require_once __DIR__ . '/../../src/Database/Database.php';
5 5 class Injury
6 6 {
7 7 private $id;
8 private $koboldId;
9 8 private $injuryType;
9 private $description;
10 10 private $category;
11 11 private $severity;
12 private $statModifications = [];
12 13
13 14 private static $cureMap = [
14 15 'wound' => 'basic_medicine',
@@ -20,13 +21,14 @@ class Injury
20 21 'old-age' => null // Cannot be cured
21 22 ];
22 23
23 public function __construct($id, $koboldId, $injuryType, $category, $severity)
24 public function __construct($id, $injuryType, $description, $category, $severity, $statModifications = [])
24 25 {
25 26 $this->id = $id;
26 $this->koboldId = $koboldId;
27 $this->description = $description;
27 28 $this->injuryType = $injuryType;
28 29 $this->category = $category;
29 30 $this->severity = $severity;
31 $this->statModifications = $statModifications;
30 32 }
31 33
32 34 public static function load($id)
@@ -75,6 +77,11 @@ class Injury
75 77 return self::$cureMap[$this->category] ?? null;
76 78 }
77 79
80 public static function getCureForCategory($category)
81 {
82 return self::$cureMap[$category] ?? null;
83 }
84
78 85 public function getDescription()
79 86 {
80 87 return ucfirst(str_replace('_', ' ', $this->injuryType));
@@ -5,10 +5,11 @@ require_once __DIR__ . '/../../src/Database/Database.php';
5class Injury
5class Injury
6{
6{
7 private $id;
7 private $id;
8 private $koboldId;
9 private $injuryType;
8 private $injuryType;
9 private $description;
10 private $category;
10 private $category;
11 private $severity;
11 private $severity;
12 private $statModifications = [];
12
13
13 private static $cureMap = [
14 private static $cureMap = [
14 'wound' => 'basic_medicine',
15 'wound' => 'basic_medicine',
@@ -20,13 +21,14 @@ class Injury
20 'old-age' => null // Cannot be cured
21 'old-age' => null // Cannot be cured
21 ];
22 ];
22
23
23 public function __construct($id, $koboldId, $injuryType, $category, $severity)
24 public function __construct($id, $injuryType, $description, $category, $severity, $statModifications = [])
24 {
25 {
25 $this->id = $id;
26 $this->id = $id;
26 $this->koboldId = $koboldId;
27 $this->description = $description;
27 $this->injuryType = $injuryType;
28 $this->injuryType = $injuryType;
28 $this->category = $category;
29 $this->category = $category;
29 $this->severity = $severity;
30 $this->severity = $severity;
31 $this->statModifications = $statModifications;
30 }
32 }
31
33
32 public static function load($id)
34 public static function load($id)
@@ -75,6 +77,11 @@ class Injury
75 return self::$cureMap[$this->category] ?? null;
77 return self::$cureMap[$this->category] ?? null;
76 }
78 }
77
79
80 public static function getCureForCategory($category)
81 {
82 return self::$cureMap[$category] ?? null;
83 }
84
78 public function getDescription()
85 public function getDescription()
79 {
86 {
80 return ucfirst(str_replace('_', ' ', $this->injuryType));
87 return ucfirst(str_replace('_', ' ', $this->injuryType));
web/src/Classes/Item.php +1 −4
@@ -9,10 +9,9 @@ class Item
9 9 private $itemType;
10 10 private $statModifications = [];
11 11
12 public function __construct($id, $saveId, $name, $description, $itemType, $statModifications = [])
12 public function __construct($id, $name, $description, $itemType, $statModifications = [])
13 13 {
14 14 $this->id = $id;
15 $this->saveId = $saveId;
16 15 $this->name = $name;
17 16 $this->description = $description;
18 17 $this->itemType = $itemType;
@@ -23,7 +22,6 @@ class Item
23 22 {
24 23 return new self(
25 24 $data['id'] ?? uniqid('itm_'),
26 $data['save_id'] ?? null,
27 25 $data['name'] ?? '',
28 26 $data['description'] ?? '',
29 27 $data['item_type'] ?? 'generic',
@@ -35,7 +33,6 @@ class Item
35 33 {
36 34 return [
37 35 'id' => $this->id,
38 'save_id' => $this->saveId,
39 36 'name' => $this->name,
40 37 'description' => $this->description,
41 38 'item_type' => $this->itemType,
@@ -9,10 +9,9 @@ class Item
9 private $itemType;
9 private $itemType;
10 private $statModifications = [];
10 private $statModifications = [];
11
11
12 public function __construct($id, $saveId, $name, $description, $itemType, $statModifications = [])
12 public function __construct($id, $name, $description, $itemType, $statModifications = [])
13 {
13 {
14 $this->id = $id;
14 $this->id = $id;
15 $this->saveId = $saveId;
16 $this->name = $name;
15 $this->name = $name;
17 $this->description = $description;
16 $this->description = $description;
18 $this->itemType = $itemType;
17 $this->itemType = $itemType;
@@ -23,7 +22,6 @@ class Item
23 {
22 {
24 return new self(
23 return new self(
25 $data['id'] ?? uniqid('itm_'),
24 $data['id'] ?? uniqid('itm_'),
26 $data['save_id'] ?? null,
27 $data['name'] ?? '',
25 $data['name'] ?? '',
28 $data['description'] ?? '',
26 $data['description'] ?? '',
29 $data['item_type'] ?? 'generic',
27 $data['item_type'] ?? 'generic',
@@ -35,7 +33,6 @@ class Item
35 {
33 {
36 return [
34 return [
37 'id' => $this->id,
35 'id' => $this->id,
38 'save_id' => $this->saveId,
39 'name' => $this->name,
36 'name' => $this->name,
40 'description' => $this->description,
37 'description' => $this->description,
41 'item_type' => $this->itemType,
38 'item_type' => $this->itemType,
web/src/Classes/Kobold.php +125 −12
@@ -111,16 +111,64 @@ class Kobold
111 111 {
112 112 // Kobold name syllables
113 113 $firstSyllables = [
114 'Grik', 'Gnak', 'Drog', 'Mog', 'Bik', 'Zag', 'Kra', 'Snak',
115 'Grok', 'Tik', 'Nag', 'Brack', 'Flak', 'Grat', 'Krag', 'Skrit',
116 'Zik', 'Bog', 'Crag', 'Gull', 'Kith', 'Mick', 'Nib', 'Prat',
117 'Rik', 'Tig', 'Vex', 'Wik', 'Xak', 'Yak', 'Zap'
114 'Grik',
115 'Gnak',
116 'Drog',
117 'Mog',
118 'Bik',
119 'Zag',
120 'Kra',
121 'Snak',
122 'Grok',
123 'Tik',
124 'Nag',
125 'Brack',
126 'Flak',
127 'Grat',
128 'Krag',
129 'Skrit',
130 'Zik',
131 'Bog',
132 'Crag',
133 'Gull',
134 'Kith',
135 'Mick',
136 'Nib',
137 'Prat',
138 'Rik',
139 'Tig',
140 'Vex',
141 'Wik',
142 'Xak',
143 'Yak',
144 'Zap'
118 145 ];
119 146
120 147 $lastSyllables = [
121 'ink', 'ack', 'og', 'ag', 'ug', 'ik', 'ek', 'ock',
122 'ar', 'ax', 'er', 'it', 'ut', 'ot', 'or', 'in',
123 'an', 'en', 'un', 'on', 'oo', 'ee', 'im', 'um'
148 'ink',
149 'ack',
150 'og',
151 'ag',
152 'ug',
153 'ik',
154 'ek',
155 'ock',
156 'ar',
157 'ax',
158 'er',
159 'it',
160 'ut',
161 'ot',
162 'or',
163 'in',
164 'an',
165 'en',
166 'un',
167 'on',
168 'oo',
169 'ee',
170 'im',
171 'um'
124 172 ];
125 173
126 174 $firstName = $firstSyllables[array_rand($firstSyllables)];
@@ -338,10 +386,40 @@ class Kobold
338 386 {
339 387 $stat = $this->getStat($statName);
340 388
389 if ($stat === null) {
390 return false;
391 }
392
393 // Apply item stat modifications (support arrays from JSON or Item objects)
394 $itemModTotal = 0;
395 if (!empty($this->items) && is_array($this->items)) {
396 foreach ($this->items as $itm) {
397 $mods = [];
398 if (is_array($itm)) {
399 $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
400 } elseif (is_object($itm)) {
401 if (method_exists($itm, 'getStatModifications')) {
402 $mods = $itm->getStatModifications();
403 } elseif (property_exists($itm, 'statModifications')) {
404 $mods = $itm->statModifications;
405 }
406 }
407
408 if (is_array($mods) && isset($mods[$statName])) {
409 $itemModTotal += (int) $mods[$statName];
410 }
411 }
412 }
413
414 // First apply item modifications to the stat
415 $stat += $itemModTotal;
416
341 417 // Apply injury modifications
342 $totalInjurySeverity = array_sum(array_column($this->injuries, 'severity', null));
343 if ($totalInjurySeverity === null) {
344 $totalInjurySeverity = 0;
418 $totalInjurySeverity = 0;
419 if (!empty($this->injuries) && is_array($this->injuries)) {
420 foreach ($this->injuries as $inj) {
421 $totalInjurySeverity += $inj['severity'] ?? 0;
422 }
345 423 }
346 424
347 425 $stat -= $totalInjurySeverity;
@@ -354,14 +432,31 @@ class Kobold
354 432
355 433 public function addInjury($injuryType, $category, $severity = 1)
356 434 {
357 $id = uniqid('inj_');
435 // If an injury file exists in assets, load it for full data
436 $injData = null;
437 require_once __DIR__ . '/../Utilities/GameHelper.php';
438 $maybe = GameHelper::loadInjury($injuryType);
439 if ($maybe) {
440 $injData = $maybe;
441 // override severity and category if provided explicitly
442 $injData['severity'] = $severity ?? ($injData['severity'] ?? 1);
443 if ($category)
444 $injData['category'] = $category;
445 // ensure kobold id
446 $injData['kobold_id'] = $this->id;
447 $this->injuries[] = $injData;
448 return;
449 }
358 450
451 // Fallback: create a minimal injury array
452 $id = uniqid('inj_');
359 453 $this->injuries[] = [
360 454 'id' => $id,
361 455 'kobold_id' => $this->id,
362 456 'injury_type' => $injuryType,
363 457 'category' => $category,
364 'severity' => $severity
458 'severity' => $severity,
459 'stat_modifications' => []
365 460 ];
366 461 }
367 462
@@ -443,6 +538,24 @@ class Kobold
443 538 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
444 539 }
445 540
541 public function getItems()
542 {
543 return $this->items;
544 }
545
546 public function addItem($item)
547 {
548 $this->items[] = $item;
549 }
550
551 public function removeItem($itemId)
552 {
553 $this->items = array_filter($this->items, function ($item) use ($itemId) {
554 return $item['id'] !== $itemId;
555 });
556 $this->items = array_values($this->items);
557 }
558
446 559 /**
447 560 * Apply transformations to sprite (injuries, age coloring, leadership marks)
448 561 * Uses PHP GD library to modify the sprite image
@@ -111,16 +111,64 @@ class Kobold
111 {
111 {
112 // Kobold name syllables
112 // Kobold name syllables
113 $firstSyllables = [
113 $firstSyllables = [
114 'Grik', 'Gnak', 'Drog', 'Mog', 'Bik', 'Zag', 'Kra', 'Snak',
114 'Grik',
115 'Grok', 'Tik', 'Nag', 'Brack', 'Flak', 'Grat', 'Krag', 'Skrit',
115 'Gnak',
116 'Zik', 'Bog', 'Crag', 'Gull', 'Kith', 'Mick', 'Nib', 'Prat',
116 'Drog',
117 'Rik', 'Tig', 'Vex', 'Wik', 'Xak', 'Yak', 'Zap'
117 'Mog',
118 'Bik',
119 'Zag',
120 'Kra',
121 'Snak',
122 'Grok',
123 'Tik',
124 'Nag',
125 'Brack',
126 'Flak',
127 'Grat',
128 'Krag',
129 'Skrit',
130 'Zik',
131 'Bog',
132 'Crag',
133 'Gull',
134 'Kith',
135 'Mick',
136 'Nib',
137 'Prat',
138 'Rik',
139 'Tig',
140 'Vex',
141 'Wik',
142 'Xak',
143 'Yak',
144 'Zap'
118 ];
145 ];
119
146
120 $lastSyllables = [
147 $lastSyllables = [
121 'ink', 'ack', 'og', 'ag', 'ug', 'ik', 'ek', 'ock',
148 'ink',
122 'ar', 'ax', 'er', 'it', 'ut', 'ot', 'or', 'in',
149 'ack',
123 'an', 'en', 'un', 'on', 'oo', 'ee', 'im', 'um'
150 'og',
151 'ag',
152 'ug',
153 'ik',
154 'ek',
155 'ock',
156 'ar',
157 'ax',
158 'er',
159 'it',
160 'ut',
161 'ot',
162 'or',
163 'in',
164 'an',
165 'en',
166 'un',
167 'on',
168 'oo',
169 'ee',
170 'im',
171 'um'
124 ];
172 ];
125
173
126 $firstName = $firstSyllables[array_rand($firstSyllables)];
174 $firstName = $firstSyllables[array_rand($firstSyllables)];
@@ -338,10 +386,40 @@ class Kobold
338 {
386 {
339 $stat = $this->getStat($statName);
387 $stat = $this->getStat($statName);
340
388
389 if ($stat === null) {
390 return false;
391 }
392
393 // Apply item stat modifications (support arrays from JSON or Item objects)
394 $itemModTotal = 0;
395 if (!empty($this->items) && is_array($this->items)) {
396 foreach ($this->items as $itm) {
397 $mods = [];
398 if (is_array($itm)) {
399 $mods = $itm['stat_modifications'] ?? $itm['statModifications'] ?? [];
400 } elseif (is_object($itm)) {
401 if (method_exists($itm, 'getStatModifications')) {
402 $mods = $itm->getStatModifications();
403 } elseif (property_exists($itm, 'statModifications')) {
404 $mods = $itm->statModifications;
405 }
406 }
407
408 if (is_array($mods) && isset($mods[$statName])) {
409 $itemModTotal += (int) $mods[$statName];
410 }
411 }
412 }
413
414 // First apply item modifications to the stat
415 $stat += $itemModTotal;
416
341 // Apply injury modifications
417 // Apply injury modifications
342 $totalInjurySeverity = array_sum(array_column($this->injuries, 'severity', null));
418 $totalInjurySeverity = 0;
343 if ($totalInjurySeverity === null) {
419 if (!empty($this->injuries) && is_array($this->injuries)) {
344 $totalInjurySeverity = 0;
420 foreach ($this->injuries as $inj) {
421 $totalInjurySeverity += $inj['severity'] ?? 0;
422 }
345 }
423 }
346
424
347 $stat -= $totalInjurySeverity;
425 $stat -= $totalInjurySeverity;
@@ -354,14 +432,31 @@ class Kobold
354
432
355 public function addInjury($injuryType, $category, $severity = 1)
433 public function addInjury($injuryType, $category, $severity = 1)
356 {
434 {
357 $id = uniqid('inj_');
435 // If an injury file exists in assets, load it for full data
436 $injData = null;
437 require_once __DIR__ . '/../Utilities/GameHelper.php';
438 $maybe = GameHelper::loadInjury($injuryType);
439 if ($maybe) {
440 $injData = $maybe;
441 // override severity and category if provided explicitly
442 $injData['severity'] = $severity ?? ($injData['severity'] ?? 1);
443 if ($category)
444 $injData['category'] = $category;
445 // ensure kobold id
446 $injData['kobold_id'] = $this->id;
447 $this->injuries[] = $injData;
448 return;
449 }
358
450
451 // Fallback: create a minimal injury array
452 $id = uniqid('inj_');
359 $this->injuries[] = [
453 $this->injuries[] = [
360 'id' => $id,
454 'id' => $id,
361 'kobold_id' => $this->id,
455 'kobold_id' => $this->id,
362 'injury_type' => $injuryType,
456 'injury_type' => $injuryType,
363 'category' => $category,
457 'category' => $category,
364 'severity' => $severity
458 'severity' => $severity,
459 'stat_modifications' => []
365 ];
460 ];
366 }
461 }
367
462
@@ -443,6 +538,24 @@ class Kobold
443 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
538 return ['father_id' => $this->fatherId, 'mother_id' => $this->motherId];
444 }
539 }
445
540
541 public function getItems()
542 {
543 return $this->items;
544 }
545
546 public function addItem($item)
547 {
548 $this->items[] = $item;
549 }
550
551 public function removeItem($itemId)
552 {
553 $this->items = array_filter($this->items, function ($item) use ($itemId) {
554 return $item['id'] !== $itemId;
555 });
556 $this->items = array_values($this->items);
557 }
558
446 /**
559 /**
447 * Apply transformations to sprite (injuries, age coloring, leadership marks)
560 * Apply transformations to sprite (injuries, age coloring, leadership marks)
448 * Uses PHP GD library to modify the sprite image
561 * Uses PHP GD library to modify the sprite image
web/src/Classes/Tribe.php +20 −6
@@ -224,9 +224,19 @@ class Tribe
224 224 }
225 225
226 226 // Storage management
227 public function addToStorage($itemId)
228 {
229 // Items are already linked to saves
227 public function addToStorage($item)
228 {
229 // Accept either Item object or array
230 if (is_object($item) && method_exists($item, 'toArray')) {
231 $this->storage[] = $item->toArray();
232 } elseif (is_array($item)) {
233 // Ensure it has an id
234 if (!isset($item['id'])) {
235 $item['id'] = uniqid('itm_');
236 }
237 $this->storage[] = $item;
238 }
239 return $this->storage;
230 240 }
231 241
232 242 public function getStorage()
@@ -409,9 +419,13 @@ class Tribe
409 419 $kobold->addInjury($injury, 'old-age', 1);
410 420 }
411 421
412 // Check if kobold should die
413 if ($kobold->isDead()) {
414 $kobold->die();
422 // Old-age death roll: if roll < (age + total injury severity), kobold dies
423 if ($kobold->getAge() >= 35) {
424 $roll = rand(1, 100);
425 $totalSeverity = $kobold->getTotalInjurySeverity();
426 if ($roll < ($kobold->getAge() + $totalSeverity)) {
427 $kobold->die();
428 }
415 429 }
416 430
417 431 $kobold->save();
@@ -224,9 +224,19 @@ class Tribe
224 }
224 }
225
225
226 // Storage management
226 // Storage management
227 public function addToStorage($itemId)
227 public function addToStorage($item)
228 {
228 {
229 // Items are already linked to saves
229 // Accept either Item object or array
230 if (is_object($item) && method_exists($item, 'toArray')) {
231 $this->storage[] = $item->toArray();
232 } elseif (is_array($item)) {
233 // Ensure it has an id
234 if (!isset($item['id'])) {
235 $item['id'] = uniqid('itm_');
236 }
237 $this->storage[] = $item;
238 }
239 return $this->storage;
230 }
240 }
231
241
232 public function getStorage()
242 public function getStorage()
@@ -409,9 +419,13 @@ class Tribe
409 $kobold->addInjury($injury, 'old-age', 1);
419 $kobold->addInjury($injury, 'old-age', 1);
410 }
420 }
411
421
412 // Check if kobold should die
422 // Old-age death roll: if roll < (age + total injury severity), kobold dies
413 if ($kobold->isDead()) {
423 if ($kobold->getAge() >= 35) {
414 $kobold->die();
424 $roll = rand(1, 100);
425 $totalSeverity = $kobold->getTotalInjurySeverity();
426 if ($roll < ($kobold->getAge() + $totalSeverity)) {
427 $kobold->die();
428 }
415 }
429 }
416
430
417 $kobold->save();
431 $kobold->save();
web/src/Events/Event.php +23 −0
@@ -6,6 +6,9 @@ abstract class Event
6 6 {
7 7 protected $tribe;
8 8 protected $story = '';
9 protected $participants = []; // array of kobold ids
10 protected $minParticipants = 1;
11 protected $maxParticipants = 3;
9 12
10 13 public function __construct(Tribe $tribe)
11 14 {
@@ -14,6 +17,26 @@ abstract class Event
14 17
15 18 abstract public function execute();
16 19
20 public function setParticipants(array $koboldIds)
21 {
22 $this->participants = $koboldIds;
23 }
24
25 public function getParticipants()
26 {
27 return $this->participants;
28 }
29
30 public function getMinParticipants()
31 {
32 return $this->minParticipants;
33 }
34
35 public function getMaxParticipants()
36 {
37 return $this->maxParticipants;
38 }
39
17 40 public function getStory()
18 41 {
19 42 return $this->story;
@@ -6,6 +6,9 @@ abstract class Event
6{
6{
7 protected $tribe;
7 protected $tribe;
8 protected $story = '';
8 protected $story = '';
9 protected $participants = []; // array of kobold ids
10 protected $minParticipants = 1;
11 protected $maxParticipants = 3;
9
12
10 public function __construct(Tribe $tribe)
13 public function __construct(Tribe $tribe)
11 {
14 {
@@ -14,6 +17,26 @@ abstract class Event
14
17
15 abstract public function execute();
18 abstract public function execute();
16
19
20 public function setParticipants(array $koboldIds)
21 {
22 $this->participants = $koboldIds;
23 }
24
25 public function getParticipants()
26 {
27 return $this->participants;
28 }
29
30 public function getMinParticipants()
31 {
32 return $this->minParticipants;
33 }
34
35 public function getMaxParticipants()
36 {
37 return $this->maxParticipants;
38 }
39
17 public function getStory()
40 public function getStory()
18 {
41 {
19 return $this->story;
42 return $this->story;
web/src/Events/ExplorationEvent.php +59 −50
@@ -1,6 +1,7 @@
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 ExplorationEvent extends Event
6 7 {
@@ -8,20 +9,33 @@ class ExplorationEvent extends Event
8 9 {
9 10 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
10 11
11 $kobolds = $this->tribe->getAliveKobolds();
12 $available = $this->tribe->getAliveKobolds();
12 13
13 if (empty($kobolds)) {
14 if (empty($available)) {
14 15 $this->story .= "But there were no kobolds to send exploring!";
15 16 return;
16 17 }
17 18
18 // Randomly select 1-3 explorers
19 $explorerCount = rand(1, min(3, count($kobolds)));
20 $explorers = array_slice(array_values($kobolds), 0, $explorerCount);
19 // Exploration must be started with explicit participants (player-started)
20 $participantIds = $this->getParticipants();
21 if (empty($participantIds) || !is_array($participantIds)) {
22 throw new \Exception('ExplorationEvent requires a participants array of kobold IDs.');
23 }
24
25 $explorers = [];
26 foreach ($participantIds as $pid) {
27 $k = $this->tribe->getKobold($pid);
28 if ($k && !$k->isDead())
29 $explorers[] = $k;
30 }
31
32 if (empty($explorers)) {
33 throw new \Exception('No valid living kobolds found in participants list.');
34 }
21 35
22 36 $this->story .= "A group of " . count($explorers) . " intrepid explorers set out:\n";
23 37 foreach ($explorers as $explorer) {
24 $this->story .= "- " . $explorer->getName() . " (Intelligence: " . $this->statDisplay($explorer->getStat('intelligence')) . ")\n";
38 $this->story .= "- " . $explorer->getName() . " (Intelligence: " . getStatLabel($explorer->getStat('intelligence')) . ")\n";
25 39 }
26 40 $this->story .= "\n";
27 41
@@ -31,7 +45,8 @@ class ExplorationEvent extends Event
31 45 $baseFood = rand(5, 15);
32 46 // Intelligence affects food discovery - smarter kobolds find more
33 47 $avgIntelligence = array_sum(array_map(function ($k) {
34 return $k->getStat('intelligence'); }, $explorers)) / count($explorers);
48 return $k->getStat('intelligence');
49 }, $explorers)) / count($explorers);
35 50 $foodBonus = intval($avgIntelligence / 20); // Max +5 food from intelligence
36 51 $totalFood = $baseFood + $foodBonus;
37 52
@@ -42,12 +57,13 @@ class ExplorationEvent extends Event
42 57 $this->story .= "The terrain was barren. No food was found.\n\n";
43 58 }
44 59
45 // Chance for injury (35% - someone trips on loose stone)
46 $injuryChance = rand(1, 100) <= 35;
60 // Chance for injury (large chance for testing) - someone trips on loose stone
61 $injuryChance = rand(1, 100) <= 70; // higher for testing
47 62 if ($injuryChance && count($explorers) > 0) {
48 63 // Vitality affects injury chance - higher vitality = less likely to be injured
49 64 $avgVitality = array_sum(array_map(function ($k) {
50 return $k->getStat('vitality'); }, $explorers)) / count($explorers);
65 return $k->getStat('vitality');
66 }, $explorers)) / count($explorers);
51 67 $injuryProbability = (100 - $avgVitality) / 100;
52 68
53 69 if (rand(1, 100) / 100 <= $injuryProbability) {
@@ -56,51 +72,44 @@ class ExplorationEvent extends Event
56 72
57 73 $this->story .= "Disaster! " . $injuredKobold->getName() . " tripped over a loose stone!\n";
58 74
59 // Create injury array (since we're in file-based storage)
60 $injuries = $injuredKobold->getInjuries();
61 $newInjury = [
62 'id' => uniqid('inj_'),
63 'kobold_id' => $injuredKobold->getId(),
64 'injury_type' => 'twisted_ankle',
65 'category' => 'wound',
66 'severity' => rand(2, 5),
67 'created_at' => date('Y-m-d H:i:s')
68 ];
69 $injuries[] = $newInjury;
70 $injuredKobold->setInjuries($injuries);
71
72 $this->story .= $injuredKobold->getName() . " suffered a twisted ankle (severity: " . $newInjury['severity'] . "/10).\n";
75 // Try to load a predefined injury (brokenLeg) from assets
76 $inj = GameHelper::loadInjury('brokenLeg');
77 if ($inj) {
78 $inj['kobold_id'] = $injuredKobold->getId();
79 $inj['id'] = uniqid('inj_');
80 $injuries = $injuredKobold->getInjuries();
81 $injuries[] = $inj;
82 $injuredKobold->setInjuries($injuries);
83
84 $this->story .= $injuredKobold->getName() . " suffered a " . ($inj['injury_type'] ?? 'broken leg') . " (severity: " . ($inj['severity'] ?? 1) . "/10).\n";
85 } else {
86 // Fallback to simple injury
87 $newInjury = [
88 'id' => uniqid('inj_'),
89 'kobold_id' => $injuredKobold->getId(),
90 'injury_type' => 'broken_leg',
91 'category' => 'fracture',
92 'severity' => rand(3, 7),
93 'created_at' => date('Y-m-d H:i:s')
94 ];
95 $injuries = $injuredKobold->getInjuries();
96 $injuries[] = $newInjury;
97 $injuredKobold->setInjuries($injuries);
98
99 $this->story .= $injuredKobold->getName() . " suffered a broken leg (severity: " . $newInjury['severity'] . "/10).\n";
100 }
73 101 }
74 102 }
75 103
104 // For testing: add a 'bone-setting' item to tribe storage so player can cure fractures
105 $boneItem = GameHelper::loadItem('bone-setting');
106 if ($boneItem) {
107 $this->tribe->addToStorage($boneItem);
108 $this->story .= "The explorers also salvaged a Bone-setting kit and brought it back to storage.\n";
109 }
110
76 111 $this->story .= "\nThe exploration party returned to the tribe with their findings.";
77 112
78 113 return $this->story;
79 114 }
80
81 /**
82 * Convert internal stat value to display text
83 */
84 private function statDisplay($stat)
85 {
86 if ($stat <= 10)
87 return "terrible";
88 if ($stat <= 20)
89 return "bad";
90 if ($stat <= 30)
91 return "unskilled";
92 if ($stat <= 40)
93 return "decent";
94 if ($stat <= 50)
95 return "good";
96 if ($stat <= 60)
97 return "excellent";
98 if ($stat <= 70)
99 return "fantastic";
100 if ($stat <= 80)
101 return "master";
102 if ($stat <= 90)
103 return "divine";
104 return "godlike";
105 }
106 115 }
@@ -1,6 +1,7 @@
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 ExplorationEvent extends Event
6class ExplorationEvent extends Event
6{
7{
@@ -8,20 +9,33 @@ class ExplorationEvent extends Event
8 {
9 {
9 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
10 $this->story = "The exploration party ventured forth into uncharted territory...\n\n";
10
11
11 $kobolds = $this->tribe->getAliveKobolds();
12 $available = $this->tribe->getAliveKobolds();
12
13
13 if (empty($kobolds)) {
14 if (empty($available)) {
14 $this->story .= "But there were no kobolds to send exploring!";
15 $this->story .= "But there were no kobolds to send exploring!";
15 return;
16 return;
16 }
17 }
17
18
18 // Randomly select 1-3 explorers
19 // Exploration must be started with explicit participants (player-started)
19 $explorerCount = rand(1, min(3, count($kobolds)));
20 $participantIds = $this->getParticipants();
20 $explorers = array_slice(array_values($kobolds), 0, $explorerCount);
21 if (empty($participantIds) || !is_array($participantIds)) {
22 throw new \Exception('ExplorationEvent requires a participants array of kobold IDs.');
23 }
24
25 $explorers = [];
26 foreach ($participantIds as $pid) {
27 $k = $this->tribe->getKobold($pid);
28 if ($k && !$k->isDead())
29 $explorers[] = $k;
30 }
31
32 if (empty($explorers)) {
33 throw new \Exception('No valid living kobolds found in participants list.');
34 }
21
35
22 $this->story .= "A group of " . count($explorers) . " intrepid explorers set out:\n";
36 $this->story .= "A group of " . count($explorers) . " intrepid explorers set out:\n";
23 foreach ($explorers as $explorer) {
37 foreach ($explorers as $explorer) {
24 $this->story .= "- " . $explorer->getName() . " (Intelligence: " . $this->statDisplay($explorer->getStat('intelligence')) . ")\n";
38 $this->story .= "- " . $explorer->getName() . " (Intelligence: " . getStatLabel($explorer->getStat('intelligence')) . ")\n";
25 }
39 }
26 $this->story .= "\n";
40 $this->story .= "\n";
27
41
@@ -31,7 +45,8 @@ class ExplorationEvent extends Event
31 $baseFood = rand(5, 15);
45 $baseFood = rand(5, 15);
32 // Intelligence affects food discovery - smarter kobolds find more
46 // Intelligence affects food discovery - smarter kobolds find more
33 $avgIntelligence = array_sum(array_map(function ($k) {
47 $avgIntelligence = array_sum(array_map(function ($k) {
34 return $k->getStat('intelligence'); }, $explorers)) / count($explorers);
48 return $k->getStat('intelligence');
49 }, $explorers)) / count($explorers);
35 $foodBonus = intval($avgIntelligence / 20); // Max +5 food from intelligence
50 $foodBonus = intval($avgIntelligence / 20); // Max +5 food from intelligence
36 $totalFood = $baseFood + $foodBonus;
51 $totalFood = $baseFood + $foodBonus;
37
52
@@ -42,12 +57,13 @@ class ExplorationEvent extends Event
42 $this->story .= "The terrain was barren. No food was found.\n\n";
57 $this->story .= "The terrain was barren. No food was found.\n\n";
43 }
58 }
44
59
45 // Chance for injury (35% - someone trips on loose stone)
60 // Chance for injury (large chance for testing) - someone trips on loose stone
46 $injuryChance = rand(1, 100) <= 35;
61 $injuryChance = rand(1, 100) <= 70; // higher for testing
47 if ($injuryChance && count($explorers) > 0) {
62 if ($injuryChance && count($explorers) > 0) {
48 // Vitality affects injury chance - higher vitality = less likely to be injured
63 // Vitality affects injury chance - higher vitality = less likely to be injured
49 $avgVitality = array_sum(array_map(function ($k) {
64 $avgVitality = array_sum(array_map(function ($k) {
50 return $k->getStat('vitality'); }, $explorers)) / count($explorers);
65 return $k->getStat('vitality');
66 }, $explorers)) / count($explorers);
51 $injuryProbability = (100 - $avgVitality) / 100;
67 $injuryProbability = (100 - $avgVitality) / 100;
52
68
53 if (rand(1, 100) / 100 <= $injuryProbability) {
69 if (rand(1, 100) / 100 <= $injuryProbability) {
@@ -56,51 +72,44 @@ class ExplorationEvent extends Event
56
72
57 $this->story .= "Disaster! " . $injuredKobold->getName() . " tripped over a loose stone!\n";
73 $this->story .= "Disaster! " . $injuredKobold->getName() . " tripped over a loose stone!\n";
58
74
59 // Create injury array (since we're in file-based storage)
75 // Try to load a predefined injury (brokenLeg) from assets
60 $injuries = $injuredKobold->getInjuries();
76 $inj = GameHelper::loadInjury('brokenLeg');
61 $newInjury = [
77 if ($inj) {
62 'id' => uniqid('inj_'),
78 $inj['kobold_id'] = $injuredKobold->getId();
63 'kobold_id' => $injuredKobold->getId(),
79 $inj['id'] = uniqid('inj_');
64 'injury_type' => 'twisted_ankle',
80 $injuries = $injuredKobold->getInjuries();
65 'category' => 'wound',
81 $injuries[] = $inj;
66 'severity' => rand(2, 5),
82 $injuredKobold->setInjuries($injuries);
67 'created_at' => date('Y-m-d H:i:s')
83
68 ];
84 $this->story .= $injuredKobold->getName() . " suffered a " . ($inj['injury_type'] ?? 'broken leg') . " (severity: " . ($inj['severity'] ?? 1) . "/10).\n";
69 $injuries[] = $newInjury;
85 } else {
70 $injuredKobold->setInjuries($injuries);
86 // Fallback to simple injury
71
87 $newInjury = [
72 $this->story .= $injuredKobold->getName() . " suffered a twisted ankle (severity: " . $newInjury['severity'] . "/10).\n";
88 'id' => uniqid('inj_'),
89 'kobold_id' => $injuredKobold->getId(),
90 'injury_type' => 'broken_leg',
91 'category' => 'fracture',
92 'severity' => rand(3, 7),
93 'created_at' => date('Y-m-d H:i:s')
94 ];
95 $injuries = $injuredKobold->getInjuries();
96 $injuries[] = $newInjury;
97 $injuredKobold->setInjuries($injuries);
98
99 $this->story .= $injuredKobold->getName() . " suffered a broken leg (severity: " . $newInjury['severity'] . "/10).\n";
100 }
73 }
101 }
74 }
102 }
75
103
104 // For testing: add a 'bone-setting' item to tribe storage so player can cure fractures
105 $boneItem = GameHelper::loadItem('bone-setting');
106 if ($boneItem) {
107 $this->tribe->addToStorage($boneItem);
108 $this->story .= "The explorers also salvaged a Bone-setting kit and brought it back to storage.\n";
109 }
110
76 $this->story .= "\nThe exploration party returned to the tribe with their findings.";
111 $this->story .= "\nThe exploration party returned to the tribe with their findings.";
77
112
78 return $this->story;
113 return $this->story;
79 }
114 }
80
81 /**
82 * Convert internal stat value to display text
83 */
84 private function statDisplay($stat)
85 {
86 if ($stat <= 10)
87 return "terrible";
88 if ($stat <= 20)
89 return "bad";
90 if ($stat <= 30)
91 return "unskilled";
92 if ($stat <= 40)
93 return "decent";
94 if ($stat <= 50)
95 return "good";
96 if ($stat <= 60)
97 return "excellent";
98 if ($stat <= 70)
99 return "fantastic";
100 if ($stat <= 80)
101 return "master";
102 if ($stat <= 90)
103 return "divine";
104 return "godlike";
105 }
106}
115}
web/src/Utilities/GameHelper.php +66 −0
@@ -212,4 +212,70 @@ class GameHelper
212 212 {
213 213 return ucfirst(str_replace('_', ' ', $text));
214 214 }
215
216 /**
217 * Load item from JSON file by ID
218 *
219 * @param string $itemId The filename without extension (e.g. 'book')
220 * @return Item|null The loaded item or null if file not found
221 */
222 public static function loadItem($itemId)
223 {
224 require_once __DIR__ . '/../Classes/Item.php';
225
226 $itemPath = __DIR__ . '/../../assets/items/' . $itemId . '.json';
227
228 if (!file_exists($itemPath)) {
229 return null;
230 }
231
232 $json = file_get_contents($itemPath);
233 $data = json_decode($json, true);
234
235 if (!$data) {
236 return null;
237 }
238
239 // Create Item with filename as ID
240 $item = new Item(
241 $itemId,
242 $data['name'] ?? '',
243 $data['description'] ?? '',
244 $data['itemType'] ?? 'generic',
245 $data['statModifications'] ?? []
246 );
247
248 return $item;
249 }
250
251 /**
252 * Load injury from JSON file by ID
253 *
254 * @param string $injuryId filename without extension (e.g. 'brokenLeg')
255 * @return array|null normalized injury array or null if not found
256 */
257 public static function loadInjury($injuryId)
258 {
259 $injuryPath = __DIR__ . '/../../assets/injuries/' . $injuryId . '.json';
260
261 if (!file_exists($injuryPath)) {
262 return null;
263 }
264
265 $json = file_get_contents($injuryPath);
266 $data = json_decode($json, true);
267 if (!$data)
268 return null;
269
270 // Normalize to snake_case keys matching internal storage
271 $inj = [];
272 $inj['id'] = uniqid('inj_');
273 $inj['injury_type'] = $data['injuryType'] ?? ($data['injury_type'] ?? $injuryId);
274 $inj['description'] = $data['description'] ?? '';
275 $inj['category'] = $data['category'] ?? null;
276 $inj['severity'] = $data['severity'] ?? ($data['severity'] ?? 1);
277 $inj['stat_modifications'] = $data['statModifications'] ?? $data['stat_modifications'] ?? [];
278
279 return $inj;
280 }
215 281 }
@@ -212,4 +212,70 @@ class GameHelper
212 {
212 {
213 return ucfirst(str_replace('_', ' ', $text));
213 return ucfirst(str_replace('_', ' ', $text));
214 }
214 }
215
216 /**
217 * Load item from JSON file by ID
218 *
219 * @param string $itemId The filename without extension (e.g. 'book')
220 * @return Item|null The loaded item or null if file not found
221 */
222 public static function loadItem($itemId)
223 {
224 require_once __DIR__ . '/../Classes/Item.php';
225
226 $itemPath = __DIR__ . '/../../assets/items/' . $itemId . '.json';
227
228 if (!file_exists($itemPath)) {
229 return null;
230 }
231
232 $json = file_get_contents($itemPath);
233 $data = json_decode($json, true);
234
235 if (!$data) {
236 return null;
237 }
238
239 // Create Item with filename as ID
240 $item = new Item(
241 $itemId,
242 $data['name'] ?? '',
243 $data['description'] ?? '',
244 $data['itemType'] ?? 'generic',
245 $data['statModifications'] ?? []
246 );
247
248 return $item;
249 }
250
251 /**
252 * Load injury from JSON file by ID
253 *
254 * @param string $injuryId filename without extension (e.g. 'brokenLeg')
255 * @return array|null normalized injury array or null if not found
256 */
257 public static function loadInjury($injuryId)
258 {
259 $injuryPath = __DIR__ . '/../../assets/injuries/' . $injuryId . '.json';
260
261 if (!file_exists($injuryPath)) {
262 return null;
263 }
264
265 $json = file_get_contents($injuryPath);
266 $data = json_decode($json, true);
267 if (!$data)
268 return null;
269
270 // Normalize to snake_case keys matching internal storage
271 $inj = [];
272 $inj['id'] = uniqid('inj_');
273 $inj['injury_type'] = $data['injuryType'] ?? ($data['injury_type'] ?? $injuryId);
274 $inj['description'] = $data['description'] ?? '';
275 $inj['category'] = $data['category'] ?? null;
276 $inj['severity'] = $data['severity'] ?? ($data['severity'] ?? 1);
277 $inj['stat_modifications'] = $data['statModifications'] ?? $data['stat_modifications'] ?? [];
278
279 return $inj;
280 }
215}
281}
web/src/api/game.php +297 −4
@@ -68,6 +68,253 @@ if ($method === 'POST') {
68 68 'error' => $e->getMessage()
69 69 ]);
70 70 }
71 } elseif (strpos($apiPath, 'cureInjury') !== false) {
72 // Cure an injury using an item from a kobold's inventory
73 try {
74 $userId = $input['userId'] ?? null;
75 $saveId = $input['saveId'] ?? null;
76 $koboldId = $input['koboldId'] ?? null;
77 $injuryId = $input['injuryId'] ?? null;
78 $itemId = $input['itemId'] ?? null;
79
80 if (!$userId || !$saveId || !$koboldId || !$injuryId || !$itemId) {
81 throw new \Exception('userId, saveId, koboldId, injuryId and itemId are required');
82 }
83
84 $tribe = Tribe::load($userId, $saveId);
85
86 // find kobold
87 $target = null;
88 foreach ($tribe->getKobolds(true) as $k) {
89 if ($k->getId() === $koboldId) {
90 $target = $k;
91 break;
92 }
93 }
94
95 if (!$target)
96 throw new \Exception('Kobold not found');
97
98 // find injury in kobold
99 $injuries = $target->getInjuries() ?? [];
100 $injury = null;
101 foreach ($injuries as $inj) {
102 if ($inj['id'] === $injuryId) {
103 $injury = $inj;
104 break;
105 }
106 }
107
108 if (!$injury)
109 throw new \Exception('Injury not found');
110
111 // malnourished cannot be cured via item
112 if (($injury['category'] ?? '') === 'malnourished') {
113 throw new \Exception('Malnourishment is cured via feeding at month end');
114 }
115
116 // required medicine by category
117 $required = Injury::getCureForCategory($injury['category'] ?? null);
118 if (!$required)
119 throw new \Exception('This injury cannot be cured with items');
120
121 if ($required !== $itemId) {
122 throw new \Exception('Provided item does not match required medicine');
123 }
124
125 // check kobold has the item
126 $has = false;
127 $itemName = $itemId;
128 $newItems = [];
129 foreach ($target->getItems() ?? [] as $it) {
130 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
131 if ($iid === $itemId && !$has) {
132 $has = true;
133 // capture name if present
134 if (is_array($it) && isset($it['name']))
135 $itemName = $it['name'];
136 elseif (is_object($it) && method_exists($it, 'getName'))
137 $itemName = $it->getName();
138 // consume (skip adding to newItems)
139 continue;
140 }
141 $newItems[] = $it;
142 }
143
144 if (!$has)
145 throw new \Exception('Kobold does not have the required item');
146
147 // remove injury
148 $target->removeInjury($injuryId);
149
150 // set kobold items to newItems (consumed)
151 $reflection = new ReflectionClass($target);
152 if ($reflection->hasProperty('items')) {
153 $prop = $reflection->getProperty('items');
154 $prop->setAccessible(true);
155 $prop->setValue($target, $newItems);
156 }
157
158 // save tribe
159 $tribe->save();
160
161 $koboldName = $target->getName();
162 $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');
163
164 $story = "{$koboldName} used the {$itemName} to cure their {$injuryName}.";
165
166 echo json_encode(['success' => true, 'story' => $story]);
167 } catch (\Exception $e) {
168 http_response_code(400);
169 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
170 }
171 } elseif (strpos($apiPath, 'giveItem') !== false) {
172 // Move item from tribe storage to kobold inventory and save
173 try {
174 $userId = $input['userId'] ?? null;
175 $saveId = $input['saveId'] ?? null;
176 $koboldId = $input['koboldId'] ?? null;
177 $itemId = $input['itemId'] ?? null;
178
179 if (!$userId || !$saveId || !$koboldId || !$itemId) {
180 throw new \Exception('userId, saveId, koboldId and itemId are required');
181 }
182
183 $tribe = Tribe::load($userId, $saveId);
184
185 // find item in storage
186 $storage = $tribe->getStorage() ?? [];
187 $found = null;
188 $newStorage = [];
189 foreach ($storage as $s) {
190 $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
191 if ($sid === $itemId && $found === null) {
192 $found = $s;
193 continue;
194 }
195 $newStorage[] = $s;
196 }
197
198 if ($found === null)
199 throw new \Exception('Item not found in storage');
200
201 // find kobold
202 $target = null;
203 foreach ($tribe->getKobolds(true) as $k) {
204 if ($k->getId() === $koboldId) {
205 $target = $k;
206 break;
207 }
208 }
209 if (!$target)
210 throw new \Exception('Kobold not found');
211
212 // add item to kobold
213 if (method_exists($target, 'addItem')) {
214 $target->addItem($found);
215 } else {
216 // fallback: set via reflection
217 $ref = new ReflectionClass($target);
218 if ($ref->hasProperty('items')) {
219 $prop = $ref->getProperty('items');
220 $prop->setAccessible(true);
221 $items = $prop->getValue($target) ?? [];
222 $items[] = $found;
223 $prop->setValue($target, $items);
224 }
225 }
226
227 // write back storage
228 $refT = new ReflectionClass($tribe);
229 if ($refT->hasProperty('storage')) {
230 $p = $refT->getProperty('storage');
231 $p->setAccessible(true);
232 $p->setValue($tribe, array_values($newStorage));
233 }
234
235 $tribe->save();
236
237 $koboldName = $target->getName();
238 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
239 $story = "{$itemName} was given to {$koboldName}.";
240
241 echo json_encode(['success' => true, 'story' => $story]);
242 } catch (\Exception $e) {
243 http_response_code(400);
244 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
245 }
246 } elseif (strpos($apiPath, 'returnItem') !== false) {
247 // Move item from kobold inventory back to tribe storage and save
248 try {
249 $userId = $input['userId'] ?? null;
250 $saveId = $input['saveId'] ?? null;
251 $koboldId = $input['koboldId'] ?? null;
252 $itemId = $input['itemId'] ?? null;
253
254 if (!$userId || !$saveId || !$koboldId || !$itemId) {
255 throw new \Exception('userId, saveId, koboldId and itemId are required');
256 }
257
258 $tribe = Tribe::load($userId, $saveId);
259
260 // find kobold
261 $target = null;
262 foreach ($tribe->getKobolds(true) as $k) {
263 if ($k->getId() === $koboldId) {
264 $target = $k;
265 break;
266 }
267 }
268 if (!$target)
269 throw new \Exception('Kobold not found');
270
271 // find item in kobold inventory
272 $found = null;
273 $newItems = [];
274 foreach ($target->getItems() ?? [] as $it) {
275 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
276 if ($iid === $itemId && $found === null) {
277 $found = $it;
278 continue;
279 }
280 $newItems[] = $it;
281 }
282 if ($found === null)
283 throw new \Exception('Item not found on kobold');
284
285 // set kobold items
286 if (method_exists($target, 'removeItem')) {
287 $target->removeItem($itemId);
288 } else {
289 $ref = new ReflectionClass($target);
290 if ($ref->hasProperty('items')) {
291 $p = $ref->getProperty('items');
292 $p->setAccessible(true);
293 $p->setValue($target, $newItems);
294 }
295 }
296
297 // add to tribe storage
298 $storage = $tribe->getStorage() ?? [];
299 $storage[] = $found;
300 $refT = new ReflectionClass($tribe);
301 if ($refT->hasProperty('storage')) {
302 $p = $refT->getProperty('storage');
303 $p->setAccessible(true);
304 $p->setValue($tribe, $storage);
305 }
306
307 $tribe->save();
308
309 $koboldName = $target->getName();
310 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
311 $story = "{$koboldName} returned the {$itemName} to storage.";
312
313 echo json_encode(['success' => true, 'story' => $story]);
314 } catch (\Exception $e) {
315 http_response_code(400);
316 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
317 }
71 318 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
72 319 // Save tribe setup
73 320 try {
@@ -117,12 +364,33 @@ if ($method === 'POST') {
117 364
118 365 $tribe = Tribe::load($userId, $saveId);
119 366
120 // TODO: Execute event and get story
367 // Execute event and get story. Allow passing participant kobold IDs.
121 368 $className = $input['eventType'] . "Event";
369 if (!class_exists($className))
370 throw new \Exception('Unknown event type');
122 371 $event = new $className($tribe);
372
373 // Player-started events MUST provide participants (array of kobold IDs)
374 $participants = $input['participants'] ?? null;
375 if (empty($participants) || !is_array($participants)) {
376 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
377 }
378
379 // validate count against event limits
380 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
381 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
382 $count = count($participants);
383 if ($count < $min || $count > $max) {
384 throw new \Exception("Participants must be between {$min} and {$max}");
385 }
386
387 $event->setParticipants($participants);
388
123 389 $event?->execute();
124 390 $story = $event?->getStory() ?? 'No event occurred.';
125 391
392 $tribe->save();
393
126 394 echo json_encode([
127 395 'success' => true,
128 396 'story' => $story
@@ -234,17 +502,41 @@ if ($method === 'POST') {
234 502
235 503 $tribe = Tribe::load($userId, $saveId);
236 504
237 // Get kobolds
505 // Get kobolds with full stats, items and injuries
238 506 $kobolds = [];
239 507 foreach ($tribe->getKobolds() as $kobold) {
508 $kInjuries = $kobold->getInjuries() ?? [];
509 // enrich injuries with required medicine mapping
510 foreach ($kInjuries as &$inj) {
511 $req = null;
512 if (class_exists('Injury')) {
513 $req = Injury::getCureForCategory($inj['category'] ?? null);
514 }
515 $inj['required_medicine'] = $req;
516 }
517
240 518 $kobolds[] = [
241 519 'id' => $kobold->getId(),
242 520 'name' => $kobold->getName(),
243 521 'age' => $kobold->getAge(),
244 'ageCategory' => $kobold->getAgeCategory()
522 'ageCategory' => $kobold->getAgeCategory(),
523 'stats' => [
524 'vitality' => $kobold->getStat('vitality'),
525 'intelligence' => $kobold->getStat('intelligence'),
526 'tinkering' => $kobold->getStat('tinkering'),
527 'medicine' => $kobold->getStat('medicine'),
528 'crafting' => $kobold->getStat('crafting'),
529 'personality' => $kobold->getStat('personality'),
530 'will' => $kobold->getStat('will')
531 ],
532 'items' => $kobold->getItems() ?? [],
533 'injuries' => $kInjuries
245 534 ];
246 535 }
247 536
537 // Get storage items
538 $storage = $tribe->getStorage();
539
248 540 echo json_encode([
249 541 'success' => true,
250 542 'save' => [
@@ -257,7 +549,8 @@ if ($method === 'POST') {
257 549 'last_played' => $tribe->getLastPlayed()
258 550 ],
259 551 'tribe' => [
260 'kobolds' => $kobolds
552 'kobolds' => $kobolds,
553 'storage' => $storage
261 554 ]
262 555 ]);
263 556 } catch (\Exception $e) {
@@ -68,6 +68,253 @@ if ($method === 'POST') {
68 'error' => $e->getMessage()
68 'error' => $e->getMessage()
69 ]);
69 ]);
70 }
70 }
71 } elseif (strpos($apiPath, 'cureInjury') !== false) {
72 // Cure an injury using an item from a kobold's inventory
73 try {
74 $userId = $input['userId'] ?? null;
75 $saveId = $input['saveId'] ?? null;
76 $koboldId = $input['koboldId'] ?? null;
77 $injuryId = $input['injuryId'] ?? null;
78 $itemId = $input['itemId'] ?? null;
79
80 if (!$userId || !$saveId || !$koboldId || !$injuryId || !$itemId) {
81 throw new \Exception('userId, saveId, koboldId, injuryId and itemId are required');
82 }
83
84 $tribe = Tribe::load($userId, $saveId);
85
86 // find kobold
87 $target = null;
88 foreach ($tribe->getKobolds(true) as $k) {
89 if ($k->getId() === $koboldId) {
90 $target = $k;
91 break;
92 }
93 }
94
95 if (!$target)
96 throw new \Exception('Kobold not found');
97
98 // find injury in kobold
99 $injuries = $target->getInjuries() ?? [];
100 $injury = null;
101 foreach ($injuries as $inj) {
102 if ($inj['id'] === $injuryId) {
103 $injury = $inj;
104 break;
105 }
106 }
107
108 if (!$injury)
109 throw new \Exception('Injury not found');
110
111 // malnourished cannot be cured via item
112 if (($injury['category'] ?? '') === 'malnourished') {
113 throw new \Exception('Malnourishment is cured via feeding at month end');
114 }
115
116 // required medicine by category
117 $required = Injury::getCureForCategory($injury['category'] ?? null);
118 if (!$required)
119 throw new \Exception('This injury cannot be cured with items');
120
121 if ($required !== $itemId) {
122 throw new \Exception('Provided item does not match required medicine');
123 }
124
125 // check kobold has the item
126 $has = false;
127 $itemName = $itemId;
128 $newItems = [];
129 foreach ($target->getItems() ?? [] as $it) {
130 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
131 if ($iid === $itemId && !$has) {
132 $has = true;
133 // capture name if present
134 if (is_array($it) && isset($it['name']))
135 $itemName = $it['name'];
136 elseif (is_object($it) && method_exists($it, 'getName'))
137 $itemName = $it->getName();
138 // consume (skip adding to newItems)
139 continue;
140 }
141 $newItems[] = $it;
142 }
143
144 if (!$has)
145 throw new \Exception('Kobold does not have the required item');
146
147 // remove injury
148 $target->removeInjury($injuryId);
149
150 // set kobold items to newItems (consumed)
151 $reflection = new ReflectionClass($target);
152 if ($reflection->hasProperty('items')) {
153 $prop = $reflection->getProperty('items');
154 $prop->setAccessible(true);
155 $prop->setValue($target, $newItems);
156 }
157
158 // save tribe
159 $tribe->save();
160
161 $koboldName = $target->getName();
162 $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');
163
164 $story = "{$koboldName} used the {$itemName} to cure their {$injuryName}.";
165
166 echo json_encode(['success' => true, 'story' => $story]);
167 } catch (\Exception $e) {
168 http_response_code(400);
169 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
170 }
171 } elseif (strpos($apiPath, 'giveItem') !== false) {
172 // Move item from tribe storage to kobold inventory and save
173 try {
174 $userId = $input['userId'] ?? null;
175 $saveId = $input['saveId'] ?? null;
176 $koboldId = $input['koboldId'] ?? null;
177 $itemId = $input['itemId'] ?? null;
178
179 if (!$userId || !$saveId || !$koboldId || !$itemId) {
180 throw new \Exception('userId, saveId, koboldId and itemId are required');
181 }
182
183 $tribe = Tribe::load($userId, $saveId);
184
185 // find item in storage
186 $storage = $tribe->getStorage() ?? [];
187 $found = null;
188 $newStorage = [];
189 foreach ($storage as $s) {
190 $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
191 if ($sid === $itemId && $found === null) {
192 $found = $s;
193 continue;
194 }
195 $newStorage[] = $s;
196 }
197
198 if ($found === null)
199 throw new \Exception('Item not found in storage');
200
201 // find kobold
202 $target = null;
203 foreach ($tribe->getKobolds(true) as $k) {
204 if ($k->getId() === $koboldId) {
205 $target = $k;
206 break;
207 }
208 }
209 if (!$target)
210 throw new \Exception('Kobold not found');
211
212 // add item to kobold
213 if (method_exists($target, 'addItem')) {
214 $target->addItem($found);
215 } else {
216 // fallback: set via reflection
217 $ref = new ReflectionClass($target);
218 if ($ref->hasProperty('items')) {
219 $prop = $ref->getProperty('items');
220 $prop->setAccessible(true);
221 $items = $prop->getValue($target) ?? [];
222 $items[] = $found;
223 $prop->setValue($target, $items);
224 }
225 }
226
227 // write back storage
228 $refT = new ReflectionClass($tribe);
229 if ($refT->hasProperty('storage')) {
230 $p = $refT->getProperty('storage');
231 $p->setAccessible(true);
232 $p->setValue($tribe, array_values($newStorage));
233 }
234
235 $tribe->save();
236
237 $koboldName = $target->getName();
238 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
239 $story = "{$itemName} was given to {$koboldName}.";
240
241 echo json_encode(['success' => true, 'story' => $story]);
242 } catch (\Exception $e) {
243 http_response_code(400);
244 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
245 }
246 } elseif (strpos($apiPath, 'returnItem') !== false) {
247 // Move item from kobold inventory back to tribe storage and save
248 try {
249 $userId = $input['userId'] ?? null;
250 $saveId = $input['saveId'] ?? null;
251 $koboldId = $input['koboldId'] ?? null;
252 $itemId = $input['itemId'] ?? null;
253
254 if (!$userId || !$saveId || !$koboldId || !$itemId) {
255 throw new \Exception('userId, saveId, koboldId and itemId are required');
256 }
257
258 $tribe = Tribe::load($userId, $saveId);
259
260 // find kobold
261 $target = null;
262 foreach ($tribe->getKobolds(true) as $k) {
263 if ($k->getId() === $koboldId) {
264 $target = $k;
265 break;
266 }
267 }
268 if (!$target)
269 throw new \Exception('Kobold not found');
270
271 // find item in kobold inventory
272 $found = null;
273 $newItems = [];
274 foreach ($target->getItems() ?? [] as $it) {
275 $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
276 if ($iid === $itemId && $found === null) {
277 $found = $it;
278 continue;
279 }
280 $newItems[] = $it;
281 }
282 if ($found === null)
283 throw new \Exception('Item not found on kobold');
284
285 // set kobold items
286 if (method_exists($target, 'removeItem')) {
287 $target->removeItem($itemId);
288 } else {
289 $ref = new ReflectionClass($target);
290 if ($ref->hasProperty('items')) {
291 $p = $ref->getProperty('items');
292 $p->setAccessible(true);
293 $p->setValue($target, $newItems);
294 }
295 }
296
297 // add to tribe storage
298 $storage = $tribe->getStorage() ?? [];
299 $storage[] = $found;
300 $refT = new ReflectionClass($tribe);
301 if ($refT->hasProperty('storage')) {
302 $p = $refT->getProperty('storage');
303 $p->setAccessible(true);
304 $p->setValue($tribe, $storage);
305 }
306
307 $tribe->save();
308
309 $koboldName = $target->getName();
310 $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
311 $story = "{$koboldName} returned the {$itemName} to storage.";
312
313 echo json_encode(['success' => true, 'story' => $story]);
314 } catch (\Exception $e) {
315 http_response_code(400);
316 echo json_encode(['success' => false, 'error' => $e->getMessage()]);
317 }
71 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
318 } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
72 // Save tribe setup
319 // Save tribe setup
73 try {
320 try {
@@ -117,12 +364,33 @@ if ($method === 'POST') {
117
364
118 $tribe = Tribe::load($userId, $saveId);
365 $tribe = Tribe::load($userId, $saveId);
119
366
120 // TODO: Execute event and get story
367 // Execute event and get story. Allow passing participant kobold IDs.
121 $className = $input['eventType'] . "Event";
368 $className = $input['eventType'] . "Event";
369 if (!class_exists($className))
370 throw new \Exception('Unknown event type');
122 $event = new $className($tribe);
371 $event = new $className($tribe);
372
373 // Player-started events MUST provide participants (array of kobold IDs)
374 $participants = $input['participants'] ?? null;
375 if (empty($participants) || !is_array($participants)) {
376 throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
377 }
378
379 // validate count against event limits
380 $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
381 $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
382 $count = count($participants);
383 if ($count < $min || $count > $max) {
384 throw new \Exception("Participants must be between {$min} and {$max}");
385 }
386
387 $event->setParticipants($participants);
388
123 $event?->execute();
389 $event?->execute();
124 $story = $event?->getStory() ?? 'No event occurred.';
390 $story = $event?->getStory() ?? 'No event occurred.';
125
391
392 $tribe->save();
393
126 echo json_encode([
394 echo json_encode([
127 'success' => true,
395 'success' => true,
128 'story' => $story
396 'story' => $story
@@ -234,17 +502,41 @@ if ($method === 'POST') {
234
502
235 $tribe = Tribe::load($userId, $saveId);
503 $tribe = Tribe::load($userId, $saveId);
236
504
237 // Get kobolds
505 // Get kobolds with full stats, items and injuries
238 $kobolds = [];
506 $kobolds = [];
239 foreach ($tribe->getKobolds() as $kobold) {
507 foreach ($tribe->getKobolds() as $kobold) {
508 $kInjuries = $kobold->getInjuries() ?? [];
509 // enrich injuries with required medicine mapping
510 foreach ($kInjuries as &$inj) {
511 $req = null;
512 if (class_exists('Injury')) {
513 $req = Injury::getCureForCategory($inj['category'] ?? null);
514 }
515 $inj['required_medicine'] = $req;
516 }
517
240 $kobolds[] = [
518 $kobolds[] = [
241 'id' => $kobold->getId(),
519 'id' => $kobold->getId(),
242 'name' => $kobold->getName(),
520 'name' => $kobold->getName(),
243 'age' => $kobold->getAge(),
521 'age' => $kobold->getAge(),
244 'ageCategory' => $kobold->getAgeCategory()
522 'ageCategory' => $kobold->getAgeCategory(),
523 'stats' => [
524 'vitality' => $kobold->getStat('vitality'),
525 'intelligence' => $kobold->getStat('intelligence'),
526 'tinkering' => $kobold->getStat('tinkering'),
527 'medicine' => $kobold->getStat('medicine'),
528 'crafting' => $kobold->getStat('crafting'),
529 'personality' => $kobold->getStat('personality'),
530 'will' => $kobold->getStat('will')
531 ],
532 'items' => $kobold->getItems() ?? [],
533 'injuries' => $kInjuries
245 ];
534 ];
246 }
535 }
247
536
537 // Get storage items
538 $storage = $tribe->getStorage();
539
248 echo json_encode([
540 echo json_encode([
249 'success' => true,
541 'success' => true,
250 'save' => [
542 'save' => [
@@ -257,7 +549,8 @@ if ($method === 'POST') {
257 'last_played' => $tribe->getLastPlayed()
549 'last_played' => $tribe->getLastPlayed()
258 ],
550 ],
259 'tribe' => [
551 'tribe' => [
260 'kobolds' => $kobolds
552 'kobolds' => $kobolds,
553 'storage' => $storage
261 ]
554 ]
262 ]);
555 ]);
263 } catch (\Exception $e) {
556 } catch (\Exception $e) {