# Game Systems

## Combat System

### Core Concepts

**Turn-Based Combat:**
- Initiative rolls determine turn order (d20 + speed stat)
- Each combatant takes one action per turn
- Effects (buffs/debuffs/DoT) process at start of turn
- Combat continues until one side is defeated

### Damage Calculations

| Attack Type | Formula | Min Damage |
|-------------|---------|------------|
| **Physical** | weapon.damage + (strength / 2) - target.defense | 1 |
| **Magical** | spell.damage + (magic_power / 2) - target.resistance | 1 |
| **Critical Hit** | base_damage × weapon.crit_multiplier | - |

**Critical Hit System:**
- **Design Choice:** Critical hits only, no damage variance (JRPG-style)
- Base damage is **deterministic** (always same result for same stats)
- Random element is **only** whether attack crits
- Default crit_chance: **5%** (0.05)
- Default crit_multiplier: **2.0×** (double damage)
- Weapons can have different crit_chance and crit_multiplier values

**Why This Design:**
- Predictable damage for tactical planning
- Exciting moments when crits occur
- Easier to balance than full damage ranges
- Simpler AI prompting (no damage variance to explain)

### Combat Flow

| Phase | Actions |
|-------|---------|
| **1. Initialize Combat** | Roll initiative for all combatants<br>Sort by initiative (highest first)<br>Set turn order |
| **2. Turn Start** | Process all active effects on current combatant<br>Check for stun (skip turn if stunned)<br>Reduce spell cooldowns |
| **3. Action Phase** | Player/AI selects action (attack, cast spell, use item, defend)<br>Execute action<br>Apply damage/effects<br>Check for death |
| **4. Turn End** | Advance to next combatant<br>If back to first combatant, increment round number<br>Check for combat end condition |
| **5. Combat Resolution** | **Victory:** Distribute XP and loot<br>**Defeat:** Handle character death/respawn |

### Action Types

| Action | Description | Examples |
|--------|-------------|----------|
| **Attack** | Physical weapon attack | Sword strike, bow shot |
| **Cast Spell** | Use magical ability | Fireball, heal, curse |
| **Use Item** | Consume item from inventory | Health potion, scroll |
| **Defend** | Defensive stance | +defense for 1 turn |
| **Special Ability** | Class-specific skill | Shield bash, stealth strike |

### Effect Mechanics

**Effect Processing:**
- Effects have **duration** (turns remaining)
- Effects can **stack** (multiple applications increase power)
- Effects are processed at **start of turn**
- Effects expire automatically when duration reaches 0

**Stacking Mechanics:**
- Effects stack up to **max_stacks** (default 5, configurable per effect)
- Re-applying same effect increases stacks (up to max)
- Duration **refreshes** on re-application (does not stack cumulatively)
- Power scales linearly with stacks: 3 stacks × 5 damage = 15 damage per turn
- Once at max stacks, re-application only refreshes duration

**Stacking Examples:**
- Poison (power=5, max_stacks=5): 3 stacks = 15 damage per turn
- Defense buff (power=3, max_stacks=5): 2 stacks = +6 defense
- Applying poison 6 times = 5 stacks (capped), duration refreshed each time

**Shield Effect Mechanics:**
- Shield absorbs damage **before HP loss**
- Shield strength = power × stacks
- Partial absorption: If damage > shield, shield breaks and remaining damage goes to HP
- Full absorption: If damage <= shield, all damage absorbed, shield reduced
- Shield depletes when power reaches 0 or duration expires

**Effect Interaction with Stats:**
- BUFF/DEBUFF effects modify stats via `get_effective_stats()`
- Stat modifications are temporary (only while effect is active)
- Debuffs **cannot reduce stats below 1** (minimum clamping)
- Buffs stack with equipment and skill bonuses

### AI-Generated Combat Narrative

**Narrative Generation:**
- After each combat action executes, generate narrative description
- Code calculates mechanics ("Aragorn attacks Goblin for 15 damage (critical hit!)")
- AI generates flavor ("Aragorn's blade finds a gap in the goblin's armor, striking a devastating blow!")

**Model Selection:**

