```instructions # 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](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