# TribeGen - AI Coding Agent Instructions
## Architecture Overview
**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.
### Storage Architecture
- **Authentication**: SQLite database (users table only) — see [src/Database/Database.php](src/Database/Database.php)
- **Game State**: JSON files organized by user → save → entities (tribe, kobolds, items, NPCs)
- **SaveManager**: Single abstraction for all file I/O — see [src/System/SaveManager.php](src/System/SaveManager.php)
- Path pattern: `data/saves/{userId}/{saveId}/` containing `save.json`, `kobolds.json`, `items.json`, `npcs.json`
**Critical Pattern**: All game classes use `fromArray()/toArray()` for JSON serialization. Changes to class properties require updating both methods.
### Core Entity Classes
1. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager
2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage
3. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat)
4. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field)
5. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10
### Event System
- **Base Class**: `Event` — abstract execute() method that modifies tribe state and sets `$this->story`
- **EventManager** ([src/Events/EventManager.php](src/Events/EventManager.php)): Loads enabled events per save, executes them
- **Implementations**: [HuntingEvent](src/Events/HuntingEvent.php), [ExplorationEvent](src/Events/ExplorationEvent.php), [FarmingEvent](src/Events/FarmingEvent.php)
- **Creating New Events**: Extend `Event`, implement `execute()`, return narrative story via `$this->story`
- **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
## API Endpoints
All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `saveId` in POST body:
- **POST `/api/game/generation`**: Create new tribe with 20 random kobolds
- **POST `/api/game/load?saveId=X`**: Load tribe state
- **POST `/api/game/save`**: Save tribe setup (currently a TODO)
- **POST `/api/game/event`**: Execute single event
- **POST `/api/game/endMonth`**: Progress month, age kobolds, apply injuries, execute month events
**Pattern**: All responses use `{ success: boolean, error?: string, ...data }`
## Key Conventions
### IDs and Naming
- **User IDs**: Database `user.id` (integer)
- **Save IDs**: Numeric string generated by `SaveManager::generateSaveId()`
- **Kobold IDs**: Prefixed with `kob_` + uniqid (example: `kob_678abc123`)
- **Method Names**: Use camelCase, boolean getters are `is*()` or `get*()` followed by value
### Stats System
- All stats are 0-100 internally, displayed as text ranges (0-10: "terrible", 90-100: "godlike")
- Stat checks: Get base value → apply item modifications → check result
- Items can boost/reduce any stat independently
### Kobold Lifecycle
- **Age Tiers**: egg → baby → adult → old → very_old (affects food consumption and sprite)
- **Sprite Morphs**: Loaded from `assets/sprites/{morph}/` directory, copied to save folder on generation
- **Genetic Inheritance**: Each kobold tracks `fatherId`, `motherId` for generation tracking
### Food System
- `Tribe::foodCount` tracks stored food
- Age tiers have food requirements (egg: 0, baby: 0.5, adult: 1.0, old: 0.6, very_old: 0.4 units)
- `endMonth()` deducts food and reports shortage via story
## Development Workflow
1. **Loading Data**: `$tribe = Tribe::load($userId, $saveId);` — automatically loads kobolds, storage, items
2. **Modifying Tribe**: Add kobolds with `$tribe->addKobold($kobold)`, modify state, then `$tribe->save()` writes all JSON
3. **Adding Features**: Update entity class → add `fromArray()/toArray()` support → update API endpoint
4. **Testing Events**: Create event class extending `Event`, test via EventManager or direct instantiation
## Common File Locations
| Purpose | File |
|---------|------|
| Database setup | [src/Database/Database.php](src/Database/Database.php) |
| User auth | [src/Classes/User.php](src/Classes/User.php), [src/api/auth.php](src/api/auth.php) |
| Game state | [src/Classes/Tribe.php](src/Classes/Tribe.php) |
| Kobold logic | [src/Classes/Kobold.php](src/Classes/Kobold.php) |
| Storage abstraction | [src/System/SaveManager.php](src/System/SaveManager.php) |
| Game routes | [src/api/game.php](src/api/game.php) |
| Frontend | [public/js/app.js](public/js/app.js), [public/index.html](public/index.html) |
## Documentation References
- **Architecture Details**: [ARCHITECTURE.md](ARCHITECTURE.md) — database schema, class hierarchy, API flow
- **Quick Reference**: [QUICK_REFERENCE.md](QUICK_REFERENCE.md) — refactoring summary, file changes
- **Getting Started**: [README.md](README.md) — installation, features, event creation guide
## Important Storage Policy
- **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.
TribeGen - AI Coding Agent Instructions
Architecture Overview
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.
Storage Architecture
- Authentication: SQLite database (users table only) — see src/Database/Database.php
- Game State: JSON files organized by user → save → entities (tribe, kobolds, items, NPCs)
- SaveManager: Single abstraction for all file I/O — see src/System/SaveManager.php
- Path pattern:
data/saves/{userId}/{saveId}/containingsave.json,kobolds.json,items.json,npcs.json
Critical Pattern: All game classes use fromArray()/toArray() for JSON serialization. Changes to class properties require updating both methods.
Core Entity Classes
1. Tribe (src/Classes/Tribe.php): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager 2. Kobold (src/Classes/Kobold.php): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage 3. Item (src/Classes/Item.php): Named items with stat modifications (each mod is -5 to +5 per stat) 4. NPC (src/Classes/NPC.php): Non-player characters/tribes (extensible via JSON data field) 5. Injury (src/Classes/Injury.php): Injury type, category (wound/fracture), severity 0-10
Event System
- Base Class:
Event— abstract execute() method that modifies tribe state and sets$this->story - EventManager (src/Events/EventManager.php): Loads enabled events per save, executes them
- Implementations: HuntingEvent, ExplorationEvent, FarmingEvent
- Creating New Events: Extend
Event, implementexecute(), return narrative story via$this->story - Example: ExplorationEvent — 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
API Endpoints
All endpoints in src/api/game.php require userId and saveId in POST body:
- POST
/api/game/generation: Create new tribe with 20 random kobolds - POST
/api/game/load?saveId=X: Load tribe state - POST
/api/game/save: Save tribe setup (currently a TODO) - POST
/api/game/event: Execute single event - POST
/api/game/endMonth: Progress month, age kobolds, apply injuries, execute month events
Pattern: All responses use { success: boolean, error?: string, ...data }
Key Conventions
IDs and Naming
- User IDs: Database
user.id(integer) - Save IDs: Numeric string generated by
SaveManager::generateSaveId() - Kobold IDs: Prefixed with
kob_+ uniqid (example:kob_678abc123) - Method Names: Use camelCase, boolean getters are
is*()orget*()followed by value
Stats System
- All stats are 0-100 internally, displayed as text ranges (0-10: "terrible", 90-100: "godlike")
- Stat checks: Get base value → apply item modifications → check result
- Items can boost/reduce any stat independently
Kobold Lifecycle
- Age Tiers: egg → baby → adult → old → very_old (affects food consumption and sprite)
- Sprite Morphs: Loaded from
assets/sprites/{morph}/directory, copied to save folder on generation - Genetic Inheritance: Each kobold tracks
fatherId,motherIdfor generation tracking
Food System
Tribe::foodCounttracks stored food- Age tiers have food requirements (egg: 0, baby: 0.5, adult: 1.0, old: 0.6, very_old: 0.4 units)
endMonth()deducts food and reports shortage via story
Development Workflow
1. Loading Data: $tribe = Tribe::load($userId, $saveId); — automatically loads kobolds, storage, items 2. Modifying Tribe: Add kobolds with $tribe->addKobold($kobold), modify state, then $tribe->save() writes all JSON 3. Adding Features: Update entity class → add fromArray()/toArray() support → update API endpoint 4. Testing Events: Create event class extending Event, test via EventManager or direct instantiation
Common File Locations
| Purpose | File |
|---|---|
| Database setup | src/Database/Database.php |
| User auth | src/Classes/User.php, src/api/auth.php |
| Game state | src/Classes/Tribe.php |
| Kobold logic | src/Classes/Kobold.php |
| Storage abstraction | src/System/SaveManager.php |
| Game routes | src/api/game.php |
| Frontend | public/js/app.js, public/index.html |
Documentation References
- Architecture Details: ARCHITECTURE.md — database schema, class hierarchy, API flow
- Quick Reference: QUICK_REFERENCE.md — refactoring summary, file changes
- Getting Started: README.md — installation, features, event creation guide
Source
| 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, fighting, 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 | ``` |
| 95 | # TribeGen - AI Coding Agent Instructions |
| 96 | |
| 97 | ## Architecture Overview |
| 98 | |
| 99 | **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. |
| 100 | |
| 101 | ### Storage Architecture |
| 102 | - **Authentication**: SQLite database (users table only) — see [src/Database/Database.php](src/Database/Database.php) |
| 103 | - **Game State**: JSON files organized by user → save → entities (tribe, kobolds, items, NPCs) |
| 104 | - **SaveManager**: Single abstraction for all file I/O — see [src/System/SaveManager.php](src/System/SaveManager.php) |
| 105 | - Path pattern: `data/saves/{userId}/{saveId}/` containing `save.json`, `kobolds.json`, `items.json`, `npcs.json` |
| 106 | |
| 107 | **Critical Pattern**: All game classes use `fromArray()/toArray()` for JSON serialization. Changes to class properties require updating both methods. |
| 108 | |
| 109 | ### Core Entity Classes |
| 110 | 1. **Tribe** ([src/Classes/Tribe.php](src/Classes/Tribe.php#L1-L100)): Manages kobolds, food/storage, month/season progression, loads/saves via SaveManager |
| 111 | 2. **Kobold** ([src/Classes/Kobold.php](src/Classes/Kobold.php#L1-L100)): Individual stats (vitality, intelligence, fighting, medicine, crafting, personality, will), injuries, items, genetic lineage |
| 112 | 3. **Item** ([src/Classes/Item.php](src/Classes/Item.php)): Named items with stat modifications (each mod is -5 to +5 per stat) |
| 113 | 4. **NPC** ([src/Classes/NPC.php](src/Classes/NPC.php)): Non-player characters/tribes (extensible via JSON `data` field) |
| 114 | 5. **Injury** ([src/Classes/Injury.php](src/Classes/Injury.php)): Injury type, category (wound/fracture), severity 0-10 |
| 115 | |
| 116 | ### Event System |
| 117 | - **Base Class**: `Event` — abstract execute() method that modifies tribe state and sets `$this->story` |
| 118 | - **EventManager** ([src/Events/EventManager.php](src/Events/EventManager.php)): Loads enabled events per save, executes them |
| 119 | - **Implementations**: [HuntingEvent](src/Events/HuntingEvent.php), [ExplorationEvent](src/Events/ExplorationEvent.php), [FarmingEvent](src/Events/FarmingEvent.php) |
| 120 | - **Creating New Events**: Extend `Event`, implement `execute()`, return narrative story via `$this->story` |
| 121 | - **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 |
| 122 | |
| 123 | ## API Endpoints |
| 124 | |
| 125 | All endpoints in [src/api/game.php](src/api/game.php) require `userId` and `saveId` in POST body: |
| 126 | |
| 127 | - **POST `/api/game/generation`**: Create new tribe with 20 random kobolds |
| 128 | - **POST `/api/game/load?saveId=X`**: Load tribe state |
| 129 | - **POST `/api/game/save`**: Save tribe setup (currently a TODO) |
| 130 | - **POST `/api/game/event`**: Execute single event |
| 131 | - **POST `/api/game/endMonth`**: Progress month, age kobolds, apply injuries, execute month events |
| 132 | |
| 133 | **Pattern**: All responses use `{ success: boolean, error?: string, ...data }` |
| 134 | |
| 135 | ## Key Conventions |
| 136 | |
| 137 | ### IDs and Naming |
| 138 | - **User IDs**: Database `user.id` (integer) |
| 139 | - **Save IDs**: Numeric string generated by `SaveManager::generateSaveId()` |
| 140 | - **Kobold IDs**: Prefixed with `kob_` + uniqid (example: `kob_678abc123`) |
| 141 | - **Method Names**: Use camelCase, boolean getters are `is*()` or `get*()` followed by value |
| 142 | |
| 143 | ### Stats System |
| 144 | - All stats are 0-100 internally, displayed as text ranges (0-10: "terrible", 90-100: "godlike") |
| 145 | - Stat checks: Get base value → apply item modifications → check result |
| 146 | - Items can boost/reduce any stat independently |
| 147 | |
| 148 | ### Kobold Lifecycle |
| 149 | - **Age Tiers**: egg → baby → adult → old → very_old (affects food consumption and sprite) |
| 150 | - **Sprite Morphs**: Loaded from `assets/sprites/{morph}/` directory, copied to save folder on generation |
| 151 | - **Genetic Inheritance**: Each kobold tracks `fatherId`, `motherId` for generation tracking |
| 152 | |
| 153 | ### Food System |
| 154 | - `Tribe::foodCount` tracks stored food |
| 155 | - Age tiers have food requirements (egg: 0, baby: 0.5, adult: 1.0, old: 0.6, very_old: 0.4 units) |
| 156 | - `endMonth()` deducts food and reports shortage via story |
| 157 | |
| 158 | ## Development Workflow |
| 159 | |
| 160 | 1. **Loading Data**: `$tribe = Tribe::load($userId, $saveId);` — automatically loads kobolds, storage, items |
| 161 | 2. **Modifying Tribe**: Add kobolds with `$tribe->addKobold($kobold)`, modify state, then `$tribe->save()` writes all JSON |
| 162 | 3. **Adding Features**: Update entity class → add `fromArray()/toArray()` support → update API endpoint |
| 163 | 4. **Testing Events**: Create event class extending `Event`, test via EventManager or direct instantiation |
| 164 | |
| 165 | ## Common File Locations |
| 166 | |
| 167 | | Purpose | File | |
| 168 | |---------|------| |
| 169 | | Database setup | [src/Database/Database.php](src/Database/Database.php) | |
| 170 | | User auth | [src/Classes/User.php](src/Classes/User.php), [src/api/auth.php](src/api/auth.php) | |
| 171 | | Game state | [src/Classes/Tribe.php](src/Classes/Tribe.php) | |
| 172 | | Kobold logic | [src/Classes/Kobold.php](src/Classes/Kobold.php) | |
| 173 | | Storage abstraction | [src/System/SaveManager.php](src/System/SaveManager.php) | |
| 174 | | Game routes | [src/api/game.php](src/api/game.php) | |
| 175 | | Frontend | [public/js/app.js](public/js/app.js), [public/index.html](public/index.html) | |
| 176 | |
| 177 | ## Documentation References |
| 178 | |
| 179 | - **Architecture Details**: [ARCHITECTURE.md](ARCHITECTURE.md) — database schema, class hierarchy, API flow |
| 180 | - **Quick Reference**: [QUICK_REFERENCE.md](QUICK_REFERENCE.md) — refactoring summary, file changes |
| 181 | - **Getting Started**: [README.md](README.md) — installation, features, event creation guide |