| Encounter Type | Model Tier |
|----------------|------------|
| Standard encounters | STANDARD (Haiku) |
| Boss fights | PREMIUM (Sonnet) |
| Free tier users | FREE (Replicate) |

---

## Ability System

### Overview

Abilities are actions that can be used in combat (attacks, spells, skills). The system is **data-driven** using YAML configuration files.

### Ability Components

| Component | Description |
|-----------|-------------|
| **Base Power** | Starting damage or healing value |
| **Scaling Stat** | Which stat enhances the ability (STR, INT, etc.) |
| **Scaling Factor** | Multiplier for scaling (default 0.5) |
| **Mana Cost** | MP required to use |
| **Cooldown** | Turns before ability can be used again |
| **Effects** | Status effects applied on hit |

### Power Calculation

```
Final Power = base_power + (scaling_stat × scaling_factor)
Minimum power is always 1
```

**Examples:**
- **Cleave** (physical skill): base_power=15, scaling_stat=STRENGTH, scaling_factor=0.5
  - With 20 STR: 15 + (20 × 0.5) = 25 power
- **Fireball** (spell): base_power=30, scaling_stat=INTELLIGENCE, scaling_factor=0.5
  - With 16 INT: 30 + (16 × 0.5) = 38 power

### Mana & Cooldown Mechanics

**Mana System:**
- Each ability has a mana_cost (0 for basic attacks)
- Combatant must have current_mp >= mana_cost
- Mana is consumed when ability is used
- Mana regeneration happens between combat encounters

**Cooldown System:**
- Abilities can have cooldowns (turns before re-use)
- Cooldown starts when ability is used
- Cooldowns tick down at start of each turn
- 0 cooldown = can use every turn

**Example:**
- Power Strike: mana_cost=10, cooldown=3
- Use on turn 1 → Can't use again until turn 5

### Effect Application

Abilities can apply effects to targets:

```yaml
effects_applied:
  - effect_id: "burn"
    name: "Burning"
    effect_type: "dot"
    duration: 3
    power: 5
    max_stacks: 3
```

When ability hits, all `effects_applied` are added to the target's `active_effects`.

### Data-Driven Design

**Benefits:**
- Game designers can add/modify abilities without code changes
- Easy balancing through config file edits
- Version control friendly (text files)
- Hot-reloading capable (reload without restart)

**Workflow:**
1. Create YAML file in `/app/data/abilities/`
2. Define ability properties
3. AbilityLoader automatically loads on request
4. Abilities available for use immediately

**Example YAML Structure:**
```yaml
ability_id: "shield_bash"
name: "Shield Bash"
description: "Bash enemy with shield, dealing damage and stunning"
ability_type: "skill"
base_power: 10
damage_type: "physical"
scaling_stat: "strength"
scaling_factor: 0.5
mana_cost: 5
cooldown: 2
effects_applied:
  - effect_id: "stun_1"
    name: "Stunned"
    effect_type: "stun"
    duration: 1
    power: 0
```

### Ability Types

| Type | Description | Typical Use |
|------|-------------|-------------|
| **ATTACK** | Basic physical attack | Default melee/ranged attacks |
| **SPELL** | Magical ability | Fireballs, heals, buffs |
| **SKILL** | Class-specific ability | Shield bash, backstab, power strike |
| **ITEM_USE** | Using consumable | Health potion, scroll |
| **DEFEND** | Defensive action | Defensive stance, dodge |

---

## Multiplayer Party System

### Session Formation

| Step | Action | Details |
|------|--------|---------|
| 1 | Create Session | Leader creates session with configuration |
| 2 | Generate Code | System generates invite code |
| 3 | Join Session | Other players join via invite code |
| 4 | Start Game | Session begins when min_players met |

**Max Party Size by Tier:**

| Subscription Tier | Max Party Size |
|-------------------|----------------|
| FREE | Solo only (1) |
| BASIC | 2 players |
| PREMIUM | 6 players |
| ELITE | 10 players |

### Turn Flow

1. Turn order determined by initiative
2. Active player takes action
3. Action queued to RQ for AI processing
4. AI response generated
5. Game state updated in Appwrite
6. All party members notified via Appwrite Realtime
7. Next player's turn

