Files
Code_of_Conquest/api/docs/GAME_SYSTEMS.md

838 lines
23 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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
**XP Sources:**
| Source | XP Gain | Notes |
|--------|---------|-------|
| Combat victory | Based on enemy `experience_reward` field | Divided evenly among party members |
| Quest completion | Fixed quest reward | Defined in quest data |
| Story milestones | Major plot points | AI-driven narrative rewards |
| Exploration | Discovering new locations | Future enhancement |
**Level Progression:**
The XP requirement for each level follows an exponential curve using the formula:
```
XP Required = 100 × (current_level ^ 1.5)
```
| Level | XP Required | Cumulative XP |
|-------|-------------|---------------|
| 1→2 | 100 | 100 |
| 2→3 | 282 | 382 |
| 3→4 | 519 | 901 |
| 4→5 | 800 | 1,701 |
| 5→6 | 1,118 | 2,819 |
| 6→7 | 1,469 | 4,288 |
| 7→8 | 1,849 | 6,137 |
| 8→9 | 2,254 | 8,391 |
| 9→10 | 2,683 | 11,074 |
**Leveling Mechanics:**
- Each level grants **+1 skill point** to spend in skill trees
- Skill points calculated: `level - unlocked_skills.length`
- Overflow XP automatically carries to next level
- Level up triggers automatically when threshold reached
- Base stats remain constant (progression via skill trees & equipment)
**Implementation:**
- Leveling logic lives in `Character` model (`add_experience()`, `level_up()` methods)
- No separate service needed (OOP design pattern)
- See `api/app/models/character.py` lines 312-358
### Skill Trees
**Overview:**
Each character class has **2-3 skill trees** representing different specializations or playstyles. Players earn **1 skill point per level** to unlock skills, which provide permanent bonuses and unlock combat abilities.
**Skill Points:**
```
Available Skill Points = Character Level - Unlocked Skills Count
```
**Skill Tree Structure:**
Each skill tree contains **5 tiers** of increasing power:
| Tier | Description | Typical Effects |
|------|-------------|-----------------|
| **1** | Entry-level skills | Basic abilities, small stat bonuses (+3-5) |
| **2** | Intermediate skills | Enhanced abilities, moderate bonuses (+5-8) |
| **3** | Advanced skills | Powerful abilities, passive effects |
| **4** | Expert skills | Ability enhancements, large bonuses (+10-15) |
| **5** | Ultimate skills | Class-defining abilities, massive bonuses (+20+) |
**Prerequisites:**
Skills have prerequisites that create progression paths:
- Tier 1 skills have **no prerequisites** (open choices)
- Higher tier skills require **specific lower-tier skills**
- Cannot skip tiers (must unlock Tier 1 before Tier 2, etc.)
- Can mix between trees within same class
**Skill Effects:**
Skills provide multiple types of benefits:
1. **Stat Bonuses** - Permanent increases to stats
```yaml
effects:
stat_bonuses:
strength: 10
defense: 5
```
2. **Ability Unlocks** - Grant new combat abilities
```yaml
effects:
abilities:
- shield_bash
- riposte
```
3. **Passive Effects** - Special mechanics
```yaml
effects:
passive_effects:
- stun_resistance
- damage_reflection
```
4. **Ability Enhancements** - Modify existing abilities
```yaml
effects:
ability_enhancements:
fireball:
damage_bonus: 15
mana_cost_reduction: 5
```
5. **Combat Bonuses** - Crit chance, crit multiplier, etc.
```yaml
effects:
combat_bonuses:
crit_chance: 0.1 # +10%
crit_multiplier: 0.5 # +0.5x
```
**Example Progression Path:**
**Vanguard - Shield Bearer Tree:**
```
Level 1: No skills yet (0 points)
Level 2: Unlock "Shield Bash" (Tier 1) → Gain shield bash ability
Level 3: Unlock "Fortify" (Tier 1) → +5 defense bonus
Level 4: Unlock "Shield Wall" (Tier 2, requires Shield Bash) → Shield wall ability
Level 5: Unlock "Iron Skin" (Tier 2, requires Fortify) → +5 constitution
Level 6: Unlock "Guardian's Resolve" (Tier 3) → +10 defense + stun resistance
...
```
**Class Specializations:**
Each class offers distinct playstyles through their trees:
| Class | Tree 1 | Tree 2 | Tree 3 |
|-------|--------|--------|--------|
| **Vanguard** | Shield Bearer (Tank) | Weapon Master (DPS) | - |
| **Arcanist** | Pyromancy (Fire) | Cryomancy (Ice) | Electromancy (Lightning) |
| **Wildstrider** | Beast Mastery | Nature Magic | - |
| **Assassin** | Shadow Arts | Poison Master | - |
| **Luminary** | Holy Magic | Divine Protection | - |
| **Necromancer** | Death Magic | Corpse Summoning | - |
| **Lorekeeper** | Arcane Knowledge | Support Magic | - |
| **Oathkeeper** | Divine Wrath | Holy Shield | - |
**Design Notes:**
- Skill choices are **permanent** (no respec system currently)
- Players can mix skills from different trees within same class
- Some skills are **mutually exclusive** by design (different playstyles)
- Skill point allocation encourages specialization vs. generalization
**Implementation:**
- Skills defined in class YAML files at `api/app/data/classes/*.yaml`
- Character stores only `unlocked_skills: List[str]` (skill IDs)
- Bonuses calculated dynamically via `Character.get_effective_stats()`
- Full documentation: [SKILLS_AND_ABILITIES.md](SKILLS_AND_ABILITIES.md)
### 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
---
## Procedural Item Generation
### Overview
Weapons and armor are procedurally generated using a Diablo-style affix system.
Items are created by combining:
1. **Base Template** - Defines item type, base stats, level requirement
2. **Affixes** - Prefixes and suffixes that add stats and modify the name
### Generation Process
1. Select base template (filtered by level, rarity)
2. Determine affix count based on rarity (0-3)
3. Roll affix tier based on rarity weights
4. Select random affixes avoiding duplicates
5. Combine stats and generate name
### Rarity System
| Rarity | Affixes | Value Multiplier | Color |
|--------|---------|------------------|-------|
| COMMON | 0 | 1.0× | Gray |
| UNCOMMON | 0 | 1.5× | Green |
| RARE | 1 | 2.5× | Blue |
| EPIC | 2 | 5.0× | Purple |
| LEGENDARY | 3 | 10.0× | Orange |
### Affix Distribution
| Rarity | Affix Count | Distribution |
|--------|-------------|--------------|
| RARE | 1 | 50% prefix OR 50% suffix |
| EPIC | 2 | 1 prefix AND 1 suffix |
| LEGENDARY | 3 | Mix (2+1 or 1+2) |
### Affix Tiers
Higher rarity items have better chances at higher tier affixes:
| Rarity | MINOR | MAJOR | LEGENDARY |
|--------|-------|-------|-----------|
| RARE | 80% | 20% | 0% |
| EPIC | 30% | 70% | 0% |
| LEGENDARY | 10% | 40% | 50% |
### Name Generation Examples
- **COMMON:** "Dagger"
- **RARE (prefix):** "Flaming Dagger"
- **RARE (suffix):** "Dagger of Strength"
- **EPIC:** "Flaming Dagger of Strength"
- **LEGENDARY:** "Blazing Glacial Dagger of the Titan"
### Luck Influence
Player's LUK stat affects rarity rolls for loot drops:
**Base chances at LUK 8:**
- COMMON: 50%
- UNCOMMON: 30%
- RARE: 15%
- EPIC: 4%
- LEGENDARY: 1%
**Luck Bonus:**
Each point of LUK above 8 adds +0.5% to higher rarity chances.
**Examples:**
- LUK 8 (baseline): 1% legendary chance
- LUK 12: ~3% legendary chance
- LUK 16: ~5% legendary chance
### Service Usage
```python
from app.services.item_generator import get_item_generator
from app.models.enums import ItemRarity
generator = get_item_generator()
# Generate item of specific rarity
sword = generator.generate_item(
item_type="weapon",
rarity=ItemRarity.EPIC,
character_level=5
)
# Generate random loot with luck bonus
loot = generator.generate_loot_drop(
character_level=10,
luck_stat=15
)
```
### Data Files
| File | Description |
|------|-------------|
| `/app/data/base_items/weapons.yaml` | 13 weapon templates |
| `/app/data/base_items/armor.yaml` | 12 armor templates |
| `/app/data/affixes/prefixes.yaml` | 18 prefix affixes |
| `/app/data/affixes/suffixes.yaml` | 11 suffix affixes |
---
## 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 |