# Post-Battle Looting System Implementation Guide

## Overview
This guide covers the implementation of the post-battle looting system, carry capacity management, and game over screen functionality for when battles end.

## 🎯 Features Implemented

### 1. Post-Battle Looting System (`PostBattleLootSystem.cs`)
- **Automatic loot generation** from defeated enemies
- **Currency rewards** (gold/silver/copper) based on enemy type
- **Item drops** with type-specific loot tables
- **Auto-distribution** to surviving players
- **Integration** with existing inventory systems

### 2. Carry Capacity System (`CharacterCarryCapacity.cs`)
- **Weight-based inventory** management
- **Strength-based capacity** calculation
- **Encumbrance penalties** for overloading
- **Movement and Dexterity penalties** for heavy loads
- **Real-time weight calculation** from inventory

### 3. Game Over Screen (`GameOverScreen.cs`)
- **Comprehensive statistics** display
- **Performance analysis** (battles won/lost, enemies slain)
- **Social impact tracking** (people helped, quests completed)
- **Final hero assessment** based on achievements
- **Restart/Main Menu options**

## 🚀 Quick Setup

### Step 1: Battle Scene Integration
The new systems integrate automatically with the existing `GameManager`:

```csharp
// Victory Detection (Enhanced)
- Properly detects when all enemies are defeated
- Automatically starts looting phase
- Distributes rewards to surviving players

// Defeat Detection (Enhanced) 
- Detects when all players are dead
- Shows comprehensive game over screen
- Displays final statistics and achievements
```

### Step 2: Character Setup
Add carry capacity to your characters:

```csharp
// Add to player prefabs
var carryCapacity = playerPrefab.AddComponent<CharacterCarryCapacity>();
carryCapacity.carrySystem.baseCarryCapacity = 50; // Base capacity
carryCapacity.carrySystem.strengthMultiplier = 5f; // STR bonus
```

### Step 3: UI Setup (Optional)
For custom UI, create these UI elements:
- **Loot Panel**: For manual loot selection
- **Game Over Panel**: For defeat screen display

## 📊 Loot System Details

### Enemy-Based Loot Generation
Different enemy types drop different items:

```csharp
// Skeleton Enemies
- Bone (30% chance)
- Rusty Sword (20% chance) 
- Bone Dust (15% chance)

// Bandit Enemies
- Thieves' Tools (40% chance)
- Rope (30% chance)
- Dagger (20% chance)
- Extra copper coins

// Orc/Goblin Enemies  
- Crude Axe (30% chance)
- Hide Armor (25% chance)
- Iron Ration (20% chance)
```

### Currency Rewards
Base currency generation per enemy:
- **Gold**: 0-5 pieces
- **Silver**: 0-15 pieces  
- **Copper**: 20-35 pieces

### Distribution Method
- Currency distributed evenly among survivors
- Items distributed round-robin style
- Remainder currency goes to first players

## ⚖️ Carry Capacity System

### Weight Categories
Default item weights:
- **Potions/Scrolls**: 0 lbs (negligible)
- **Daggers**: 1 lb
- **Swords/Axes**: 3 lbs
- **Hammers/Maces**: 4 lbs
- **Light Armor**: 5 lbs
- **Medium Armor**: 15 lbs
- **Heavy Armor**: 25 lbs

### Encumbrance Levels
Based on percentage of max capacity:

```csharp
Light Load (0-33%):    No penalties
Medium Load (34-66%):  -25% movement speed
Heavy Load (67-100%):  -50% movement, -3 DEX
Overloaded (100%+):    -75% movement, -6 DEX
```

### Capacity Calculation
```csharp
Max Capacity = Base Capacity + (Strength × Strength Multiplier)
Default: 50 + (STR × 5) pounds
```

## 📈 Game Over Statistics

### Tracked Statistics
The system tracks and displays:

**Journey:**
- Total play time
- Days traveled  
- Locations visited

**Combat:**
- Battles won/lost
- Win rate percentage
- Enemies slain
- Damage dealt/taken

**Social Impact:**
- People helped
- Lives saved
- Quests completed/failed
- Final fame level

**Economic:**
- Gold earned/spent
- Net worth
- Items bought/sold