### Session End Conditions

| Condition | Result |
|-----------|--------|
| Manual end by leader | Session completed |
| Below min_players for timeout duration | Session timeout |
| All players leave | Session completed |
| Total party wipeout in combat | Session completed (defeat) |

### Post-Session

- Players keep all loot/gold earned
- Session logs saved:
  - **Free tier:** 7 days
  - **Basic:** 14 days
  - **Premium:** 30 days
  - **Elite:** 90 days
- Exportable as Markdown

### Realtime Synchronization

**Appwrite Realtime Features:**
- WebSocket connections for multiplayer
- Automatic updates when game state changes
- No polling required
- Built-in connection management
- Automatic reconnection

**Update Flow:**
1. Player takes action
2. Backend updates Appwrite document
3. Appwrite triggers realtime event
4. All subscribed clients receive update
5. UI updates automatically

---

## Marketplace System

### Overview

| Aspect | Details |
|--------|---------|
| **Access Level** | Premium+ subscription tiers only |
| **Currency** | In-game gold only (no real money trading) |
| **Listing Types** | Fixed price or auction |
| **Transaction Fee** | None (may implement later for economy balance) |

### Auction System

**eBay-Style Bidding:**

| Feature | Description |
|---------|-------------|
| **Starting Bid** | Minimum bid set by seller |
| **Buyout Price** | Optional instant-win price |
| **Duration** | 24, 48, or 72 hours |
| **Bidding** | Must exceed current bid |
| **Auto-Win** | Buyout price triggers instant sale |
| **Winner** | Highest bidder when auction ends |
| **Notifications** | Outbid alerts via Appwrite Realtime |

**Auction Processing:**
- RQ periodic task checks for ended auctions every 5 minutes
- Winner receives item, seller receives gold
- If no bids, item returned to seller

### Fixed Price Listings

| Feature | Description |
|---------|-------------|
| **Price** | Set by seller |
| **Purchase** | Immediate transaction |
| **Availability** | First come, first served |

### Item Restrictions

**Non-Tradeable Items:**
- Quest items
- Character-bound items
- Items marked `is_tradeable: false`

### Marketplace Features by Tier

| Tier | Access | Max Active Listings | Priority |
|------|--------|---------------------|----------|
| FREE | ✗ | - | - |
| BASIC | ✗ | - | - |
| PREMIUM | ✓ | 10 | Normal |
| ELITE | ✓ | 25 | Priority (shown first) |

---

## NPC Shop System

### Overview

**Game-Run Shop:**
- Sells basic items at fixed prices
- Always available (not affected by marketplace access)
- Provides gold sink to prevent inflation

### Shop Categories

| Category | Items | Tier Range |
|----------|-------|------------|
| **Consumables** | Health potions, mana potions, antidotes | All |
| **Basic Weapons** | Swords, bows, staves | 1-2 |
| **Basic Armor** | Helmets, chest plates, boots | 1-2 |
| **Crafting Materials** | (Future feature) | - |

### Pricing Strategy

- Basic items priced reasonably for new players
- Prices higher than marketplace average (encourages player economy)
- No selling back to shop (or at 50% value to prevent abuse)

---

## Progression Systems

### Experience & Leveling

| Source | XP Gain |
|--------|---------|
| Combat victory | Based on enemy difficulty |
| Quest completion | Fixed quest reward |
| Story milestones | Major plot points |
| Exploration | Discovering new locations |

**Level Progression:**
- XP required increases per level (exponential curve)
- Each level grants +1 skill point
- Stats may increase based on class

### Loot System

**Loot Sources:**
- Defeated enemies
- Treasure chests
- Quest rewards
- Boss encounters

**Loot Quality Tiers:**

| Tier | Color | Drop Rate | Example |
|------|-------|-----------|---------|
| Common | Gray | 60% | Basic health potion |
| Uncommon | Green | 25% | Enhanced sword |
| Rare | Blue | 10% | Fire-enchanted blade |
| Epic | Purple | 4% | Legendary armor |
| Legendary | Orange | 1% | Artifact weapon |

**Boss Loot:**
- Bosses always drop rare+ items
- Guaranteed unique item per boss
- Chance for legendary items

