# Shadowed Realms - Complete Design Document (Updated)

## Table of Contents
1. [Game Overview](#game-overview)
2. [Technical Architecture](#technical-architecture)
3. [Combat System](#combat-system)
4. [Alliance System](#alliance-system)
5. [Kingdom vs Kingdom (KvK) Events](#kingdom-vs-kingdom-kvk-events)
6. [Kingdom Management](#kingdom-management)
7. [Alliance Territory System](#alliance-territory-system)
8. [Dragon System](#dragon-system)
9. [Resource Economy](#resource-economy)
10. [PvE Content System](#pve-content-system)
11. [Player Progression System](#player-progression-system)
12. [Monetization Strategy](#monetization-strategy)
13. [Server Infrastructure](#server-infrastructure)
14. [Implementation Roadmap](#implementation-roadmap)

---

## Game Overview

### Vision Statement
Create a production-ready multiplayer strategy MMO that addresses critical design flaws in existing King of Avalon-style games while maintaining commercial viability. Focus on preserving player agency, preventing pay-to-win dominance, and avoiding vendor lock-in through self-hosted infrastructure.

### Core Objectives
- **Preserve Player Agency:** Field interception system allows defenders to meet attackers before castle sieges
- **Prevent Pay-to-Win:** Speed boost limitations and skill-based alternatives maintain competitive balance
- **Strategic Depth:** Multiple victory paths and sophisticated political systems
- **Social Preservation:** Alliance coalition system eliminates forced alliance merging
- **Technical Independence:** Self-hosted infrastructure avoids cloud vendor lock-in

### Target Platform
- **Primary:** Mobile (iOS/Android) with Unity client
- **Secondary:** PC support with enhanced features
- **Cross-Platform:** Shared progression and multiplayer interaction

### Launch Parameters
- **Maximum Castle Level:** Level 30 (expandable post-launch)
- **Maximum Troop Tier:** T10 at launch
- **Post-Launch Expansion:** T11 at Castle 35, T12 at Castle 40, T13 at Castle 44

---

## Technical Architecture

### Development Stack
**Client Side:**
- **Engine:** Unity 2023.3 LTS
- **Networking:** Unity Netcode for GameObjects (client-side only)
- **UI Framework:** UI Toolkit for scalable interfaces
- **Platforms:** iOS, Android, PC (Windows/Mac/Linux)

**Server Side:**
- **Language:** C# .NET 8 (for production)
- **IDE:** Visual Studio 2022
- **Framework:** ASP.NET Core Web API
- **Database:** PostgreSQL with Entity Framework Core
- **Caching:** Redis for sessions and real-time data
- **Real-time:** SignalR for WebSocket communication
- **Hosting:** Self-hosted, cross-platform (Linux/Windows)

### Architecture Principles
- **Server-Authoritative:** All game logic validated server-side
- **Cross-Platform Deployment:** Identical operation on Linux and Windows
- **Horizontal Scaling:** Kingdom-based partitioning for growth
- **Decoupled Design:** Unity client communicates with independent server

---

## Combat System

### Core Combat Mechanics

#### Troop System
**Four Main Troop Types:**
- **Infantry:** Defensive tanks, absorb casualties
- **Cavalry:** High damage, mobile attackers
- **Bowmen:** Ranged damage dealers
- **Siege:** Anti-building specialists

**Effectiveness Matrix:**
```
Infantry > Cavalry > Bowmen > Siege > Infantry
```

**Tier System:**
- 10 tiers per troop type at launch (T1-T10)
- Higher tiers cost more but provide better effectiveness
- Mixed-tier armies often optimal due to resource constraints

#### Battle Resolution
**Statistical Combat System:**
```
Effective Damage = (Attacker Attack - Defender Defense) × Damage Multipliers
Casualties = Effective Damage / Troop Health
```

**Key Modifiers:**
- **Dragon Skills:** Significant damage and damage reduction bonuses
- **Equipment Bonuses:** Lord gear provides army-wide improvements
- **Research Bonuses:** University and Alliance research trees
- **Terrain Effects:** Different battlefield types affect troop effectiveness

### Automatic Field Interception System

#### Revolutionary Defensive Innovation
**Automatic Interceptor Formation:**
- **Pre-configured defensive army** set by defender
- **Automatically deploys** against incoming attacks without manual intervention
- **Toggle on/off** - players can enable/disable the system
- **24/7 protection** - works whether player is online or offline

#### Per-Attacker Trigger System
**Smart Anti-Abuse Mechanics:**
- **First attack from Player A** → Interceptor triggers
- **Second attack from Player A** → Goes directly to castle (no interception)
- **First attack from Player B** → Interceptor can trigger again
- **Prevents ping-pong exploitation** while maintaining defensive value

#### Hybrid Defense System
**Multiple Attacker Management:**
- **Interceptor auto-engages largest incoming attack** (by army size)
- **20% reserve force** held back for potential second engagement
- **Maximum 2 engagements** per interceptor deployment
- **Priority target selection** prevents overwhelming but maintains coverage

#### Strategic Risk/Reward Balance
**Interceptor Advantages:**
- **Field initiative** - meet enemies on neutral ground
- **Tactical choice** - prevent siege bonuses for attackers
- **Always active** - works even when offline

**Interceptor Disadvantages:**
- **No home castle buffs** - lose defensive research, trap support, wall bonuses
- **Committed troops** - can't use those armies for other activities
- **Double jeopardy** - lose interceptor battle AND still face castle attack
- **March capacity based** - interceptor size limited by march capacity and dragon presence

### Attack Classification System

#### Lightning Raids (2-5 minutes) - UNRESTRICTED
- **Targets:** Resource gatherers, exposed armies
- **Purpose:** Fast resource acquisition
- **Restrictions:** None - full speed boost effectiveness
- **Balance:** Only works on small, exposed targets

#### Hit-and-Run Attacks (5-15 minutes) - LIGHTLY RESTRICTED
- **Targets:** Castle outskirts, economic buildings
- **Restrictions:** 5-minute minimum approach time
- **Purpose:** Quick tactical strikes without full siege commitment

#### Surgical Strikes (10-30 minutes) - MODERATELY RESTRICTED
- **Targets:** Specific strategic elements
- **Restrictions:** 10-minute minimums, reduced speed boost effectiveness
- **Purpose:** Strategic depth without slow pacing

#### Castle Sieges (30+ minutes) - FULLY RESTRICTED
- **Targets:** Complete base destruction
- **Restrictions:** All defensive mechanics apply
- **Purpose:** Epic strategic warfare with proper build-up

### Speed Boost Limitations
**Preventing Abuse:**
- **Minimum March Times:** 5-30 minutes based on distance
- **Diminishing Returns:** Each successive speed boost less effective
- **Detection Grace Periods:** Mandatory warning times regardless of speed boosts
- **Phase-Based Pricing:** Speed boosts cost more in final approach

### Stealth Attack System

#### Free Stealth Through Skill
**Route Planning Mechanics:**
- **Forest Paths:** 75% reduced detection range
- **Mountain Passes:** 60% reduced detection range
- **River Valleys:** 50% reduced detection range
- **Timing Windows:** Attack during target's offline hours for 90% stealth

**Skill Requirements:**
- 2-6 hours of route scouting and target analysis
- Learning defender patterns and offline schedules
- Terrain knowledge and route optimization
- Precise timing coordination

#### Premium Stealth Convenience
**Gold-Based Alternatives:**
- **Instant Route Analysis:** 200 gold for immediate scouting
- **Intelligence Reports:** 300 gold for defender activity analysis
- **Stealth Enhancement:** 500 gold for artificial stealth bonuses

---

## Alliance System

### Alliance Structure and Hierarchy

#### Leadership Roles
```
Alliance Leader (1) - Ultimate authority
├── Right Hand (1) - Co-leader with most permissions
├── Generals (3-5) - Military commanders and recruiters
├── Captains (8-12) - Mid-tier leaders and moderators
├── Veterans (20-30) - Experienced trusted members
└── Members (60-150) - Standard participants
```

#### Role-Based Permissions
- **Send Mail, Kick Members, Accept Applications**
- **Initiate War, Manage Resources, Set Policy**
- **Promote Members, Alliance Research, Territory Management**

### Alliance Progression System

#### Alliance Levels (1-25)
**Level Benefits Include:**
- **Member Capacity:** 50 → 200 members
- **Territory Slots:** 1 → 20 controlled territories
- **Research Slots:** 2 → 15 simultaneous projects
- **Rally Size:** 500k → 3M total army capacity

#### Experience Sources
- **Combat Victories:** Battle wins and rally successes
- **Territory Control:** Daily XP for strategic locations
- **Member Activity:** Bonus based on participation rates
- **Research Completion:** Large XP for alliance projects
- **Event Participation:** Alliance-wide milestone achievements

#### Level Requirements
**Multiple Advancement Paths:**
- **Activity-Based:** Time and member engagement
- **Investment-Based:** Resource and gold contributions
- **Achievement-Based:** Strategic accomplishments and victories

### Alliance Research System

#### Research Categories
**Military Research:**
- Army Effectiveness (+5% per level)
- Rally Capacity (+10k per level)
- March Speed (+3% per level)
- Reinforcement Efficiency (+2% per level)

**Economic Research:**
- Resource Production (+8% per level)
- Construction Speed (+5% per level)
- Trading Efficiency (+10% per level)
- Tax Collection Optimization (+3% per level)

**Technology Research:**
- Advanced Communications (coordination tools)
- Intelligence Networks (enemy detection)
- Logistics Mastery (reduced march costs)
- Defensive Strategies (fortification bonuses)

### Alliance Economy

#### Treasury System
**Revenue Sources:**
- **Member Donations:** Voluntary contributions
- **Territory Income:** Automatic from controlled areas
- **Tax Collection:** Percentage of member generation
- **War Spoils:** Resources from successful battles
- **Trade Commissions:** Fees from facilitated trades

#### Resource Sharing
- **Member-to-Member Trading:** With alliance commission
- **Emergency Assistance:** Support for attacked members
- **Bulk Purchasing:** Collective buying power discounts
- **Research Funding:** Pooled resources for advancement

---

## Kingdom vs Kingdom (KvK) Events

### KvK Scheduling and Timing

#### Kingdom Creation and First KvK
- **New Kingdom Creation Trigger:** When current newest kingdom reaches ~1,200 players
- **First KvK Delay:** 1 month after kingdom creation
- **Realistic Timeline:** First KvK typically occurs months 2-4 depending on population growth
- **Age-Based Matching:** Kingdoms matched with similar creation dates when possible

#### KvK Frequency
- **Standard Schedule:** Once per month (configurable)
- **Frequency Adjustments:** Based on player feedback and engagement metrics
- **Population Considerations:** May adjust timing based on kingdom development rates

### 3-Kingdom KvK Format

#### Enhanced Political Complexity
**Triangle Dynamic:**
- **Kingdom A vs Kingdom B vs Kingdom C**
- **No permanent alliances** - any two can ally against the third
- **Dynamic alliance shifts** throughout the 6-hour battle
- **Trust becomes strategic resource** with long-term consequences

#### Real-Time Political Alliance System
**Alliance Proposal Framework:**
- **Formal proposals** between kingdom Host Alliances during KvK
- **Example:** "Kingdom A + Kingdom B eliminate Kingdom C first, then 1v1 finale"
- **Accept/Reject/Counter-propose** options for strategic negotiation
- **Betrayal mechanics** - either kingdom can attack their "ally" instantly breaking alliance

**Active Alliance Benefits:**
- **Cross-kingdom reinforcements** - Kingdom B can help defend Kingdom A's castles
- **Coordinated attacks** - Joint rallies against common enemy
- **Shared intelligence** - Both kingdoms see each other's strategic information
- **Joint victory bonuses** - Shared rewards if target kingdom eliminated

**Betrayal Consequences:**
- **Instant alliance termination** when ally attacks ally
- **All reinforcements recalled** immediately upon betrayal
- **Public announcement** of betrayal visible to all kingdoms
- **Reputation impact** affecting future KvK negotiation credibility

### Alliance Coalition System (Revolutionary Feature)

#### Preserving Alliance Independence
**Core Innovation:**
- **No forced alliance merging** - all alliances maintain independence during KvK
- **Coalition cooperation** - temporary coordination without structural changes
- **Shared kingdom objectives** while preserving alliance identity
- **Cross-alliance participation** in rallies and reinforcements

#### Democratic Host Selection
**Democratic Process:**
- **24-48 hours before KvK:** Kingdom-wide voting period
- **One vote per alliance** (not per player) - prevents large alliance dominance
- **Alliance leaders cast votes** on behalf of their members
- **Host alliance responsibilities:** Strategic coordination, diplomacy, King/Queen appointment

### Rally System Across Alliances

#### Cross-Alliance Rally Participation
**Merit-Based Leadership:**
- **Any player can start a rally** regardless of alliance membership
- **Rally participants inherit leader's stats** - encourages following strongest leaders
- **Natural coordination** - players gravitate toward most effective commanders
- **Alliance research bonuses:** Only rally leader's alliance research applies (prevents host alliance favoritism)

**Rally Mechanics:**
- **Rally leader limit:** Can only host 1 rally at a time
- **No cooldowns:** Can start new rally immediately after previous concludes
- **Rally capacity:** Based on Hall of War level + Alliance Mega Rally research
- **Timing coordination:** Multiple strong leaders can launch simultaneous rallies for "double whammy" attacks

**Rally Formation Rules:**
- **5-minute standard formation time** (shorter rallies possible but limited)
- **Troops must reach rally castle** before departure (geography matters)
- **No army composition changes** once rally launches
- **March speed affects participation** ability

### KvK Event Structure

#### Event Duration
**6-Hour Base Battle:**
- **Continuous competition** without artificial phases
- **Dynamic extensions** if victory margins are close (<10%)
- **Maximum 8-10 hours** including potential overtime
- **Optimal timing** for multiple time zones

#### 24-Hour Preparation Period
**Pre-Battle Activities:**
- **Strategy Declaration:** Choose kingdom focus (Military/Economic/Diplomatic/Technological)
- **Treaty Negotiations:** Form alliances, non-aggression pacts, trade agreements
- **Coalition Planning:** Alliance coordination and resource preparation
- **Diplomatic Maneuvering:** Target selection and partnership building

### Multi-Path Victory System

#### Victory Types
**Military Domination:** Traditional conquest and territory control
**Economic Supremacy:** Resource control and infrastructure development
**Diplomatic Victory:** Coalition building and alliance success
**Technological Advancement:** Research leadership and innovation
**Hybrid Strategies:** Adaptive multi-path approaches

#### Victory Point Distribution
- **25% Military** actions and conquest
- **25% Economic** development and resource control
- **25% Diplomatic** achievements and alliance success
- **15% Technological** progress and innovation
- **10% Participation** bonuses and engagement

### Advanced KvK Features

#### Forest Barrier Mechanics
**High-Risk Zone Around Center Castle:**
- **50% movement speed reduction** in forest zone
- **Castle banishment** consequence for losing forest battles
- **All reinforcements recalled** when castle is banished
- **Strategic isolation** from kingdom support during forest approach

#### Castle Control Victory
**Cumulative Time System:**
- **Victory Condition:** Hold center castle for 3+ hours cumulative
- **Any coalition alliance** holding castle counts for kingdom
- **Rotation strategies** allow different alliances to defend
- **Last-hour drama** as kingdoms race to threshold

### Matchmaking and Balance

#### Multi-Dimensional Analysis
**Beyond Raw Power:**
- **Active Player Count** (25% of matching weight)
- **Alliance Coordination Score** (20% weight)
- **Spending Distribution** (10% weight)
- **Recent Activity Trends** (5% weight)

#### Age-Based Competition Brackets
**Month 1-3 Kingdoms:** First-time KvK participants, learning-focused
**Month 4-8 Kingdoms:** Developing strategies and competitive meta
**Month 9+ Kingdoms:** Mature competitive play with established politics

#### Dynamic Balance Mechanisms
**Mid-Event Adjustments:**
- **Underdog bonuses** if early results show severe imbalance
- **Multiple victory paths** beyond pure domination
- **Participation rewards** ensure meaningful engagement for all

---

## Kingdom Management

### Kingdom Population Strategy

#### Optimal Kingdom Size
**Target Population: 1,200-1,500 active players**
- **Alliance Distribution:** 8-12 alliances × 100-150 members
- **KvK Balance:** Sufficient for competitive 3-kingdom battles
- **Social Dynamics:** Large enough for politics, not overwhelming
- **Resource Competition:** Adequate nodes and strategic locations

#### New Kingdom Creation
**Triggers:**
- **Population Threshold:** Current kingdom reaches ~1,200 active players
- **Age Requirement:** Kingdom minimum 14 days old
- **Automatic Process:** New kingdoms open when conditions met

### Kingdom Selection System

#### Player Choice with Smart Defaults
**Default Selection:**
- **Newest kingdom** accepting players (recommended for new players)
- **Population balance** consideration
- **Language and time zone optimization**

**Available Information:**
- **Player count** and activity levels
- **Kingdom age** and competitive level
- **Primary language** and time zones
- **Recent KvK performance** and community rating

#### Personalized Recommendations
**Matching Factors:**
- **Language preference** alignment
- **Time zone compatibility**
- **Competitive level** (Casual/Moderate/Competitive/Hardcore)
- **Community culture** fit

### Castle Teleportation System

#### Balanced Teleportation Mechanics
**Post-Teleport Combat Restrictions:**
- **0-30 minutes:** Cannot launch attacks
- **30-60 minutes:** 50% army effectiveness
- **1-2 hours:** 25% army effectiveness
- **2-4 hours:** Normal combat capability

#### Teleportation Limitations
**Proximity Blocks (REMOVED):**
- Previous 100km restriction removed to allow legitimate castle sieges and farming

**Escalating Costs:**
- **1st teleport:** 1000 gold, 24-hour cooldown
- **2nd teleport:** 2500 gold, 48-hour cooldown
- **3rd+ teleport:** 5000+ gold, 72+ hour cooldowns

#### Territory-Based Pricing
- **Friendly territory:** 500 gold
- **Neutral territory:** 1500 gold
- **Enemy territory:** 5000 gold
- **Active war zones:** 10000+ gold

### Kingdom Merger System

#### Voluntary Merger Framework
**Democratic Process:**
- **48-hour proposal period** with kingdom-wide voting
- **60% approval threshold** required
- **Weighted voting** based on activity and contribution
- **Alliance leader consultation** and coalition input

#### Merger Eligibility
**Quality-Based Assessment:**
- **Competitive viability** over raw population numbers
- **Coordination quality** and strategic execution
- **KvK performance** and win rates
- **Player retention** and community health

#### Compatibility Matching
**Multi-Factor Analysis:**
- **Population balance** (neither kingdom > 70% of merged total)
- **Alliance structure compatibility**
- **Economic and technological balance**
- **Cultural and language compatibility**
- **Time zone overlap optimization**

---

## Alliance Territory System

### Core Alliance Buildings

#### Fortress - Territory Control Hub
- **Largest territory claim** - major strategic footprint
- **Alliance stronghold** - heavily defended, high-value target
- **Command center** - hub for alliance-wide coordination
- **Limited quantity** - 1-2 per alliance to maintain strategic value
- **Upgradeable** - Level 1-10 with scaling territory and benefits

#### Tower - Expansion Points
- **Smaller territory bubbles** - fill strategic gaps
- **Flexible placement** - control resource nodes, chokepoints, borders
- **Faster construction** - easier to build than fortresses
- **Contested zones** - "first tower up wins" in prime locations
- **Upgradeable** - Enhanced territory radius and alliance benefits per level

#### Resource Buildings - Economic Infrastructure
- **Alliance-wide resource generation** boosts for members
- **Specialized buildings** for different resource types
- **Strategic vulnerability** - enemies benefit from destroying these
- **Collective investment** - alliance funds construction and upgrades

#### Alliance Hospital - Military Support
- **Reduced healing costs** for alliance members within territory
- **Faster healing times** - accelerated troop recovery
- **Capacity scaling** - handle more wounded troops as alliance/building levels increase
- **Strategic military infrastructure** enabling more aggressive alliance warfare

#### Trade Route Buildings - Economic Networks
- **In-kingdom alliance commerce** - no cross-kingdom trading
- **Alliance specialization** - some alliances become economic powerhouses
- **Farm alliance strategy** - dedicated resource generation alliances
- **Economic warfare** - rival alliances can target trade infrastructure
- **Trade route vulnerability** - buildings can be attacked and disrupted

### Territory Benefits and Scaling

#### Dynamic Territory System
**Alliance Level + Building Level Synergy:**
- **Territory bonuses scale** with both alliance level and individual building level
- **Maximum benefits require investment** in both alliance advancement AND building upgrades
- **Example:** Level 20 Alliance + Level 5 Fortress = major bonuses
- **Resource allocation strategy** - balance alliance research vs building investment

**Territory Benefits:**
- **Resource generation boost** for members within territory
- **March speed bonus** for alliance members in own territory
- **Troop training speed** improvements near alliance buildings
- **Healing cost reduction** within alliance medical buildings' territory

### Forest Competition Strategy

#### Prime Territory Around Forest
- **Highest tier resource nodes** concentrated near forest border
- **Strategic positioning** for KvK castle approach routes
- **Limited prime spots** - intense competition during expansion
- **Risk/reward balance** - better resources but more vulnerable during KvK

#### Contested Zone Resolution
- **"First tower up wins"** creates land rush dynamics
- **Multiple alliances racing** to claim forest-adjacent locations
- **Tower construction speed** becomes competitive advantage
- **Territory wars** - destroy enemy construction to claim contested spots

### Building Progression System

#### Upgrade Framework
**Building Levels 1-10:**
- **Exponential resource costs** - higher levels require massive investment
- **Extended construction times** - weeks or months for maximum level buildings
- **Collective alliance effort** - multiple members contribute to upgrades
- **Alliance level gates** - advanced building levels require advanced alliance levels

**Strategic Investment Decisions:**
- **Quality over quantity** - upgrade existing buildings vs building new ones
- **Territorial expansion** vs **territorial consolidation** strategies
- **Specialization paths** - focus on military buildings vs economic buildings

---

## Dragon System

### Dragon Acquisition and Basic Progression

#### Initial Dragon Acquisition
- **Automatic unlock at Castle Level 2** - ensures players understand basic mechanics first
- **No equipment system** - dragons provide benefits through skills only
- **Single dragon per player** - maintains strategic choice and balance

#### Dragon Leveling System
**Primary Progression:**
- **Building level correlation** - dragon level tied to castle development
- **Activity bonuses** - additional XP from completing various in-game actions
- **Future expansion potential** - gold-based acceleration items in later updates

#### Dragon Skill Categories
**Offensive Skills:**
- **Flaming Arrows I/II/III:** Bowmen damage bonuses against other troop types
- **Cavalry Claw I/II/III:** Cavalry damage bonuses against other troop types
- **March of Fury:** Increases army size capacity for larger forces

**Defensive Skills:**
- **Infantry Backbone I/II/III:** Damage reduction bonuses for infantry units
- **Dragon Blessing:** Reduces overall troop casualties in battle
- **Smokescreen:** Increases trap health for castle defense scenarios

**Utility Skills:**
- **Beast of Burden:** Increases resource carrying capacity for gathering
- **Winged Heels:** Increases march speed for faster army movement
- **Trap Wrecker:** Anti-trap damage bonuses for siege units

### Shadow Dragon System (Premium)

#### Time-Limited Dragon Support
**Revolutionary Multi-March Solution:**
- **Purchase Shadow Dragons** with gold for temporary use
- **Every march can have dragon support** while Shadow Dragon is active
- **Time-limited duration** - hours or days depending on purchase tier
- **Strategic timing** - save Shadow Dragons for crucial battles or KvK events

**Balance Considerations:**
- **Temporary boost** rather than permanent advantage
- **Strategic resource management** - when to use limited Shadow Dragons
- **Maintains single permanent dragon** as core progression system
- **Premium convenience** without breaking free-to-play viability

#### Shadow Dragon Mechanics
- **Same skill effects** as permanent dragon
- **Applies to all marches** simultaneously while active
- **Countdown timer** visible to player
- **Cannot be extended** - must purchase new Shadow Dragon when expired
- **Stacks with permanent dragon** for enhanced effects during Shadow Dragon periods

---

## Resource Economy

### Resource Types and Uses

#### Five Core Resources
**Traditional Resources:**
- **Food:** Troop training, troop upkeep, building construction
- **Wood:** Building construction, research projects, equipment crafting
- **Iron:** Troop training, equipment crafting, advanced buildings

**Advanced Resources:**
- **Silver:** Premium currency for advanced items and acceleration
- **Mithril:** Rare resource for high-end equipment and upgrades

#### Resource Applications
- **Construction:** All buildings require specific resource combinations
- **Military:** Troop training costs scale with tier and quantity
- **Research:** University and Alliance research consume resources over time
- **Equipment:** Crafting and upgrading gear requires material combinations
- **Alliance:** Territory buildings and upgrades require massive resource investment

### Dynamic Resource Node System

#### Node Mechanics
**Tier-Based Resource Nodes:**
- **T1-T10 nodes** corresponding to different resource quantities and quality
- **Higher tier nodes** contain more resources per gathering session
- **Troop efficiency scaling** - T10 troops gather significantly faster than T1 troops
- **Capacity based on node tier** - higher tier nodes support more simultaneous gatherers

#### Node Spawning and Competition
**Dynamic Map System:**
- **Node depletion** - nodes disappear when fully harvested
- **Random respawn locations** - prevents territory monopolization
- **Balanced spawn algorithms** - ensure adequate resource availability across kingdom
- **Geographic distribution** - higher tier nodes more likely to spawn near strategic locations

**Resource Competition:**
- **No permanent resource control** - nodes move to prevent static advantages
- **Gathering speed advantages** reward military investment in higher tier troops
- **Alliance coordination** for securing high-value nodes
- **Territory benefits** enhance gathering within alliance-controlled areas

### Storage and Protection System

#### Alliance Storage Integration
- **Alliance storage buildings** provide shared resource pools
- **Individual storage houses** protect percentage of personal resources
- **Protection scaling** based on storage house level and alliance storage access
- **Raidable resources** - unprotected resources can be stolen in attacks
- **Strategic resource management** - balance protection vs accessibility

#### Resource Security Balance
- **Protected resource percentage** requires careful balance testing
- **Too much protection** reduces raid incentives and economic warfare
- **Too little protection** frustrates casual players and new accounts
- **Dynamic protection scaling** based on player activity and development level

---

## PvE Content System

### Monster and Barbarian Progression

#### Sequential PvE Content
**Monster Hunting System:**
- **Level-gated progression** - must kill Level 1 monsters before accessing Level 2
- **Random map spawning** - monsters appear throughout kingdom territory
- **Solo engagement** - individual players hunt monsters for personal rewards
- **Geographic difficulty** - higher level monsters spawn near forest and strategic areas

**Barbarian Camp System:**
- **Rally requirement** - barbarian camps require coordinated alliance attacks
- **Progressive difficulty** - must clear lower level camps before accessing higher tiers
- **Alliance cooperation** - encourages teamwork and strategic coordination
- **Proximity to forest** - higher level barbarian camps spawn closer to strategic forest areas

#### PvE Reward Scaling
- **Experience and resources** from monster kills
- **Alliance XP bonuses** from barbarian camp victories
- **Unique materials** available only through PvE content
- **Equipment crafting components** from higher tier PvE encounters

### Raid Mob Kingdom Events

#### Dynamic Kingdom-Wide Events
**Raid Mob Spawn System:**
- **Completely random timing** - no predictable schedule
- **Minimum 48+ hour respawn** after successful kill
- **Random location spawning** - cannot be camped or predicted
- **Kingdom-wide notification** when raid mob appears (optional feature)

#### Raid Mob Engagement Rules
**First-Come, First-Served System:**
- **First alliance to reach and engage** locks the encounter for 10 minutes
- **10-minute exclusive window** - sufficient time for organized assault
- **Teleport on failure** - raid mob relocates if not defeated within time limit
- **Defeated army restriction** - armies that lose cannot re-engage the same raid mob

#### Alliance Level Scaling Rewards
**Dynamic Reward System:**
- **Rewards scale with alliance level** - ensures value for both new and mature alliances
- **Unique materials** only available through raid mob encounters
- **Alliance-wide benefits** - entire alliance receives rewards upon successful completion
- **Strategic coordination requirement** - encourages alliance teamwork and planning

---

## Player Progression System

### Hero and Lord Development

#### Hero Star System
- **Fragment-based progression** - collect hero fragments to increase star rating
- **Long-term advancement** - provides sustained progression goals
- **Star-based power scaling** - clear milestones with meaningful power increases
- **Multiple acquisition methods** - events, purchases, achievements

#### Talent Point Progression
- **Activity-based advancement** - talent points earned through gameplay actions
- **Diversified XP sources** - building, researching, fighting, gathering all contribute
- **Skill tree specialization** - players choose focus areas for character development
- **Respec availability** - ability to redistribute talent points (potentially premium feature)

### Equipment and Crafting System

#### Material-Based Crafting
- **Resource requirements** - equipment requires specific material combinations
- **Crafting within castle** - no separate alliance crafting buildings needed
- **Tier-based materials** - higher tier equipment requires rare materials from advanced content
- **Enhancement system** - upgrade existing equipment rather than replacing

#### Equipment Sources
- **PvE content** - monsters and raids provide crafting materials
- **Resource conversion** - basic resources can be processed into crafting materials
- **Event rewards** - special materials available through competitions and achievements
- **Trading system** - alliance members can exchange materials and components

### University Research System

#### Individual Research Paths
- **Personal advancement** separate from alliance research
- **Multiple specialization trees** - military, economic, technological focus options
- **Long-term progression** - months of advancement available in each tree
- **Strategic choices** - cannot max all trees simultaneously, requires focus

#### Research Integration
- **Stacks with alliance research** - personal and alliance bonuses combine
- **Prerequisites and gates** - certain research requires building levels or achievements
- **Resource investment** - significant resource costs for advanced research
- **Time investment** - days or weeks for high-level research projects

---

## Monetization Strategy

### Revenue Model Framework

#### Free-to-Play Foundation
**Core Gameplay Accessibility:**
- **All essential features** available without payment
- **Skill-based alternatives** to premium conveniences
- **Daily allowances** for competitive participation
- **Alliance support systems** for resource sharing and progression assistance

#### Premium Convenience Options
**Speed Boost System:**
- **Graduated effectiveness** with diminishing returns after multiple uses
- **Phase-based pricing** - more expensive during final approach phases
- **Daily usage caps** to prevent pure pay-to-win scenarios
- **Emergency reserves** available at premium costs for critical situations

**Shadow Dragon System:**
- **Time-limited dragon support** for multiple marches simultaneously
- **Strategic resource** - when to use limited Shadow Dragons for maximum effect
- **Maintains balance** - temporary boost rather than permanent advantage
- **Premium convenience** without breaking free-to-play competitive viability

### Skill vs. Convenience Balance

#### Multiple Paths to Success
**Free Skill-Based Options:**
- **Route planning stealth** - 2-6 hours of scouting for maximum stealth effectiveness
- **Timing coordination** - precise attack timing for optimal results
- **Alliance cooperation** - teamwork and coordination competitive with individual spending
- **Strategic planning** - long-term progression through smart resource management

**Premium Convenience Alternatives:**
- **Instant route analysis** - immediate scouting results for gold
- **Intelligence reports** - defender activity analysis for premium currency
- **Speed boost options** - reduced travel time with diminishing returns
- **Shadow Dragon support** - temporary multi-march dragon bonuses

### Tax and Tribute System

#### Victory-Based Resource Benefits
**Conquest Rewards:**
- **0% tax on domestic gathering** for victorious kingdoms in KvK
- **4% tax on conquered kingdoms'** resource collection
- **Royal treasury management** by democratically elected King/Queen
- **Merit-based reward distribution** rather than spending-based favoritism

#### Democratic Resource Distribution
- **Elected leadership** manages kingdom resources and rewards
- **Alliance contribution tracking** for fair reward allocation
- **Player activity consideration** in benefit distribution
- **Transparent resource flow** with visible contribution and reward metrics

### Anti-Pay-to-Win Measures

#### System Safeguards
- **Minimum march times** prevent instant attacks regardless of spending level
- **Detection grace periods** ensure defender response opportunities exist
- **Diminishing returns** on excessive speed boost usage
- **Democratic systems** prevent single-player kingdom dominance through spending

#### Balanced Progression
- **Time investment paths** can achieve premium-equivalent results
- **Strategic skill** valued over pure monetary investment
- **Alliance cooperation** provides competitive advantages beyond individual spending
- **Multiple victory conditions** prevent single-strategy dominance

---

## Server Infrastructure

### Production-Ready Architecture

#### Self-Hosted Design
**Cross-Platform Server:**
- **C# .NET 8** for identical Linux/Windows operation
- **Visual Studio 2022** development environment
- **Single binary deployment** with minimal runtime dependencies
- **Auto-scaling capability** for unpredictable growth patterns

#### Database Strategy
**Multi-Kingdom Database:**
- **PostgreSQL** with kingdom-based partitioning
- **Redis caching** for real-time data and session management
- **Automated sharding** when kingdom count exceeds server thresholds
- **Read replica support** for query distribution and performance optimization

### Scalability Framework

#### Kingdom Distribution
**Dynamic Assignment:**
- **Load balancing** across server instances based on kingdom activity
- **Maximum kingdoms per server** with automatic overflow to new instances
- **Server health monitoring** and capacity management
- **Auto-scaling triggers** based on player count and usage metrics

#### Growth Adaptation
**Designed for Unknown Scale:**
- **Single server start** capable of handling 1-50 kingdoms
- **Horizontal scaling** to multiple server instances as growth demands
- **Database cluster expansion** with kingdom-based sharding strategies
- **Configuration-driven scaling** parameters for easy adjustment

### Monitoring and Administration

#### Comprehensive Logging
**Server Monitoring:**
- **Combat logging** for all battles, outcomes, and balance analysis
- **Purchase tracking** for spending pattern analysis and revenue optimization
- **Player behavior analytics** for retention improvement and engagement optimization
- **Performance metrics** across all server instances and database queries

#### Administrative Dashboard
**Real-Time Management:**
- **Live kingdom statistics** including population, activity, and health metrics
- **Server performance** monitoring with automated alerting systems
- **Revenue analytics** and monetization effectiveness tracking
- **Player support** tools and community management interfaces

### Web Dashboard Features

#### Public Features
**Community Engagement:**
- **Live kingdom map** displaying alliance territories and control
- **Active battle tracker** for ongoing conflicts and major engagements
- **Alliance rankings** and achievement displays
- **Player statistics** and leaderboards across multiple categories

#### Administrative Features
**Operational Management:**
- **Server health** monitoring and performance optimization tools
- **Balance analysis** for game mechanics and competitive fairness
- **Revenue tracking** and monetization strategy effectiveness
- **Community health** metrics and player retention analysis

---

## Implementation Roadmap

### Phase 1: Foundation (Months 1-3)
**Core Infrastructure:**
- **Visual Studio 2022 project setup** with proper architecture and organization
- **PostgreSQL database** schema design and Entity Framework integration
- **Basic API controllers** for player authentication and alliance management
- **JWT authentication system** with ASP.NET Core Identity integration
- **Unity client** with server communication layer and basic UI framework

### Phase 2: Combat System (Months 4-6)  
**Battle Mechanics:**
- **Statistical combat engine** with troop effectiveness calculations and damage systems
- **Dragon system** implementation with skills, leveling, and Shadow Dragon mechanics
- **Automatic field interception** mechanics with per-attacker triggers and hybrid defense
- **Speed boost** limitations, diminishing returns, and balance systems
- **Attack classification** framework with appropriate restrictions per attack type

### Phase 3: Alliance Features (Months 7-9)
**Social Systems:**
- **Alliance hierarchy** and role-based permission systems
- **Alliance research** trees with military, economic, and technology branches
- **Alliance territory system** with buildings, upgrades, and scaling benefits
- **Alliance level** progression with meaningful capacity and feature unlocks
- **Resource sharing** and treasury management systems

### Phase 4: KvK Events (Months 10-12)
**Kingdom Warfare:**
- **3-kingdom KvK** system with dynamic political alliance mechanics
- **Multi-alliance coalition** system preserving alliance independence
- **Democratic host selection** with cross-alliance rally coordination
- **Victory condition** systems with multiple paths to success
- **Forest barrier** mechanics and strategic territory control

### Phase 5: Kingdom Management (Months 13-15)
**Population Systems:**
- **Kingdom creation** triggers and population management systems
- **Player assignment** and kingdom selection interface with smart recommendations
- **Castle teleportation** system with balanced restrictions and escalating costs
- **Kingdom merger** framework with democratic processes and compatibility matching
- **Tax and tribute** systems with royal distribution mechanics

### Phase 6: Polish and Launch (Months 16-18)
**Production Readiness:**
- **Performance optimization** across all systems and database queries
- **Comprehensive testing** and quality assurance validation
- **Balance refinement** based on extensive internal testing and feedback
- **Administrative tools** and monitoring systems for live service management
- **Marketing preparation** and community building initiatives

### Phase 7: Post-Launch Evolution (Months 19+)
**Continuous Development:**
- **Castle level expansion** to 35+ with T11+ troop tiers
- **Advanced alliance buildings** - Dragon Altar and Spirit Altar ceremony systems
- **Seasonal events** and competitive tournament systems
- **PvE expansion** with raid dungeons and advanced monster encounters
- **Cross-kingdom features** for advanced players and mature server clusters

---

## Success Metrics and KPIs

### Technical Performance
- **Server uptime:** >99.5% availability across all instances
- **Response times:** <200ms for API calls and <50ms for database queries
- **Concurrent players:** Target support for 10,000+ simultaneous users per server cluster
- **Kingdom capacity:** 1,200-1,500 players per kingdom with optimal performance

### Player Engagement
- **Daily Active Users (DAU)** tracking with growth targets and retention analysis
- **Session length and frequency** analysis for engagement optimization
- **Player retention rates** (D1, D7, D30) with industry-leading targets
- **Alliance participation** metrics and social engagement measurement

### Business Metrics
- **Average Revenue Per User (ARPU)** optimization with sustainable growth targets
- **Player Lifetime Value (LTV)** measurement and improvement strategies
- **Conversion rates** from free to paying players with balanced monetization
- **Kingdom population** health and competitive balance maintenance

### Community Health
- **Alliance stability** and member retention within social structures
- **KvK participation** rates and competitive balance across all kingdom tiers
- **Player satisfaction** through regular surveys and community feedback analysis
- **Community growth** through organic word-of-mouth and player referrals

---

## Risk Management and Mitigation

### Technical Risks
- **Server scaling challenges** - Mitigated by kingdom-based partitioning design and horizontal scaling architecture
- **Database performance** - Addressed through PostgreSQL optimization, Redis caching, and read replica strategies
- **Security vulnerabilities** - Prevented by server-authoritative design and comprehensive input validation
- **Cross-platform compatibility** - Managed through .NET 8 standardization and extensive testing protocols

### Business Risks  
- **Monetization balance** - Addressed through skill-based alternatives, democratic systems, and anti-pay-to-win measures
- **Player retention** - Mitigated by strong social features, meaningful progression, and preserved alliance structures
- **Market competition** - Differentiated through innovative field interception, coalition systems, and political mechanics
- **Development timeline** - Managed through phased implementation, MVP approach, and realistic scope management

### Operational Risks
- **Community management** - Planned through comprehensive administrative tools and moderation systems
- **Balance maintenance** - Supported by extensive logging, analytics systems, and data-driven optimization
- **Technical support** - Enabled through detailed monitoring, diagnostic capabilities, and player support tools
- **Growth management** - Prepared through scalable architecture, kingdom merger systems, and population balancing

---

This design document represents the complete vision for Shadowed Realms, incorporating all discussed refinements and new systems. The game is designed to scale from hundreds to tens of thousands of players while preserving the social dynamics, strategic depth, and competitive balance that create compelling long-term player experiences in the strategy MMO genre.