### Performance Messages
Final message based on achievements:
- **Legendary Hero**: High win rate + high social impact
- **Valiant Fighter**: Good combat record + some helping
- **Fierce Warrior**: Many enemies slain
- **Kind Soul**: Helped many people
- **Explorer**: Traveled extensively
- **Brief Adventure**: Short journey

## 🔧 Integration Points

### With Existing Systems

**BattleSetup Integration:**
- Automatically hooks into `GameManager.MainBattleLoopCoroutine()`
- Uses existing `Character.IsDead` detection
- Works with `BattleSetupData` and `CombatDataTransfer`

**Inventory Integration:**
- Compatible with existing `Inventory` component
- Uses `CombatDataTransfer.miscItems` for session data
- Supports both ScriptableObject and string-based items

**Character Integration:**
- Extends existing `Character` class functionality
- Uses `Character.Strength` for capacity calculation
- Compatible with existing stat modifiers

### Test Mode Enhancement
`BattleTestMode` now includes:
- Carry capacity setup for test characters
- Enhanced inventory generation
- Integration with post-battle systems

## 🐛 Troubleshooting

### Loot Not Appearing
- Check that enemies have `Character` component with `IsDead = true`
- Verify `PostBattleLootSystem` is created automatically
- Check console for loot generation debug logs

### Carry Capacity Not Working  
- Ensure `CharacterCarryCapacity` component is added to characters
- Verify character has `Character` component with `Strength` property
- Check that `Inventory` component exists for weight calculation

### Game Over Not Showing
- Confirm all player characters have `IsDead = true`
- Check that `GameOverScreen` component is created
- Verify UI panel references are set up correctly

### Weight Calculation Issues
- Ensure items have proper types (`WeaponItem`, `ArmorItem`, etc.)
- Check that inventory slots have correct quantities
- Verify weight calculation fallbacks are working

## 📝 Example Usage

### Manual Loot System Setup
```csharp
// In your battle scene
var lootSystem = battleScene.AddComponent<PostBattleLootSystem>();
lootSystem.baseGoldReward = 10; // Increase gold rewards
lootSystem.showDebugLogs = true; // Enable debugging

// When battle ends with victory
lootSystem.InitializeLootSystem(defeatedEnemies);
lootSystem.StartLooting();
```

### Character Capacity Setup
```csharp
// Add to character prefab or runtime setup
var capacity = character.AddComponent<CharacterCarryCapacity>();
capacity.carrySystem.baseCarryCapacity = 75; // Higher base capacity
capacity.carrySystem.strengthMultiplier = 7f; // More STR bonus
capacity.showDebugInfo = true; // Enable weight logging
```

### Game Over Integration
```csharp
// Setup in main scene
var gameOver = gameObject.AddComponent<GameOverScreen>();
gameOver.showDetailedStats = true; // Show all statistics

// Update statistics during gameplay
gameOver.UpdateStatistic("enemiesslain", 1);
gameOver.UpdateStatistic("peoplehelped", 1);
gameOver.UpdateStatistic("goldearned", 50);
```

## 🔮 Future Enhancements

### Planned Features
1. **Custom Loot UI**: Visual item selection interface
2. **Item Weight Properties**: ScriptableObject weight fields
3. **Advanced Drop Tables**: Integration with `EnemyCharacterData.dropTable`
4. **Persistent Statistics**: Save/load game statistics
5. **Achievement System**: Unlock titles based on performance
6. **Encumbrance Visual**: UI indicators for carry capacity
7. **Auto-Sort Inventory**: Organize by weight/value
8. **Loot Quality**: Rare/legendary item drops

### Integration Opportunities
1. **Travel System**: Track actual travel statistics
2. **Quest System**: Real quest completion tracking  
3. **Social System**: Actual people helped/saved counts
4. **Fame System**: Real fame level progression
5. **Market System**: Item value based on market prices

## 📂 File Structure
```
Assets/Scripts/
├── BattleScene/
│   ├── PostBattleLootSystem.cs     # Main looting logic
│   ├── GameManager.cs              # Enhanced battle detection
│   └── BattleTestMode.cs           # Enhanced test setup
├── Objects/
│   └── CharacterCarryCapacity.cs   # Weight management
└── UI/
    └── GameOverScreen.cs           # Defeat screen system
```

This system provides a solid foundation for post-battle gameplay and can be extended as your RPG systems grow!