---

## Quest System (Future)

### Quest Types

| Type | Description | Example |
|------|-------------|---------|
| **Main Story** | Plot progression | "Defeat the Dark Lord" |
| **Side Quest** | Optional content | "Help the blacksmith" |
| **Daily Quest** | Repeatable daily | "Slay 10 goblins" |
| **World Event** | Server-wide | "Defend the city" |

### Quest Rewards

- Gold
- Experience
- Items (equipment, consumables)
- Unlock locations/features
- Reputation with factions

---

## Economy & Balance

### Gold Sources (Inflow)

| Source | Amount |
|--------|--------|
| Combat loot | 10-100 per encounter |
| Quest rewards | 100-1000 per quest |
| Marketplace sales | Player-driven |

### Gold Sinks (Outflow)

| Sink | Cost |
|------|------|
| NPC shop purchases | Varies |
| Skill respec | Level × 100 gold |
| Fast travel | 50-500 per location |
| Equipment repairs | (Future feature) |

### Economy Monitoring

**Metrics to Track:**
- Average gold per player
- Marketplace price trends
- Item availability
- Transaction volume

**Balancing Actions:**
- Adjust NPC shop prices
- Introduce new gold sinks
- Modify loot drop rates
- Implement transaction fees if needed

---

## PvP Arena (Future Feature)

### Planned Features

| Feature | Description |
|---------|-------------|
| **Arena Mode** | Optional combat mode |
| **Matchmaking** | Ranked and casual |
| **Rewards** | Exclusive PvP items |
| **Leaderboard** | Season-based rankings |
| **Restrictions** | Balanced gear/levels |

**Note:** PvP is entirely optional and separate from main game.

---

## Guild System (Future Feature)

### Planned Features

| Feature | Description |
|---------|-------------|
| **Guild Creation** | Player-run organizations |
| **Guild Bank** | Shared resources |
| **Guild Quests** | Cooperative challenges |
| **Guild Halls** | Customizable spaces |
| **Guild Wars** | PvP guild vs guild |

---

## World Events (Future Feature)

### Planned Features

| Feature | Description |
|---------|-------------|
| **Server-Wide Events** | All players can participate |
| **Timed Events** | Limited duration |
| **Cooperative Goals** | Community objectives |
| **Exclusive Rewards** | Event-only items |
| **Story Impact** | Events affect world state |

---

## Achievements (Future Feature)

### Planned Categories

| Category | Examples |
|----------|----------|
| **Combat** | "Defeat 100 enemies", "Win without taking damage" |
| **Exploration** | "Discover all locations", "Travel 1000 miles" |
| **Collection** | "Collect all legendary items", "Complete skill tree" |
| **Social** | "Join a guild", "Complete 10 multiplayer sessions" |
| **Story** | "Complete main story", "Complete all side quests" |

**Rewards:**
- Titles
- Cosmetic items
- Special abilities
- Achievement points

---

## Crafting System (Future Feature)

### Planned Features

| Feature | Description |
|---------|-------------|
| **Recipes** | Learn from quests, loot, NPCs |
| **Materials** | Gather from enemies, exploration |
| **Crafting Stations** | Special locations required |
| **Item Enhancement** | Upgrade existing items |
| **Unique Items** | Crafted-only items |

---

## Common Patterns

### AI Cost Tracking

**Log every AI call:**
- User ID
- Model used
- Cost tier
- Tokens used
- Timestamp

**Daily Limits:**
- Track usage per user per day
- Block calls if limit exceeded
- Graceful degradation message

### Error Handling

**Consistent error format:**
```json
{
  "error": "Error message",
  "code": "ERROR_CODE",
  "details": {}
}
```

### Logging

**Structured logging with context:**
- Session ID
- Character ID
- Action type
- Results
- Timestamp

---

## Glossary

| Term | Definition |
|------|------------|
| **DM** | Dungeon Master (AI in this case) |
| **NPC** | Non-Player Character |
| **DoT** | Damage over Time |
| **HoT** | Heal over Time |
| **AoE** | Area of Effect |
| **XP** | Experience Points |
| **PWA** | Progressive Web App |
