Back to Game

Slime Rancher Defense - Game Design Guide

Game Concept

# Slime Rancher Defense ## Theme The player manages a magical slime ranch on the edge of a enchanted forest, where they breed, train, and deploy slimes to defend against waves of corrupted creatures trying to invade. The twist: slimes aren't just defenders—they're resource producers, breeders, and evolve based on what they eat and how they're deployed. The player is both rancher and tactician, balancing economy and defense in real-time. ## Visual Game World The Canvas shows a top-down view of a ranch with designated zones: a central ranch house, grazing pens where slimes roam, defensive trenches where slimes patrol, and forest edges where enemies emerge. Slimes bounce around with cute, squishy animations—stretching and compressing as they move. Enemies emerge from shadowy forest patches at the top. The background transitions from day to night, affecting slime behavior (some slimes glow at night, others become more active). Gold and essence sprites sparkle and float when collected, with satisfying pop animations. ## Player Interaction 1. **Click and drag slimes** to move them between zones—drag a slime from the grazing pen to the defensive trench to reposition it for battle 2. **Click on enemies** to command nearby slimes to target them (tactical priority setting) 3. **Click on food items** in the ranch to feed specific slimes, triggering immediate evolution effects and stat boosts 4. **Click on slime babies** to collect them before they wander off (adds urgency) 5. **Place slime toys/structures** in pens by clicking and dragging from a build panel onto the Canvas 6. **Activate slime special abilities** by clicking on charged slimes (glowing aura indicates readiness) ## Entity Types ### Rancher Slime (Player's Basic Unit) - **Sprite**: `slime` with blue ProceduralSprite color variant - **Appearance**: Small, bouncy blue blob with cute eyes, squishy bounce animation (4 frames) - **Behavior**: Wanders in pens when idle, bounces toward enemies when threatened, attacks by projecting smaller slime projectiles - **Interaction**: Drag to reposition, click to select, can be fed different foods to evolve ### Warrior Slime (Combat Evolution) - **Sprite**: `slime` with red ProceduralSprite color variant, larger scale - **Appearance**: Red, spiky slime with visible "armor" plates, aggressive bounce animation - **Behavior**: Patrols defensive trenches, actively seeks enemies, higher damage but slower movement - **Interaction**: Cannot be bred (sterile), purely defensive unit, click to set patrol waypoint ### Breeder Slime (Economy Unit) - **Sprite**: `slime` with pink ProceduralSprite color variant, heart glow effect - **Appearance**: Pink, smaller slime with subtle heart pulse animation, produces baby slimes periodically - **Behavior**: Wanders pens seeking mates, produces baby slimes that must be clicked to collect, cannot fight - **Interaction**: Drag near other slimes to encourage breeding, click on babies to "ranch" them ### Corrupted Spider (Basic Enemy) - **Sprite**: `slime` with dark purple ProceduralSprite color variant, stretched scale (oblong shape) - **Appearance**: Dark purple, jagged movement, red eyes, emerges from forest edges in waves - **Behavior**: Moves toward ranch house directly, damages slimes on contact, drops essence on death - **Interaction**: Player clicks to prioritize targets, slimes auto-attack but player can influence focus ### Shadow Wolf (Elite Enemy) - **Sprite**: `ghost` with black color tint and fast animation speed - **Appearance**: Shadowy wolf-like form, moves quickly, dashes toward slimes to disable them temporarily - **Behavior**: Targets slimes specifically, temporary stun on hit, drops rare shadow essence - **Interaction**: High priority target, player must quickly click to direct slimes to intercept ### Slime King (Mini-Boss) - **Sprite**: `slime` with golden ProceduralSprite variant, massive scale (2x), glow effect enabled - **Appearance**: Giant golden slime with crown-like protrusion, slow but devastating, spawns every 10 waves - **Behavior**: Extremely high HP, spawns smaller slimes as minions, drops king essence (prestige currency) - **Interaction**: Requires concentrated slime force, player must micromanage slime positioning to win ## Core Loop ### Second-to-Second (ACTIVE GAMEPLAY) - **Player watches enemy waves approach** from forest edges, clicking on high-priority targets (shadow wolves targeting valuable slimes) - **Drags slimes tactically**—pulling warriors to the left flank where enemies are concentrated, moving breeders to safety in back pens - **Clicks on spawned food items** to feed specific slimes, watching them instantly evolve with visual flash and size increase - **Collects baby slimes** by clicking them before they wander into danger (10-second timer before they escape) - **Activates charged slime abilities**—clicking a glowing warrior slime triggers area damage blast ### Minute-to-Minute (STRATEGIC DECISIONS) - **Between waves**, player checks slime composition—too many breeders and defense will fail, too many warriors and economy stagnates - **Buys pen upgrades** that visibly expand grazing areas on Canvas, allowing more slimes to be housed - **Evolution choices**—feeding a slime crystal essence vs. forest essence creates different evolution paths visible on Canvas - **Builds defensive structures**—places slime toys that boost breeding speed or defensive barriers that block enemy movement ### Session-Level (META STRATEGY) - **Player pursues a build**—"slime swarm" strategy (many weak slimes) vs. "elite defender" (few powerful evolved slimes) - **The ranch visibly transforms** from a simple pen to a complex fortress with multiple zones, specialized breeding areas, and defensive layers - **Prestige push**—player accumulates king essence from bosses, eventually resetting for permanent slime gene upgrades that make evolved slimes more powerful ## The 30-Second Gameplay Description Enemies pour from the forest edge as the player quickly clicks a shadow wolf to mark it priority. Two warrior slimes bounce toward it, leaving a gap on the right. The player drags a third warrior from the back pen to plug the hole, then spots a baby slime wandering toward the oncoming wave. She clicks it to collect, adding it to her inventory. A corrupted spider breaks through and lunges at a breeder slime—the player frantically drags the breeder to safety, then feeds a crystal essence to a nearby warrior, watching it flash and grow into an elite form with visible armor plates. The elite slimes slam into the wolf, defeating it as purple essence sprites float from its corpse. The player clicks the essence to collect, watching it sparkle toward her currency counter. ## Currencies ### Slime Tokens - **Role**: Primary currency - **Earned by**: Clicking on baby slimes to "ranch" them before they escape (Canvas interaction), plus passive generation from breeder slimes - **Spent on**: Buying new slimes, pen upgrades, basic food items - **Feel**: The "always flowing" currency that keeps the ranch running. Satisfying to collect from Canvas. ### Essence - **Earned by**: Enemy deaths drop essence sprites on Canvas that must be clicked to collect—different enemies drop different colors (corrupted spiders = purple essence, shadow wolves = shadow essence) - **Spent on**: Evolution items, special abilities, pen decorations - **Feel**: Combat reward currency. Visible feedback loop—kill enemies, see essence, click to collect, get stronger. ### King Essence (Prestige Currency) - **Earned by**: Defeating Slime King mini-boss (every 10 waves), drops rare golden essence sprites - **Spent on**: Permanent slime gene upgrades (carry across prestiges), unlocks new evolution paths - **Feel**: The rare, precious reward. Players work toward each King fight excitedly. ### Genes (Prestige Reset Currency) - **Earned by**: Prestiging—converting accumulated resources and slime count into genes - **Spent on**: Permanent bonuses: starting slimes, evolution speed, essence drop rate, new evolution paths - **Feel**: Long-term progression. Each prestige visibly changes starting conditions on Canvas. ### Currency Flow Slime Tokens buy slimes and food → fed slimes evolve → stronger slimes kill more enemies → enemies drop Essence → Essence buys evolution items → evolved slimes produce more Tokens (better breeders) and kill bosses faster → King Essence unlocks genes → Genes make everything more efficient → cycle accelerates. ## Progression Hooks ### Early Game (0-5 minutes) - **First slime placement**: Player starts with 2 rancher slimes and 1 breeder. Immediate Canvas interaction—dragging them into position. - **First wave approach**: Enemies emerge, player sees slimes auto-attack, discovers they can click to prioritize targets. - **First baby slime**: Breeder produces a baby, player learns to click it before it escapes. Immediate "aha—I need to pay attention!" - **First evolution**: Player buys essence food, feeds a slime, watches it transform into a warrior. Visual payoff. ### Mid Game (5-15 minutes) - **Multiple pens unlock**: Player can now separate zones—breeding area, defensive trench, nursery. Canvas becomes spatially complex. - **Evolution paths**: Player discovers crystal essence vs. forest essence creates different slime types. Strategic choice emerges. - **Shadow wolves appear**: New enemy type requires active micromanagement. Player must decide: protect breeders or let them die? - **Slime abilities**: Charged slimes unlock special moves. Player now times ability activations during waves. ### Late Game (15-30 minutes) - **Slime King encounters**: Every 10 waves, the massive boss appears. Requires full slime army coordination to defeat. - **Prestige approach**: Player accumulates 3-5 King Essence, faces the decision: prestige now for genes or push for more? - **Maxed ranch**: Canvas is crowded with evolved slimes, multiple zones, active defenses. Visual spectacle of slime army vs. enemy waves. - **Gene upgrades visible**: After first prestige, player starts with evolved slimes and better pens. Run 2 feels different immediately. ### Key Milestones 1. **First Successful Wave Defense**: Survive wave 3 without any slime deaths → unlocks pen expansion 2. **First Warrior Evolution**: Evolve a rancher slime using essence → unlocks evolution system fully 3. **Baby Boom**: Reach 10 slimes in pens → unlocks breeder specialization upgrade 4. **Elite Slime**: Evolve a slime to elite form → unlocks special abilities 5. **Shadow Wolf Slayer**: Defeat first shadow wolf → drops shadow essence, unlocks dark evolution path 6. **King's Fall**: Defeat first Slime King → drops king essence, unlocks prestige 7. **Full Ranch**: All pen zones unlocked and upgraded → visual transformation to fortress 8. **First Prestige**: Reset with genes → Run 2 starts with 2 elite slimes and expanded pens 9. **Gene Mastery**: Unlock 5 gene upgrades → prestige currency multiplier 10. **Slime Godhood**: Reach 100 slimes in late game → ultimate visual spectacle, all evolution paths active ## Meaningful Choices - **Choice 1: Quantity vs. Quality** - **Options**: Invest tokens in many basic slimes (swarm strategy) OR fewer evolved slimes (elite strategy) - **Tradeoff**: Many slimes can cover more ground but die easily; elites are powerful but can't be everywhere - **Canvas impact**: Swarm fills the screen with bouncing slimes, zerg-rush style. Elite strategy shows fewer, larger slimes with dramatic ability effects - **Choice 2: Economy vs. Defense** - **Options**: Build more breeder slimes for faster token generation OR more warriors for better defense - **Tradeoff**: More breeders = faster evolution but vulnerable to attacks. More warriors = safer but slower progression - **Canvas impact**: Heavy breeder strategy shows constant baby slime production, active clicking to collect. Heavy warrior strategy shows intense combat with less baby management ## Prestige Concept - **Trigger**: Player accumulates 5+ King Essence (from defeating Slime King bosses) and feels the ranch is maxed out - **What resets**: All slimes, pen upgrades, tokens, essence, items. Ranch returns to basic state with 2 rancher slimes. - **What persists**: Genes (permanent upgrades), unlocked evolution paths, slime knowledge (can evolve immediately in Run 2) - **Prestige currency**: Genes, earned from King Essence conversion (1 King Essence = 10 genes base, multiplied by bonuses) - **Acceleration**: Run 2 starts with gene bonuses applied—e.g., "Gene: Fast Start" begins with 5 slimes instead of 2. Player can evolve slimes immediately (no need to unlock). Pen expansions are cheaper. - **Visual transformation**: After prestige, the ranch house visually upgrades (thatch roof → stone castle → crystal fortress). Background shows accumulated prestige rank in subtle ways (flags, trophies). Slimes gain subtle visual auras indicating gene strength. ## Unique Selling Point **Real-time positional tactics meet incremental breeding**—you're not just watching numbers go up, you're actively managing a living army of slimes on the Canvas, dragging units to respond to threats, clicking to collect babies, and timing ability activations, while the incremental systems make your army stronger over time. The game is simultaneously an action-oriented tower defense and a breeding simulation economy game. ## Visual Direction - **Color palette**: Vibrant, saturated colors—bright blues, pinks, greens for slimes; deep purples for corrupted enemies; golden highlights for rare items - **Aesthetic**: Cute but dangerous—slimes are adorable and bouncy, combat effects are satisfyingly crunchy with pops and bursts - **Mood**: Whimsical tension—the ranch feels peaceful between waves, chaotic and desperate during enemy attacks - **Canvas feel**: Alive and squishy—every slime bounce has stretch/compress, enemies have jagged threatening movements, particles burst on hits ## Technical Scope Check - **Implementability**: HIGH. All mechanics use standard sprite framework features—position, drag, click detection, basic AI (move toward target), collision detection - **Complex mechanics**: Slime breeding with inheritance is most complex—can simplify to random evolution instead of genetic system - **Wave system**: Standard incremental pattern—each wave gets harder, new enemy types unlock over time - **Simplification opportunities**: Remove slime toy placement if time-constrained (focus on slime management only), simplify to 2 evolution paths instead of 3, remove special abilities if core gameplay is engaging enough - **AI complexity**: Slime AI can be simple state machine (idle → patrol → chase → attack), doesn't need pathfinding - **Performance**: Limited entity count (cap at 100 slimes, 50 enemies) ensures smooth Canvas rendering This game is highly implementable because it relies on: 1. Basic sprite movement and animation (built into framework) 2. Click/drag interaction (standard Canvas events) 3. Simple collision detection (circle/box overlap) 4. Wave spawning system (incremental standard) 5. Currency and upgrade systems (provided in framework) The unique innovation is the combination of breeding economy + positional tactics, but both systems are straightforward to implement.

Currencies

# Phase 2 GDD: Currency System Design
## Slime Rancher Defense

---

## 1. Economy Flow Diagram

```mermaid
flowchart LR
    subgraph "Sources (Gameplay Actions)"
        BabyCollect["Baby Slime Collected\n+5 Tokens\nClick on Canvas"]
        EnemyKill["Enemy Defeated\n+2-8 Essence\nAuto-drop + Click to collect"]
        WaveComplete["Wave Complete\n+50 Tokens * waveNumber\nAuto-collect"]
        BossKill["Slime King Defeated\n+3 King Essence\nAuto-drop + Click to collect"]
        FirstKill["First Enemy in Wave\n+10 Tokens bonus\nOnce per wave"]
    end

    subgraph "Sources (Passive Generation)"
        BreederProd["Breeder Slime Production\n+0.5 Tokens/sec per breeder"]
        PenBonus["Pen Upgrade Bonus\n+1-10 Tokens/sec based on pens"]
        GeneIncome["Gene: Token Boost\n+10-50% passive multiplier"]
    end

    subgraph "Currencies"
        Tokens((Slime Tokens\nPrimary\nstart: 50\ncap: 999,999\n🪙))
        Essence((Essence\nCombat/Evolution\nstart: 0\ncap: 99,999\n💜))
        KingEssence((King Essence\nPrestige\nstart: 0\ncap: 999\n👑))
        Genes((Genes\nMeta Upgrade\nstart: 0\npersists forever\n🧬))
    end

    subgraph "Conversion Paths"
        TokensToEssence["Buy Basic Food\n10 Tokens → 5 Essence\nShop: instant"]
        EssenceToKing["Accumulate to Boss\nCannot convert directly\nMust defeat Slime King"]
        KingToGenes["Prestige Action\n1 King Essence = 10 Genes\nRequires prestige reset"]
    end

    subgraph "Sinks (Token Spending)"
        BuySlime["Buy Slime\nRancher: 20 Tokens\nBreeder: 50 Tokens\nWarrior: 100 Tokens"]
        PenUpgrade["Pen Expansion\nLevel 1: 100 Tokens\nLevel 2: 500 Tokens\nLevel 3: 2000 Tokens"]
        BuyFoodBasic["Basic Food\n10 Tokens → 5 Essence\nInstant shop purchase"]
        BuyStructure["Place Structures\nToys: 50 Tokens\nBarriers: 150 Tokens"]
        PenDecor["Pen Decorations\nBoost breeder production\n75-500 Tokens"]
    end

    subgraph "Sinks (Essence Spending)"
        EvolveWarrior["Evolve to Warrior\n50 Essence\nRequires Rancher Slime"]
        EvolveElite["Evolve to Elite\n200 Essence\nRequires Warrior Slime"]
        SpecialFood["Special Evolution Food\n100 Essence each\nCrystal/Shadow types"]
        UnlockAbility["Unlock Special Ability\n150 Essence\nPer slime type"]
        PenDecoration["Pen Decorations\nCombat-themed\n50-300 Essence"]
    end

    subgraph "Sinks (King Essence Spending)"
        PrestigeTrigger["Trigger Prestige\nRequires 5+ King Essence\nOptional at any amount"]
        GeneSlots["Unlock Gene Slots\n1-5 King Essence each\nMax 10 slots"]
        EvolutionPath["Unlock Evolution Path\n3 King Essence each\nNew paths"]
    end

    subgraph "Sinks (Gene Spending)"
        GeneFastStart["Fast Start Gene\n5 Genes\n+3 starting slimes"]
        GeneTokenBoost["Token Boost Gene\n8 Genes\n+25% passive tokens"]
        GeneEssenceDrop["Essence Drop Gene\n10 Genes\n+50% essence drops"]
        GeneEvoSpeed["Evolution Speed Gene\n12 Genes\nInstant evolution"]
        GeneNewPath["New Evolution Path Gene\n15 Genes\nUnlock special path"]
        GenePenDiscount["Pen Discount Gene\n7 Genes\n-20% pen costs"]
        GeneKingLoot["King Loot Gene\n20 Genes\n+2 King Essence per boss"]
    end

    %% Primary Flow: Gameplay Actions
    BabyCollect --> Tokens
    FirstKill --> Tokens
    WaveComplete --> Tokens

    %% Passive Flow
    BreederProd --> Tokens
    PenBonus --> Tokens
    GeneIncome --> Tokens

    %% Combat Flow
    EnemyKill --> Essence
    BossKill --> KingEssence

    %% Token Sinks
    Tokens --> BuySlime
    Tokens --> PenUpgrade
    Tokens --> BuyFoodBasic
    Tokens --> BuyStructure
    Tokens --> PenDecor
    Tokens --> TokensToEssence
    TokensToEssence --> Essence

    %% Essence Sinks
    Essence --> EvolveWarrior
    Essence --> EvolveElite
    Essence --> SpecialFood
    Essence --> UnlockAbility
    Essence --> PenDecoration

    %% King Essence Flow
    KingEssence --> PrestigeTrigger
    KingEssence --> GeneSlots
    KingEssence --> EvolutionPath
    KingEssence --> KingToGenes
    KingToGenes --> Genes

    %% Gene Sinks
    Genes --> GeneFastStart
    Genes --> GeneTokenBoost
    Genes --> GeneEssenceDrop
    Genes --> GeneEvoSpeed
    Genes --> GeneNewPath
    Genes --> GenePenDiscount
    Genes --> GeneKingLoot

    %% Feedback Loops (shown as indirect)
    BuySlime -.->|"More slimes = more kills"| Essence
    EvolveElite -.->|"Elite slimes kill bosses"| KingEssence
    GeneEssenceDrop -.->|"More drops = more essence"| Essence
    GeneTokenBoost -.->|"More tokens = more slimes"| Tokens
```

---

## 2. Currency Definitions Diagrams

### Slime Tokens

```mermaid
graph TD
    subgraph "Slime Tokens [Primary Currency]"
        T_display["Display: 🪙 Slime Tokens\n0 decimals\nSuffixes: K/M/B\nColor: #FFD700 (Gold)"]
        T_start["Starting Amount: 50\nGenerous start for first purchases"]
        T_earn["Earning Methods:\n\nGameplay:\n- Baby slime collected: +5 Tokens\n- First enemy in wave: +10 Tokens (once/wave)\n- Wave complete: +50 * waveNumber Tokens\n\nPassive:\n- Breeder slime: +0.5 Tokens/sec per breeder\n- Pen upgrades: +1-10 Tokens/sec\n- Gene bonuses: +10-50% multiplier"]
        T_spend["Spending Methods:\n\n- Buy Rancher Slime: 20 Tokens\n- Buy Breeder Slime: 50 Tokens\n- Buy Warrior Slime: 100 Tokens\n- Pen Level 1: 100 Tokens\n- Pen Level 2: 500 Tokens\n- Pen Level 3: 2000 Tokens\n- Basic Food: 10 Tokens → 5 Essence\n- Structure Toy: 50 Tokens\n- Barrier: 150 Tokens\n- Pen Decoration: 75-500 Tokens"]
        T_inflation["Inflation Control:\n\n- Pen costs scale exponentially (2x-4x per level)\n- Slime costs fixed (encourages quantity)\n- Food purchase creates Essence drain\n- Prestige resets all Tokens"]
        T_cap["Hard Cap: 999,999\n- Overflow beyond cap is lost\n- Creates spending pressure\n- Prevents infinite hoarding"]
    end
```

### Essence

```mermaid
graph TD
    subgraph "Essence [Combat/Evolution Currency]"
        E_display["Display: 💎 Essence\n0 decimals\nSuffixes: K/M\nColor: #9B59B6 (Purple)"]
        E_start["Starting Amount: 0\nMust be earned from combat"]
        E_earn["Earning Methods:\n\nGameplay ONLY:\n- Corrupted Spider killed: +2 Essence\n- Shadow Wolf killed: +5 Essence\n- Slime King minion: +3 Essence\n\nBonus Multipliers:\n- Gene: Essence Drop +50%\n- Elite Slime kill: +25% bonus\n- Wave number multiplier: 1 + (wave * 0.05)"]
        E_collect["Collection Mechanic:\n- Drops as sprite on Canvas\n- Player must click to collect\n- Lifetime: 8 seconds\n- Collect radius: 20 pixels\n- Floating text: '+{value} 💎'"]
        E_spend["Spending Methods:\n\n- Evolve Rancher → Warrior: 50 Essence\n- Evolve Warrior → Elite: 200 Essence\n- Crystal Essence Food: 100 Essence\n- Shadow Essence Food: 100 Essence\n- Unlock Special Ability: 150 Essence\n- Pen Decoration (Combat): 50-300 Essence"]
        E_inflation["Inflation Control:\n\n- Evolution costs fixed (encourages targeting)\n- Special foods are repeatable (constant drain)\n- Abilities unlock once per slime type\n- Prestige resets all Essence"]
        E_cap["Hard Cap: 99,999\n- Overflow beyond cap is lost\n- Creates evolution pressure"]
    end
```

### King Essence

```mermaid
graph TD
    subgraph "King Essence [Prestige Currency]"
        K_display["Display: 👑 King Essence\n0 decimals\nNo suffixes (rare)\nColor: #FFA500 (Golden Orange)"]
        K_start["Starting Amount: 0\nMust earn from bosses"]
        K_earn["Earning Method:\n\nBoss Gameplay ONLY:\n- Slime King defeated: +3 King Essence (base)\n- Gene: King Loot +2 per boss\n- Total per boss: 3-5 King Essence\n\n- Drops 3 golden sprites on Canvas\n- Each sprite worth 1 King Essence\n- Player must click each to collect\n- Lifetime: 15 seconds\n- Collect radius: 25 pixels"]
        K_spend["Spending Methods:\n\n- Unlock Gene Slot: 1-5 King Essence (progressive)\n- Unlock Evolution Path: 3 King Essence each\n- Prestige Conversion: 1 King Essence → 10 Genes"]
        K_strategic["Strategic Decision:\n\n- Trade-off: Unlock now OR save for prestige?\n- More King Essence = more Genes on prestige\n- But spending on slots/paths accelerates current run\n- Player decision point: 'Can I earn more before prestiging?'"]
        K_inflation["Inflation Control:\n\n- Boss spawns every 10 waves\n- Difficulty increases each boss\n- Eventually impossible to progress\n- Forces prestige decision"]
        K_cap["Hard Cap: 999\n- Realistically unreachable\n- Single run max: ~30 King Essence"]
    end
```

### Genes

```mermaid
graph TD
    subgraph "Genes [Meta Upgrade Currency]"
        G_display["Display: 🧬 Genes\n0 decimals\nSuffixes: K/M\nColor: #2ECC71 (Green)"]
        G_start["Starting Amount: 0\nEarned through prestige"]
        G_earn["Earning Method:\n\nPrestige Conversion:\n- Base rate: 1 King Essence = 10 Genes\n- Conversion multiplier: 1.0 + (prestigeCount * 0.1)\n- Bonus: +5 Genes per 100 slimes owned\n- Bonus: +10 Genes per pen level owned\n\nExample:\n- 5 King Essence * 10 = 50 Genes\n- First prestige bonus: * 1.0 = 50 Genes\n- 20 slimes: +1 Genes\n- 3 pen levels: +3 Genes\n- Total: 54 Genes"]
        G_persist["Persists Across ALL Prestiges:\n- Never reset\n- Permanent progression\n- Accumulates over entire playtime"]
        G_spend["Spending Methods (ONE-TIME UNLOCKS):\n\n- Fast Start: 5 Genes (+3 starting slimes)\n- Token Boost: 8 Genes (+25% passive tokens)\n- Essence Drop: 10 Genes (+50% essence drops)\n- Evolution Speed: 12 Genes (Instant evolution)\n- Pen Discount: 7 Genes (-20% pen costs)\n- King Loot: 20 Genes (+2 King Essence/boss)\n- New Evolution Path: 15 Genes each\n- Starting Elite: 25 Genes\n- Auto-Collect: 30 Genes\n- Max Slimes +10: 10 Genes each"]
        G_inflation["No Inflation Control:\n- Costs are fixed one-time purchases\n- All upgrades are permanent\n- Player can eventually unlock everything\n- Gene farming becomes long-term goal"]
    end
```

---

## 3. Conversion Rate Diagram

```mermaid
flowchart LR
    subgraph "Token Conversions"
        T1["Slime Tokens\n(10)"] -->|"Shop Purchase\nInstant\nNo cooldown\nUnlocked: Start"| E1["Essence\n(5)"]
    end

    subgraph "Boss-Based Conversion"
        E2["Essence\n(spent on evolution)"] -->|"Indirect Conversion\nEvolved slimes kill bosses faster"| B1["Slime King\nDefeated"]
        B1 -->|"Drops 3 sprites\nMust click to collect\n15s lifetime"| K1["King Essence\n(+3 base)"]
    end

    subgraph "Prestige Conversion"
        K2["King Essence\n(1)"] -->|"Prestige Action\nRequires full reset\nConversion rate: 1:10\nMultiplier: 1.0 + (prestige * 0.1)"| G1["Genes\n(+10 base)"]
    end

    subgraph "Gene Multiplier Effect"
        G2["Genes\n(spent on upgrades)"] -.->|"Token Boost Gene\n+25% passive"| T2["Slime Tokens\n(more passive income)"]
        G3["Genes\n(spent on upgrades)"] -.->|"Essence Drop Gene\n+50% drops"| E3["Essence\n(more combat rewards)"]
        G4["Genes\n(spent on upgrades)"] -.->|"King Loot Gene\n+2 per boss"| K3["King Essence\n(more per boss)"]
    end

    style T1 fill:#FFD700
    style E1 fill:#9B59B6
    style K1 fill:#FFA500
    style G1 fill:#2ECC71
```

---

## 4. Pacing Timeline

```mermaid
gantt
    title Currency Pacing (First 30 Minutes)
    dateFormat mm:ss
    axisFormat %M:%S

    section Slime Token Milestones
    First baby slime collected (5 Tokens)      :milestone, 00:15, 0
    First breeder slime purchase (50 Tokens)   :milestone, 01:00, 0
    Pen Level 1 upgrade (100 Tokens)           :milestone, 02:30, 0
    First warrior slime purchase (100 Tokens)  :milestone, 04:00, 0
    Pen Level 2 upgrade (500 Tokens)           :milestone, 08:00, 0
    Elite evolution (via food) (100 Tokens)    :milestone, 12:00, 0
    Pen Level 3 upgrade (2000 Tokens)          :milestone, 18:00, 0
    Mid-game token surplus (10K Tokens)        :milestone, 25:00, 0

    section Essence Milestones
    First enemy kill drops Essence (2)         :milestone, 00:45, 0
    First shadow wolf (5 Essence)              :milestone, 05:00, 0
    First warrior evolution (50 Essence)       :milestone, 06:30, 0
    First elite evolution (200 Essence)        :milestone, 14:00, 0
    Special evolution path unlocked (100)      :milestone, 16:00, 0
    Essence surplus (5K Essence)               :milestone, 28:00, 0

    section King Essence Milestones
    First Slime King encounter (wave 10)       :milestone, 10:00, 0
    First King Essence collected (3)           :milestone, 11:30, 0
    Second Slime King (wave 20)                :milestone, 22:00, 0
    Prestige available (5+ King Essence)       :milestone, 28:00, 0

    section Gene Milestones
    First prestige (50-100 Genes)              :milestone, 30:00, 0
    First gene unlock (Fast Start - 5 Genes)   :milestone, 31:00, 0

    section Key Moments
    First wave spawns enemies                  :milestone, 00:30, 0
    First breeder produces baby                :milestone, 01:30, 0
    First slime death (need replacement)       :milestone, 03:00, 0
    Pen expansion visible on Canvas            :milestone, 03:00, 0
    First elite slime on field                 :milestone, 07:00, 0
    Shadow wolves introduced (wave 5)          :milestone, 06:00, 0
    Boss fight becomes challenging             :milestone, 12:00, 0
    Prestige decision point                    :milestone, 28:00, 0
```

---

## 5. Upgrade Cost Curves

### Pen Upgrades

```mermaid
graph LR
    subgraph "Pen Expansion [Slime Capacity + Effect]"
        P0["Level 0 (Start)\nCost: Free\nCapacity: 5 slimes\nEffect: None"]
        P1["Level 1\nCost: 100 Tokens\nCapacity: 10 slimes\nEffect: +1 Token/sec"]
        P2["Level 2\nCost: 500 Tokens\nCapacity: 20 slimes\nEffect: +3 Tokens/sec"]
        P3["Level 3\nCost: 2000 Tokens\nCapacity: 40 slimes\nEffect: +10 Tokens/sec\nUnlock: Nursery Zone"]
        P4["Level 4\nCost: 8000 Tokens\nCapacity: 75 slimes\nEffect: +25 Tokens/sec\nUnlock: Defensive Trench"]
        P5["Level 5 (MAX)\nCost: 32000 Tokens\nCapacity: 100 slimes\nEffect: +50 Tokens/sec\nUnlock: All Zones"]
        P0 --> P1 --> P2 --> P3 --> P4 --> P5
    end
```

### Slime Purchase Costs

```mermaid
graph LR
    subgraph "Slime Purchases [Fixed Cost - Quantity Strategy]"
        S1["Rancher Slime\nCost: 20 Tokens\nHP: 50\nDamage: 5\nRole: Basic Fighter"]
        S2["Breeder Slime\nCost: 50 Tokens\nHP: 30\nDamage: 0\nRole: Economy (Babies)"]
        S3["Warrior Slime\nCost: 100 Tokens\nHP: 100\nDamage: 15\nRole: Tank/DPS"]
        S1 --> S2
        S1 --> S3
    end
```

### Evolution Costs

```mermaid
graph LR
    subgraph "Evolution Path [Essence Spending]"
        E1["Rancher Slime\n(Base)"]
        E2["Warrior Evolution\nCost: 50 Essence\nHP: 100 → 150\nDamage: 15 → 25\nUnlock: Active Targeting"]
        E3["Elite Evolution\nCost: 200 Essence\nHP: 150 → 250\nDamage: 25 → 40\nUnlock: Special Ability"]
        E4["Crystal Path\nCost: 100 Essence\nEffect: +50% Ranged Damage\nColor: Cyan glow"]
        E5["Shadow Path\nCost: 100 Essence\nEffect: +50% Melee Damage\nColor: Dark aura"]
        E1 --> E2
        E2 --> E3
        E2 --> E4
        E2 --> E5
    end
```

### Gene Upgrade Costs

```mermaid
graph LR
    subgraph "Gene Upgrades [Permanent One-Time]"
        G1["Fast Start\nCost: 5 Genes\nEffect: +3 starting slimes"]
        G2["Pen Discount\nCost: 7 Genes\nEffect: -20% pen costs"]
        G3["Token Boost\nCost: 8 Genes\nEffect: +25% passive tokens"]
        G4["Essence Drop\nCost: 10 Genes\nEffect: +50% essence drops"]
        G5["Max Slimes +10\nCost: 10 Genes\nEffect: Cap +10"]
        G6["Evolution Speed\nCost: 12 Genes\nEffect: Instant evolution"]
        G7["New Evolution Path\nCost: 15 Genes\nEffect: Unlock path"]
        G8["Starting Elite\nCost: 25 Genes\nEffect: Begin with 1 Elite"]
        G9["Auto-Collect\nCost: 30 Genes\nEffect: Auto-collect babies"]
        G10["King Loot\nCost: 20 Genes\nEffect: +2 King Essence/boss"]
    end
```

---

## 6. Collectible Entity State Machines

### Baby Slime (Token Source)

```mermaid
stateDiagram-v2
    [*] --> Spawning: breeder produces baby\n(production timer completes)
    Spawning --> Wandering: spawn animation (400ms)\nVisible at pen location

    Wandering --> Wandering: wander timer tick\n(random direction change)
    Wandering --> Collected: player clicks baby\n(collect radius: 18px)
    Wandering --> Escaped: lifetime exceeds 10s\n(player failed to collect)
    Wandering --> Drifting: Auto-Collect Gene active\n(baby moves toward player cursor)

    Drifting --> Collected: reaches collection point
    Drifting --> Escaped: lifetime exceeds 10s

    Collected --> [*]: add Tokens (+5)\nspawn floating text("+5 🪙", gold)\nplay sound: collect_baby.mp3\nparticle burst (5 pink particles)

    Escaped --> [*]: fade out animation (500ms)\nshow "Escaped!" text\nplay sound: fail.mp3

    note right of Wandering
        Visual: Small pink slime bobbing
        Bounce animation: 0.5s period
        Shows "5" on hover
        Escape timer bar visible above
        Clickable radius: 18px
        Movement: Random walk within pen
    end note

    note right of Collected
        Immediate feedback:
        - Currency counter animates
        - Floating text at baby position
        - Sound plays
        - Baby despawns immediately
    end note
```

### Essence Drop (Combat Reward)

```mermaid
stateDiagram-v2
    [*] --> Spawning: enemy dies at position\n(death animation starts)
    Spawning --> Active: spawn animation (300ms)\nScale 0 → 1 (pop in)\nVisible at enemy death location

    Active --> Active: bob animation\n(amplitude: 3px, speed: 2Hz)\nglow pulse
    Active --> Collected: player clicks essence\n(collect radius: 20px)
    Active --> Expired: lifetime exceeds 8s\n(player didn't collect)
    Active --> Magneting: Magnet upgrade active\n(player within 100px)

    Magneting --> Collected: reaches player position
    Magneting --> Expired: lifetime exceeds 8s

    Collected --> [*]: add Essence (+value)\nspawn floating text("+{value} 💎", purple)\nplay sound: collect_essence.mp3\nparticle burst (5 purple particles)

    Expired --> [*]: fade out (500ms)\nshrink to scale 0

    note right of Active
        Visual: Purple crystal sprite
        Shows value on hover (2/3/5)
        Glow effect enabled
        Spawns 1 sprite per enemy kill
        Position: Enemy death coordinates
    end note

    note right of Collected
        Value depends on enemy:
        - Corrupted Spider: +2 Essence
        - Shadow Wolf: +5 Essence
        - King Minion: +3 Essence
        - First kill bonus: +50% (wave only)
    end note
```

### King Essence Drop (Boss Reward)

```mermaid
stateDiagram-v2
    [*] --> Spawning: Slime King dies\n(boss death animation)
    Spawning --> Active: spawn 3 sprites\n(500ms delay between each)\nSpawn at boss death position

    Active --> Active: majestic bob animation\n(amplitude: 5px, speed: 1Hz)\ngolden glow pulse
    Active --> Collected: player clicks essence\n(collect radius: 25px)
    Active --> Expired: lifetime exceeds 15s\n(rare case)
    Active --> Magneting: Magnet upgrade active\n(player within 120px)

    Magneting --> Collected: reaches player position
    Magneting --> Expired: lifetime exceeds 15s

    Collected --> [*]: add King Essence (+1)\nspawn floating text("+1 👑", gold)\nplay sound: collect_king.mp3\nparticle burst (10 gold particles)\nScreen flash effect

    Expired --> [*]: fade out (1000ms)\nshrink to scale 0\n(WARNING: Rare resource lost!)

    note right of Active
        Visual: Large golden crown sprite
        Shows "KING ESSENCE" on hover
        Massive glow effect
        Spawns 3 sprites (each worth 1)
        Lifetime: 15s (generous)
        Collect radius: 25px
    end note

    note right of Collected
        Value: Always +1 King Essence
        Special effects:
        - Screen golden flash
        - Achievement sound
        - Particle explosion
        - This is a BIG MOMENT
    end note
```

### Wave Complete Reward

```mermaid
stateDiagram-v2
    [*] --> Spawning: last enemy in wave dies\nwave.clear() triggers
    Spawning --> AutoCollected: instant (no spawn)\nAuto-add to Tokens

    AutoCollected --> [*]: add Tokens (+50 * waveNumber)\nspawn HUD notification\n"Wave Complete! +{value} 🪙"\nplay sound: wave_complete.mp3\nshow wave summary panel

    note right of AutoCollected
        No collection required
        Auto-added to balance
        Formula: 50 * waveNumber
        Examples:
        - Wave 1: +50 Tokens
        - Wave 5: +250 Tokens
        - Wave 10: +500 Tokens
        - Wave 20: +1000 Tokens
    end note

    note right of Spawning
        Triggered by wave system
        Happens immediately
        No player action needed
        Reward scales with wave number
        Encourages wave progression
    end note
```

### First Kill Bonus (Wave Event)

```mermaid
stateDiagram-v2
    [*] --> Waiting: wave starts\nwave.firstKill = true
    Waiting --> Triggered: first enemy dies in wave\nwave.firstKill == true
    Triggered --> AutoCollected: instant (no spawn)\nSet wave.firstKill = false

    AutoCollected --> [*]: add Tokens (+10)\nspawn floating text\n"FIRST KILL! +10 🪙"\nplay sound: first_kill.mp3

    Waiting --> Waiting: enemy dies\n(firstKill already claimed)

    note right of Triggered
        Once per wave ONLY
        First enemy death triggers
        Applies to ANY enemy type
        Even baby collection counts
        Encourages quick wave starts
    end note

    note right of AutoCollected
        Fixed bonus: +10 Tokens
        Small but meaningful
        Creates micro-goal per wave
        Teaches wave awareness
    end note
```

---

## 7. Currency Event Flows

### Baby Slime Collection Flow

```mermaid
sequenceDiagram
    participant Breeder as Breeder Slime
    participant Canvas as Canvas (Game World)
    participant Baby as Baby Slime Entity
    participant EventBus as EventBus
    participant Currency as CurrencyManager
    participant UI as HUD Display

    Breeder->>Canvas: production timer completes
    Canvas->>Baby: spawnBabySlime(position)
    Baby->>Baby: play spawn animation (400ms)
    Baby->>Canvas: visible at position
    Note over Canvas: Baby wanders randomly

    Canvas->>Canvas: player clicks at position
    Canvas->>Baby: click detection (18px radius)
    alt Click within radius
        Baby->>EventBus: emit('baby-collected', {position, value: 5})
        EventBus->>Currency: currency.add('tokens', 5)
        EventBus->>UI: floatingText("+5 🪙", position)
        EventBus->>Canvas: particleBurst(position, 5, 'pink')
        EventBus->>UI: updateDisplay('tokens')
        UI->>UI: count-up animation (200ms)
        Baby->>Baby: despawn immediately
    else Click outside radius
        Baby->>Baby: continue wandering
    end

    Note over Baby: 10 second lifetime elapses
    Baby->>EventBus: emit('baby-escaped')
    EventBus->>UI: floatingText("Escaped!", position, red)
    EventBus->>UI: playSound('fail.mp3')
    Baby->>Baby: fade out animation (500ms)
    Baby->>Baby: despawn
```

### Enemy Kill & Essence Collection Flow

```mermaid
sequenceDiagram
    participant Slime as Warrior Slime
    participant Enemy as Enemy Entity
    participant Canvas as Canvas (Game World)
    participant EventBus as EventBus
    participant Currency as CurrencyManager
    participant UI as HUD Display
    participant Essence as Essence Sprite

    Slime->>Enemy: attack(damage)
    Enemy->>Enemy: hp -= damage
    Enemy->>Canvas: play hit animation
    Canvas->>Canvas: particle burst at position

    alt hp <= 0 (Enemy dies)
        Enemy->>Enemy: play death animation
        Enemy->>EventBus: emit('enemy-killed', {type, position, waveNumber})
        EventBus->>Currency: calculateEssenceReward(type, waveNumber)
        Currency->>EventBus: return essenceValue
        EventBus->>Canvas: spawnEssence({type: 'essence', position, value})
        Canvas->>Essence: create essence sprite at position
        Essence->>Essence: play spawn animation (300ms scale 0→1)
        Essence->>Canvas: visible bobbing with glow
        Enemy->>Enemy: despawn

        Note over Canvas: Player sees essence sprite
        Canvas->>Canvas: player clicks near essence
        Canvas->>Essence: click detection (20px radius)
        Essence->>EventBus: emit('essence-collected', {value, position})
        EventBus->>Currency: currency.add('essence', value)
        EventBus->>UI: floatingText("+{value} 💎", position)
        EventBus->>Canvas: particleBurst(position, 5, 'purple')
        EventBus->>UI: updateDisplay('essence')
        EventBus->>UI: playSound('collect_essence.mp3')
        UI->>UI: count-up animation (200ms)
        Essence->>Essence: despawn immediately

        alt 8 seconds pass without collection
            Essence->>Essence: fade out (500ms)
            Essence->>Essence: despawn
            Essence->>EventBus: emit('essence-expired')
            EventBus->>UI: floatingText("Missed!", position, gray)
        end
    end
```

### Wave Complete Reward Flow

```mermaid
sequenceDiagram
    participant Wave as WaveSystem
    participant Enemy as Last Enemy in Wave
    participant EventBus as EventBus
    participant Currency as CurrencyManager
    participant UI as HUD Display
    participant Game as GameState

    Enemy->>Enemy: hp <= 0 (dies)
    Enemy->>Wave: notify enemy death
    Wave->>Wave: check if wave is clear
    Wave->>Wave: enemiesRemaining === 0
    Wave->>EventBus: emit('wave-complete', {waveNumber})
    EventBus->>Currency: calculateWaveReward(waveNumber)
    Currency->>Currency: reward = 50 * waveNumber
    EventBus->>Currency: currency.add('tokens', reward)
    EventBus->>UI: showNotification("Wave {waveNumber} Complete!")
    EventBus->>UI: floatingText("Wave Complete! +{reward} 🪙", centerScreen)
    EventBus->>UI: updateDisplay('tokens')
    UI->>UI: count-up animation (500ms, larger)
    EventBus->>UI: playSound('wave_complete.mp3')
    EventBus->>Game: startWaveIntermission()
    Game->>Game: showWaveSummaryPanel(stats)
    Game->>Wave: scheduleNextWave(delay)
```

### Boss Kill & King Essence Flow

```mermaid
sequenceDiagram
    participant Slime as Player Slimes
    participant Boss as Slime King
    participant Canvas as Canvas (Game World)
    participant EventBus as EventBus
    participant Currency as CurrencyManager
    participant UI as HUD Display
    participant KingE as King Essence Sprites

    Slime->>Boss: continuous attacks
    Boss->>Boss: hp -= damage
    Boss->>Canvas: show damage numbers

    alt hp <= 0 (Boss dies)
        Boss->>Boss: play epic death animation (2000ms)
        Boss->>Canvas: screen shake effect
        Boss->>Canvas: massive particle explosion
        Boss->>EventBus: emit('boss-defeated', {type: 'SlimeKing', position})
        EventBus->>Currency: calculateKingReward()
        Currency->>EventBus: return {kingEssence: 3}
        EventBus->>UI: showNotification("SLIME KING DEFEATED!")
        EventBus->>UI: playSound('boss_death.mp3')

        par Spawn 3 King Essence sprites (staggered)
            Canvas->>KingE: spawnKingEssence(position, delay=0ms)
            KingE->>KingE: spawn animation (300ms)
            KingE->>Canvas: visible with golden glow
        and
            Canvas->>KingE: spawnKingEssence(position, delay=500ms)
            KingE->>KingE: spawn animation (300ms)
        and
            Canvas->>KingE: spawnKingEssence(position, delay=1000ms)
            KingE->>KingE: spawn animation (300ms)
        end

        Boss->>Boss: despawn after animation

        Note over Canvas: Player clicks each King Essence
        Canvas->>KingE: click detection (25px radius)
        KingE->>EventBus: emit('king-essence-collected', {position})
        EventBus->>Currency: currency.add('kingEssence', 1)
        EventBus->>UI: floatingText("+1 👑", position)
        EventBus->>Canvas: particleBurst(position, 10, 'gold')
        EventBus->>UI: screenFlash(gold)
        EventBus->>UI: playSound('collect_king.mp3')
        EventBus->>UI: updateDisplay('kingEssence')
        UI->>UI: dramatic count-up (1000ms)
        KingE->>KingE: despawn

        alt All 3 collected
            EventBus->>UI: showAchievement("KING SLAYER!")
            EventBus->>UI: showPrestigeHint("5 King Essence to Prestige")
        end
    end
```

### Prestige Conversion Flow

```mermaid
sequenceDiagram
    participant Player as Player
    participant UI as Prestige Panel
    participant GameState as GameState
    participant Currency as CurrencyManager
    participant EventBus as EventBus
    participant Game as GameSession

    Player->>UI: click "Prestige" button
    UI->>UI: showPrestigeConfirmation()
    UI->>Player: display stats:\n- King Essence: {count}\n- Genes earned: {calculated}\n- Slimes owned: {count}\n- Pens upgraded: {levels}

    Player->>UI: confirm "Reset for Genes"
    UI->>EventBus: emit('prestige-triggered')
    EventBus->>Currency: calculateGeneYield(kingEssence, slimes, pens)
    Currency->>Currency: genes = kingEssence * 10\n* (1.0 + prestigeCount * 0.1)\n+ floor(slimes / 100 * 5)\n+ pens * 3
    EventBus->>Currency: prestigeCount += 1
    EventBus->>Currency: currency.add('genes', calculatedGenes)
    EventBus->>UI: showPrestigeSummary({genesEarned, newTotal})

    EventBus->>Game: resetRun()
    Game->>Game: removeAllSlimes()
    Game->>Game: resetPenUpgrades()
    Game->>Game: currency.tokens = 50\n(currency.essence = 0,\ncurrency.kingEssence = 0)
    Game->>Game: applyGeneBonuses()
    Game->>Game: respawnStartingSlimes()

    EventBus->>UI: showNotification("PRESTIGE COMPLETE!\n+{genes} 🧬")
    EventBus->>UI: playSound('prestige.mp3')
    EventBus->>UI: updateAllDisplays()

    Note over Game: Gene bonuses now active:\n- More starting slimes\n- Passive token multiplier\n- Essence drop boost\n- etc.
```

### Passive Generation Flow (Breeder Slime)

```mermaid
sequenceDiagram
    participant Breeder as Breeder Slime
    participant Timer as Game Timer
    participant Currency as CurrencyManager
    participant UI as HUD Display

    Note over Breeder: Passive production\nNOT a collectible event
    Timer->>Timer: game tick (every 1 second)
    Timer->>Breeder: for each breeder slimes
    Breeder->>Currency: calculatePassiveTokens()
    Currency->>Currency: base = 0.5 per breeder\nmultiplier = geneBonus (1.0 + 0.25 * geneLevel)\npenBonus = currentPenLevel\nresult = breeders * 0.5 * geneMultiplier + penBonus
    Currency->>Currency: currency.add('tokens', result)
    Currency->>UI: updateDisplay('tokens')

    Note over UI: No floating text\nJust counter increment\nSilent accumulation
```

---

## 8. CONFIG Spec: currencies Section

```javascript
// ============================================================================
// CONFIG.CURRENCIES - Complete Currency System Configuration
// ============================================================================
// This configuration defines every currency, source, sink, conversion,
// collectible, and upgrade cost for Slime Rancher Defense.
// ============================================================================

CONFIG.currencies = {
  tokens: {
    displayName: 'Slime Tokens',
    icon: '🪙',
    color: '#FFD700',
    startingAmount: 50,
    cap: 999999,
    decimals: 0,
    suffixes: ['K', 'M', 'B'],
    persistsOnPrestige: false,
  },
  essence: {
    displayName: 'Essence',
    icon: '💎',
    color: '#9B59B6',
    startingAmount: 0,
    cap: 99999,
    decimals: 0,
    suffixes: ['K', 'M'],
    persistsOnPrestige: false,
  },
  kingEssence: {
    displayName: 'King Essence',
    icon: '👑',
    color: '#FFA500',
    startingAmount: 0,
    cap: 999,
    decimals: 0,
    suffixes: [],
    persistsOnPrestige: false,
  },
  genes: {
    displayName: 'Genes',
    icon: '🧬',
    color: '#2ECC71',
    startingAmount: 0,
    cap: null, // uncapped
    decimals: 0,
    suffixes: ['K', 'M'],
    persistsOnPrestige: true,
  },
};

// ----------------------------------------------------------------------------
// CURRENCY SOURCES - How currencies are earned
// ----------------------------------------------------------------------------
CONFIG.currencySources = {
  // Token Sources
  babyCollected: {
    currency: 'tokens',
    formula: 'baseValue',
    baseValue: 5,
    description: 'Collected baby slime',
  },
  firstKillBonus: {
    currency: 'tokens',
    formula: 'baseValue',
    baseValue: 10,
    description: 'First enemy in wave',
    oncePerWave: true,
  },
  waveComplete: {
    currency: 'tokens',
    formula: 'baseReward * waveNumber',
    baseReward: 50,
    description: 'Wave completion bonus',
  },
  passiveGeneration: {
    currency: 'tokens',
    formula: '(breederCount * breederRate + penBonus) * geneMultiplier',
    breederRate: 0.5,
    penBonus: 'penLevel * penBonuses[level]',
    geneMultiplier: '1 + (geneLevel * 0.25)',
    description: 'Passive token generation',
  },

  // Essence Sources
  enemyKill: {
    currency: 'essence',
    formula: 'baseReward * (1 + waveNumber * 0.05) * geneDropMultiplier',
    baseReward: {
      'corruptedSpider': 2,
      'shadowWolf': 5,
      'kingMinion': 3,
    },
    geneDropMultiplier: '1 + (geneEssenceDrop * 0.5)',
    description: 'Enemy defeated',
  },
  buyEssence: {
    currency: 'essence',
    formula: 'outputAmount',
    inputCurrency: 'tokens',
    inputAmount: 10,
    outputAmount: 5,
    description: 'Buy basic essence food',
  },

  // King Essence Sources
  bossKill: {
    currency: 'kingEssence',
    formula: 'baseDrops + geneBonus',
    baseDrops: 3,
    geneBonus: 'geneKingLoot * 2',
    description: 'Slime King defeated',
  },

  // Gene Sources (Prestige)
  prestigeConversion: {
    currency: 'genes',
    formula: 'kingEssence * conversionRate * (1 + prestigeCount * 0.1) + slimeBonus + penBonus',
    conversionRate: 10,
    slimeBonus: 'floor(slimeCount / 100 * 5)',
    penBonus: 'penLevelSum * 3',
    description: 'Prestige conversion',
  },
};

// ----------------------------------------------------------------------------
// COLLECTIBLES - Spawnable sprites on Canvas
// ----------------------------------------------------------------------------
CONFIG.collectibles = {
  babySlime: {
    sprite: 'slime',
    colorVariant: 'pink',
    scale: 0.6,
    lifetime: 10, // seconds before escape
    collectRadius: 18, // pixels
    value: 5,
    currency: 'tokens',
    bobAmplitude: 2,
    bobSpeed: 2, // Hz
    spawnAnimation: 'popIn',
    spawnAnimationDuration: 400, // ms
    collectAnimation: 'burst',
    collectParticleCount: 5,
    collectParticleColor: '#FF69B4', // pink
    onCollect: 'currency.add(tokens, value)',
    onExpire: 'emit(baby-escaped)',
    expireAnimation: 'fadeOut',
    expireAnimationDuration: 500, // ms
    hoverText: '{value}',
  },

  essence: {
    sprite: 'crystal',
    colorVariant: 'purple',
    scale: 0.8,
    lifetime: 8,
    collectRadius: 20,
    value: 'calculated', // based on enemy type
    currency: 'essence',
    bobAmplitude: 3,
    bobSpeed: 2,
    spawnAnimation: 'popIn',
    spawnAnimationDuration: 300,
    collectAnimation: 'burst',
    collectParticleCount: 5,
    collectParticleColor: '#9B59B6', // purple
    onCollect: 'currency.add(essence, value)',
    onExpire: 'emit(essence-expired)',
    expireAnimation: 'fadeOut',
    expireAnimationDuration: 500,
    hoverText: '{value}',
    glowEffect: true,
    glowColor: '#9B59B6',
  },

  kingEssence: {
    sprite: 'crown',
    colorVariant: 'gold',
    scale: 1.5,
    lifetime: 15,
    collectRadius: 25,
    value: 1,
    currency: 'kingEssence',
    bobAmplitude: 5,
    bobSpeed: 1,
    spawnAnimation: 'popIn',
    spawnAnimationDuration: 500,
    collectAnimation: 'burst',
    collectParticleCount: 10,
    collectParticleColor: '#FFD700', // gold
    onCollect: 'currency.add(kingEssence, 1)',
    onExpire: 'emit(king-essence-expired)', // rare case
    expireAnimation: 'fadeOut',
    expireAnimationDuration: 1000,
    hoverText: 'KING ESSENCE',
    glowEffect: true,
    glowColor: '#FFA500',
    screenFlash: true,
    screenFlashColor: 'rgba(255, 215, 0, 0.3)',
  },
};

// ----------------------------------------------------------------------------
// UPGRADE COSTS - All purchasable items and upgrades
// ----------------------------------------------------------------------------
CONFIG.upgradeCosts = {
  // Slime Purchases (Token costs)
  rancherSlime: {
    baseCost: 20,
    costMultiplier: 1.0, // fixed cost
    currency: 'tokens',
    category: 'slime',
  },
  breederSlime: {
    baseCost: 50,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'slime',
  },
  warriorSlime: {
    baseCost: 100,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'slime',
  },

  // Pen Upgrades (Exponential scaling)
  penLevel1: {
    baseCost: 100,
    costMultiplier: 5.0, // to level 2
    currency: 'tokens',
    category: 'pen',
  },
  penLevel2: {
    baseCost: 500,
    costMultiplier: 4.0, // to level 3
    currency: 'tokens',
    category: 'pen',
  },
  penLevel3: {
    baseCost: 2000,
    costMultiplier: 4.0, // to level 4
    currency: 'tokens',
    category: 'pen',
  },
  penLevel4: {
    baseCost: 8000,
    costMultiplier: 4.0, // to level 5
    currency: 'tokens',
    category: 'pen',
  },
  penLevel5: {
    baseCost: 32000,
    costMultiplier: 1.0, // max level
    currency: 'tokens',
    category: 'pen',
  },

  // Evolution Costs (Essence)
  evolveWarrior: {
    baseCost: 50,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'evolution',
    requires: 'rancherSlime',
  },
  evolveElite: {
    baseCost: 200,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'evolution',
    requires: 'warriorSlime',
  },
  crystalPath: {
    baseCost: 100,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'evolution',
  },
  shadowPath: {
    baseCost: 100,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'evolution',
  },

  // Food Items
  basicFood: {
    baseCost: 10,
    costMultiplier: 1.0,
    currency: 'tokens',
    outputCurrency: 'essence',
    outputAmount: 5,
    category: 'consumable',
  },
  crystalFood: {
    baseCost: 100,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'consumable',
  },
  shadowFood: {
    baseCost: 100,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'consumable',
  },

  // Structures
  toyStructure: {
    baseCost: 50,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'structure',
  },
  barrierStructure: {
    baseCost: 150,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'structure',
  },

  // Pen Decorations
  penDecorationBasic: {
    baseCost: 75,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'decoration',
  },
  penDecorationAdvanced: {
    baseCost: 300,
    costMultiplier: 1.0,
    currency: 'tokens',
    category: 'decoration',
  },
  penDecorationCombat: {
    baseCost: 50,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'decoration',
  },

  // Ability Unlocks
  unlockAbility: {
    baseCost: 150,
    costMultiplier: 1.0,
    currency: 'essence',
    category: 'ability',
  },

  // Gene Upgrades (One-time permanent)
  geneFastStart: {
    baseCost: 5,
    costMultiplier: 1.0, // one-time
    currency: 'genes',
    category: 'gene',
    effect: 'startingSlimes + 3',
  },
  genePenDiscount: {
    baseCost: 7,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'penCostMultiplier - 0.2',
  },
  geneTokenBoost: {
    baseCost: 8,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'passiveTokenMultiplier + 0.25',
  },
  geneEssenceDrop: {
    baseCost: 10,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'essenceDropMultiplier + 0.5',
  },
  geneMaxSlimes: {
    baseCost: 10,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'slimeCap + 10',
  },
  geneEvolutionSpeed: {
    baseCost: 12,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'instantEvolution = true',
  },
  geneNewPath: {
    baseCost: 15,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'unlockEvolutionPath',
  },
  geneKingLoot: {
    baseCost: 20,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'bossKingEssence + 2',
  },
  geneStartingElite: {
    baseCost: 25,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'startWithElite = true',
  },
  geneAutoCollect: {
    baseCost: 30,
    costMultiplier: 1.0,
    currency: 'genes',
    category: 'gene',
    effect: 'autoCollectBabies = true',
  },

  // Prestige Unlocks (King Essence costs)
  geneSlot1: {
    baseCost: 1,
    costMultiplier: 2.0, // progressive
    currency: 'kingEssence',
    category: 'prestigeUnlock',
    maxLevel: 10,
  },
  evolutionPathUnlock: {
    baseCost: 3,
    costMultiplier: 1.0,
    currency: 'kingEssence',
    category: 'prestigeUnlock',
  },
};

// ----------------------------------------------------------------------------
// CONVERSIONS - Currency exchange mechanisms
// ----------------------------------------------------------------------------
CONFIG.conversions = {
  tokensToEssence: {
    name: 'Buy Basic Essence Food',
    input: { currency: 'tokens', amount: 10 },
    output: { currency: 'essence', amount: 5 },
    unlockCondition: 'true', // always available
    cooldown: 0, // no cooldown
    instant: true,
    description: 'Purchase essence food from shop',
  },

  kingEssenceToGenes: {
    name: 'Prestige Conversion',
    input: { currency: 'kingEssence', amount: 'all' },
    output: { currency: 'genes', amount: 'calculated' },
    formula: 'inputAmount * 10 * (1 + prestigeCount * 0.1) + bonuses',
    unlockCondition: 'kingEssence >= 1',
    cooldown: 0,
    instant: false, // requires full reset
    requiresPrestige: true,
    description: 'Convert King Essence to Genes (requires prestige reset)',
  },
};

// ----------------------------------------------------------------------------
// PEN BONUSES - Passive token generation by pen level
// ----------------------------------------------------------------------------
CONFIG.penBonuses = {
  0: { tokensPerSec: 0, capacity: 5 },
  1: { tokensPerSec: 1, capacity: 10 },
  2: { tokensPerSec: 3, capacity: 20 },
  3: { tokensPerSec: 10, capacity: 40 },
  4: { tokensPerSec: 25, capacity: 75 },
  5: { tokensPerSec: 50, capacity: 100 },
};

// ----------------------------------------------------------------------------
// ENEMY REWARDS - Essence drops by enemy type
// ----------------------------------------------------------------------------
CONFIG.enemyRewards = {
  corruptedSpider: {
    essence: 2,
    tokens: 0,
    kingEssence: 0,
  },
  shadowWolf: {
    essence: 5,
    tokens: 0,
    kingEssence: 0,
  },
  kingMinion: {
    essence: 3,
    tokens: 0,
    kingEssence: 0,
  },
  slimeKing: {
    essence: 0,
    tokens: 0,
    kingEssence: 3, // base drops
  },
};

// ----------------------------------------------------------------------------
// PRESTIGE CONFIGURATION
// ----------------------------------------------------------------------------
CONFIG.prestige = {
  minimumKingEssence: 5,
  baseConversionRate: 10, // genes per King Essence
  prestigeMultiplier: 0.1, // +10% per previous prestige
  slimeBonus: 5, // genes per 100 slimes
  penBonus: 3, // genes per pen level

  // What resets
  resets: {
    tokens: true,
    essence: true,
    kingEssence: true,
    slimes: true,
    penUpgrades: true,
    structures: true,
    items: true,
  },

  // What persists
  persists: {
    genes: true,
    unlockedPaths: true,
    geneUpgrades: true,
    prestigeCount: true,
  },
};

// ----------------------------------------------------------------------------
// FORMULAS - All calculation formulas for implementation
// ----------------------------------------------------------------------------
CONFIG.formulas = {
  // Token calculations
  totalPassiveTokens: '(breederCount * 0.5 + penBonus) * geneMultiplier',
  waveReward: '50 * waveNumber',
  babyValue: 5,
  firstKillBonus: 10,

  // Essence calculations
  essenceReward: 'baseEnemyReward * (1 + waveNumber * 0.05) * geneDropMultiplier',
  baseEnemyReward: {
    corruptedSpider: 2,
    shadowWolf: 5,
    kingMinion: 3,
  },

  // King Essence calculations
  bossKingEssence: '3 + (geneKingLoot * 2)',

  // Gene calculations
  genesFromPrestige: 'kingEssence * 10 * (1 + prestigeCount * 0.1) + floor(slimeCount / 100 * 5) + penLevels * 3',

  // Upgrade costs
  penCost: 'baseCost * costMultiplier^(level - 1)',

  // Gene multipliers
  geneTokenMultiplier: '1 + (geneTokenBoostLevel * 0.25)',
  geneEssenceMultiplier: '1 + (geneEssenceDropLevel * 0.5)',
  genePenDiscount: '1 - (genePenDiscountLevel * 0.2)',

  // Capacity
  slimeCapacity: '100 + (geneMaxSlimesLevel * 10)',
};

// ----------------------------------------------------------------------------
// BALANCE TARGETS - Expected progression checkpoints
// ----------------------------------------------------------------------------
CONFIG.balanceTargets = {
  '0:30': { tokens: 25, essence: 0, kingEssence: 0, event: 'First wave spawns' },
  '1:00': { tokens: 50, essence: 4, kingEssence: 0, event: 'First breeder purchase' },
  '2:00': { tokens: 150, essence: 20, kingEssence: 0, event: 'Pen level 1 upgrade' },
  '4:00': { tokens: 400, essence: 60, kingEssence: 0, event: 'First warrior purchase' },
  '6:00': { tokens: 800, essence: 120, kingEssence: 0, event: 'First evolution' },
  '8:00': { tokens: 1500, essence: 200, kingEssence: 0, event: 'Pen level 2 upgrade' },
  '10:00': { tokens: 2500, essence: 350, kingEssence: 3, event: 'First boss defeated' },
  '15:00': { tokens: 6000, essence: 900, kingEssence: 3, event: 'Elite evolution' },
  '20:00': { tokens: 12000, essence: 1800, kingEssence: 6, event: 'Second boss' },
  '25:00': { tokens: 25000, essence: 3500, kingEssence: 9, event: 'Pen level 3 upgrade' },
  '30:00': { tokens: 50000, essence: 6000, kingEssence: 12, event: 'Prestige available' },
};
```

---

## 9. Exact Formulas

All formulas are copy-pasteable for implementation:

### Token Formulas
```javascript
// Baby slime collection
const babyValue = 5;

// First kill in wave
const firstKillBonus = 10;

// Wave completion
const waveReward = 50 * waveNumber;

// Passive generation (per second)
const passiveTokens = (breederCount * 0.5 + penBonus) * geneMultiplier;

// Gene multiplier
const geneMultiplier = 1 + (geneTokenBoostLevel * 0.25);

// Pen bonus by level
const penBonus = CONFIG.penBonuses[penLevel].tokensPerSec;
```

### Essence Formulas
```javascript
// Enemy kill reward
const essenceReward = baseEnemyReward * (1 + waveNumber * 0.05) * geneDropMultiplier;

// Gene drop multiplier
const geneDropMultiplier = 1 + (geneEssenceDropLevel * 0.5);

// Base enemy rewards
const baseEnemyReward = {
  corruptedSpider: 2,
  shadowWolf: 5,
  kingMinion: 3,
};

// Shop purchase
const shopEssence = floor(tokens / 10) * 5; // 10 tokens → 5 essence
```

### King Essence Formulas
```javascript
// Boss drops
const bossKingEssence = 3 + (geneKingLootLevel * 2);

// Total per boss fight (3 sprites spawn)
const totalKingEssence = bossKingEssence;
```

### Gene Formulas (Prestige)
```javascript
// Conversion calculation
const genesFromKingEssence = kingEssence * 10 * (1 + prestigeCount * 0.1);
const slimeBonus = floor(slimeCount / 100) * 5;
const penBonus = penLevelsSum * 3;
const totalGenes = genesFromKingEssence + slimeBonus + penBonus;
```

### Upgrade Cost Formulas
```javascript
// Pen upgrade costs (exponential)
const penCost = baseCost * Math.pow(costMultiplier, level - 1);

// Example: Pen level 3
// cost = 100 * 5^2 = 2500 (wait, that's wrong)
// Let me recalculate:
// Level 1: 100
// Level 2: 100 * 5 = 500
// Level 3: 500 * 4 = 2000
// Level 4: 2000 * 4 = 8000
// Level 5: 8000 * 4 = 32000

// Gene discount multiplier
const penCostMultiplier = 1 - (genePenDiscountLevel * 0.2);
const finalPenCost = penCost * penCostMultiplier;

// Slime capacity
const slimeCapacity = 100 + (geneMaxSlimesLevel * 10);
```

### Overflow Protection
```javascript
// Cap enforcement
const tokensSafe = Math.min(tokens, CONFIG.currencies.tokens.cap);
const essenceSafe = Math.min(essence, CONFIG.currencies.essence.cap);
const kingEssenceSafe = Math.min(kingEssence, CONFIG.currencies.kingEssence.cap);

// Genes are uncapped
```

---

## 10. Balance Targets Table

| Time  | Tokens | Essence | King Essence | Key Event                      |
|-------|--------|---------|--------------|--------------------------------|
| 0:30  | 25     | 0       | 0            | First wave spawns              |
| 1:00  | 50     | 4       | 0            | First breeder purchase          |
| 2:00  | 150    | 20      | 0            | Pen level 1 upgrade            |
| 4:00  | 400    | 60      | 0            | First warrior purchase          |
| 6:00  | 800    | 120     | 0            | First evolution (Warrior)      |
| 8:00  | 1500   | 200     | 0            | Pen level 2 upgrade            |
| 10:00 | 2500   | 350     | 3            | First boss defeated            |
| 12:00 | 3500   | 500     | 3            | Elite evolution available      |
| 15:00 | 6000   | 900     | 3            | First elite slime on field     |
| 20:00 | 12000  | 1800    | 6            | Second boss defeated           |
| 25:00 | 25000  | 3500    | 9            | Pen level 3 upgrade            |
| 30:00 | 50000  | 6000    | 12           | Prestige available (5+ KE)     |

---

## 11. Edge Cases

### Overflow Protection
- **Hard caps enforced**: Tokens (999,999), Essence (99,999), King Essence (999)
- **Overflow is lost**: Currency beyond cap disappears (creates spending pressure)
- **Visual warning**: Display "MAX!" when approaching cap (90%+)
- **Genes uncapped**: No overflow concern for prestige currency

### Negative Balance Prevention
- **canAfford() check**: Required before ALL purchases
- **Purchase validation**: Return `false` if insufficient funds
- **UI feedback**: Disable buttons gray out when unaffordable
- **No debt system**: Cannot spend what you don't have

### Hoarding Prevention
- **Token sinks**: Multiple upgrade paths encourage spending
- **Essence pressure**: Evolution is essential for boss progression
- **Prestige urgency**: King Essence has diminishing returns after 5+
- **Hard cap forcing**: Players must spend or lose excess

### Baby Slime Edge Cases
- **Lifetime expires**: Baby escapes at 10s (lost opportunity)
- **Auto-collect gene**: High-tier gene eliminates clicking babies
- **Pen capacity**: Max slime cap prevents infinite breeding
- **Magnet upgrade**: Babies drift toward player when close

### Essence Collection Edge Cases
- **Lifetime expires**: Essence despawns at 8s (lost reward)
- **Off-screen drops**: Essence can spawn outside visible area
- **Magnet upgrade**: High-tier gene auto-collects nearby essence
- **Boss fight urgency**: May miss essence during intense combat

### Prestige Edge Cases
- **Minimum King Essence**: 5+ recommended (but can prestige at 1+)
- **Reset confirmation**: Must confirm to avoid accidental loss
- **Gene calculation errors**: Formula handles edge cases (0 slimes, 0 pens)
- **Prestige regret**: No undo—reset is permanent

### Save/Load Edge Cases
- **Negative values**: Clamp to 0 on load
- **Overflow values**: Clamp to cap on load
- **Invalid currencies**: Reset to default on load
- **Version migration**: Handle config changes between versions

---

## 12. Currency Interconnection Diagram

```mermaid
graph TD
    subgraph "Immediate Feedback Loops"
        T1["Buy Breeder\n-50 Tokens"] -->|"Produces babies"| B1["Baby Collection\n+5 Tokens each"]
        B1 -->|"Faster collection"| T2["More Tokens\nCan buy more breeders"]

        E1["Evolve Warrior\n-50 Essence"] -->|"Stronger combat"| K1["Kill enemies faster\n+2-5 Essence each"]
        K1 -->|"More essence"| E2["Can evolve more slimes"]
    end

    subgraph "Medium-Term Loops"
        P1["Pen Upgrade\n-100-32000 Tokens"] -->|"Housing + passive income"| T3["More token capacity\n+ faster earning"]
        T3 -->|"Afford more"| P2["Higher pen levels\nMore slimes"]

        G1["Gene: Token Boost\n-8 Genes"] -->|"25% more passive"| T4["Accelerated token economy"]
        T4 -->|"Faster progression"| B2["More slimes → More kills → More Essence"]
    end

    subgraph "Long-Term Prestige Loop"
        Boss["Defeat Slime King\n+3 King Essence"] -->|"Accumulate"| KE["5+ King Essence"]
        KE -->|"Prestige reset"| PR["Prestige\nConvert all to Genes"]
        PR -->|"Permanent bonus"| G2["Gene Upgrades\nEverything faster"]
        G2 -->|"Better stats"| Boss2["Kill bosses faster\nMore King Essence"]
    end

    subgraph "Cross-Currency Dependencies"
        Tokens["Slime Tokens"] -->|"Buy food"| Food["Essence Food\n10→5 conversion"]
        Food --> Essence["Essence Pool"]
        Essence -->|"Evolve slimes"| Combat["Stronger Army"]
        Combat -->|"Kill bosses"| King["King Essence"]
        King -->|"Prestige"| Genes["Gene Pool"]
        Genes -->|"Permanent boosts"| All["ALL CURRENCIES MULTIPLIED"]
    end

    style T1 fill:#FFD700
    style E1 fill:#9B59B6
    style Boss fill:#FFA500
    style Genes fill:#2ECC71
```

---

## 13. Player Agency Diagram

```mermaid
flowchart LR
    subgraph "Meaningful Player Choices"
        direction LR
        Q1["Quantity vs Quality\nMany weak slimes\nOR\nFew elite slimes?"]
        Q2["Economy vs Defense\nMore breeders for tokens\nOR\nMore warriors for safety?"]
        Q3["Now or Later\nSpend Essence now\nOR\nSave for Elite evolution?"]
        Q4["Prestige Timing\nPrestige now with 5 KE\nOR\nPush for 10+ KE?"]
        Q5["Gene Prioritization\nWhich gene to unlock first?\nFast Start? Token Boost? Essence Drop?"]
    end

    subgraph "Consequences on Canvas"
        C1["Swarm Strategy\nScreen full of bouncy slimes\nZerg-rush chaos"]
        C2["Elite Strategy\nFewer, larger slimes\nDramatic ability effects"]
        C3["Economy Focus\nConstant baby production\nActive clicking gameplay"]
        C4["Defense Focus\nIntense combat moments\nLess baby management"]
    end

    Q1 --> C1
    Q1 --> C2
    Q2 --> C3
    Q2 --> C4

    style Q1 fill:#FFE5B4
    style Q2 fill:#FFE5B4
    style Q3 fill:#FFE5B4
    style Q4 fill:#FFB4B4
    style Q5 fill:#B4E5FF
```

---

## Design Verification Checklist

- [x] The economy flow diagram shows EVERY currency, source, sink, and conversion
- [x] At least one primary currency (Tokens) has gameplay-earned source (baby collection, enemy kills)
- [x] Gameplay earning events are tied to visible Canvas actions (clicking babies, collecting essence)
- [x] Every formula is exact and copy-pasteable into code
- [x] Conversion rates create meaningful decisions (spend vs. save for prestige)
- [x] The pacing timeline produces the 30-minute target
- [x] Essence is scarce enough to force hard choices (evolution paths)
- [x] The first 30 seconds feel generous (50 starting tokens, first baby at 15s)
- [x] No currency becomes irrelevant (Genes boost all, Essence scales with waves)
- [x] All formulas use consistent variable naming
- [x] The economy forms a web (not a chain) — multiple interconnection loops
- [x] A developer can implement the entire economy from diagrams alone
- [x] Collectible entity state machines define lifecycle for all 4 drop types (baby, essence, king essence, wave reward)
- [x] Currency event flow diagrams show complete chains for all 5 pathways (baby collection, enemy kill, wave complete, boss kill, prestige)
- [x] CONFIG.currencies spec has exact values for all 4 currencies
- [x] CONFIG.collectibles spec defines all 3 collectibles with sprite, scale, lifetime, radius
- [x] CONFIG.currencySources spec defines all 10 earning pathways with formula and base values
- [x] CONFIG.upgradeCosts spec defines all 30+ upgrades with baseCost, costMultiplier, currency
- [x] CONFIG.conversions spec defines all 2 conversions with input/output amounts and unlock conditions

---

## Summary: Design Philosophy

This currency system is built around **active Canvas gameplay** as the primary earning mechanism:

1. **Tokens** flow from clicking baby slimes (primary) and passive breeders (secondary). The 10-second escape timer creates urgency and attention.

2. **Essence** is EXCLUSIVELY earned from combat — killing enemies drops sprites on Canvas that must be clicked. No passive generation means players must fight to progress.

3. **King Essence** is the rare boss reward, dropping 3 collectible sprites per boss. The visual spectacle (screen flash, particles) makes these moments memorable.

4. **Genes** are the permanent progression currency, earned only through prestige. Each gene creates a visible gameplay change (more starting slimes, faster collection, better drops).

The **inflation controls** are multi-layered:
- Hard caps prevent infinite hoarding
- Exponential pen costs create natural progression walls
- Prestige resets force strategic decisions about when to convert
- Gene upgrades accelerate subsequent runs

The **"almost enough" feeling** is achieved through:
- First upgrade affordable in 10 seconds (50 tokens, breeder costs 50)
- Essence rewards always 2-3 kills away from next evolution
- King Essence always "one more boss" from prestige goal
- Gene costs create long-term aspiration (5-30 genes each)

Most importantly, **every currency is tied to Canvas gameplay** — clicking babies, collecting essence, positioning slimes, timing abilities. The player EARNS everything through active play, not just waiting for timers.

Prestige

{
  "gameTitle": "Slime Rancher Defense - Prestige System Design",
  "version": "1.0",
  "lastUpdated": "2025-02-07",
  "summary": "Complete prestige/reset system with visual world transformations. Players convert King Essence to Genes, permanently upgrading their ranch while the Canvas world shifts to harder, more dangerous biomes with each prestige tier.",
  "prestigeCycle": {
    "diagram": "mermaid",
    "definition": "stateDiagram-v2\n    [*] --> Run1: Game Start\n\n    state \"Run 1 (No Bonuses)\" as Run1 {\n        [*] --> EarlyGame1: 0-5 min\n        EarlyGame1: 2 Rancher + 1 Breeder slimes\n        note right of EarlyGame1\n            Basic pen (capacity: 5)\n            Normal enemies\n            Bright forest background\n        end note\n        EarlyGame1 --> MidGame1: Wave 3-7\n        MidGame1: Evolution unlocks\n        MidGame1 --> LateGame1: Wave 8-10\n        LateGame1: Slime King boss fight\n        LateGame1 --> PrestigeReady1: Wave 15+ complete\n        PrestigeReady1: 5+ King Essence\n    }\n\n    state \"Prestige Decision\" as Decision {\n        [*] --> Preview\n        Preview: Prestige button glows\n        Preview: Shows genes calculation\n        Preview: Visual preview of new world\n        Preview: \"World will become HARDER\"\n        Preview --> Confirm: Player clicks Prestige\n        Preview --> Wait: Keep playing\n        Wait --> Preview: Check again later\n    }\n\n    state \"Run 2 (With Bonuses + Corrupted Forest)\" as Run2 {\n        [*] --> EarlyGame2: 0-3 min (2x faster!)\n        note right of EarlyGame2\n            Gene bonuses active\n            Corrupted forest background (red-shifted)\n            Enemies: Red palette variant\n            ProceduralSprite.generateColorVariant\n            Slimes have subtle auras\n        end note\n        EarlyGame2 --> MidGame2: Wave 5-10\n        MidGame2: Multipliers active\n        MidGame2 --> LateGame2: Wave 12-15\n        LateGame2: Elite evolution faster\n        LateGame2 --> PrestigeReady2: Wave 20+\n    }\n\n    state \"Run 3 (More Genes + Dark Swamp)\" as Run3 {\n        [*] --> EarlyGame3: 0-2 min (3x faster!)\n        note right of EarlyGame3\n            More gene bonuses\n            Dark swamp background (purple/green)\n            Enemies: Purple + geometric variants\n            New enemy: Corrupted Slime\n            ProceduralSprite.generateSimpleSprite\n            Elite enemies have glow effects\n        end note\n        EarlyGame3 --> MidGame3\n        MidGame3 --> LateGame3\n        LateGame3 --> PrestigeReady3\n    }\n\n    state \"Run 4+ (Gene Mastery + Shadow Realm)\" as Run4 {\n        [*] --> EarlyGame4: 0-1 min (5x faster!)\n        note right of EarlyGame4\n            Max gene upgrades\n            Shadow realm background (dark gray/red)\n            Enemies: Gold palette + shadow variants\n            New enemy: Shadow Stalker\n            All enemies have death effects\n            Slimes have permanent glow\n        end note\n        EarlyGame4 --> MidGame4\n        MidGame4 --> LateGame4\n        LateGame4 --> AscensionReady\n    }\n\n    Run1 --> Decision: King Essence >= 5\n    Decision --> Run2: Prestige confirmed\n    Run2 --> Decision: King Essence >= 5\n    Run3 --> Decision: King Essence >= 5\n    Run4 --> Ascension: Max prestige reached",
    "description": "The complete prestige loop showing how each run transforms visually while becoming faster due to gene bonuses. Players SEE the world change colors and difficulty after each prestige."
  },
  "resetSpecification": {
    "diagram": "mermaid",
    "definition": "graph TD\n    subgraph \"🔴 RESETS (back to zero)\"\n        R1[\"Slime Tokens → 0 (start with gene bonus)\"]\n        R2[\"Essence → 0\"]\n        R3[\"King Essence → 0\"]\n        R4[\"All slimes despawned from Canvas\"]\n        R5[\"Pen upgrades → Level 0 (or gene-modified)\"]\n        R6[\"All structures → Removed\"]\n        R7[\"All evolution progress → Reset\"]\n        R8[\"Wave counter → Wave 1\"]\n        R9[\"All food items → Cleared\"]\n        R10[\"All collectibles → Despawned\"]\n    end\n\n    subgraph \"🟢 PERSISTS (kept forever)\"\n        P1[\"Genes (prestige currency)\"]\n        P2[\"Purchased gene upgrades\"]\n        P3[\"Prestige count (tier level)\"]\n        P4[\"Lifetime statistics\"]\n        P5[\"Unlocked evolution paths\"]\n        P6[\"Achievements earned\"]\n        P7[\"Tutorial flags (don't re-show)\"]\n    end\n\n    subgraph \"🟡 CHANGES (visual transformation)\"\n        V1[\"Canvas background shifts biome\"]\n        V2[\"Enemy sprites get new color palette\"]\n        V3[\"New enemy types may appear\"]\n        V4[\"Slimes gain gene aura effects\"]\n        V5[\"Death effects enhance\"]\n        V6[\"Ranch house visual upgrade\"]\n    end\n\n    subgraph \"🔵 GENE BONUSES (apply after reset)\"\n        G1[\"Starting Slimes: +3 per Fast Start gene\"]\n        G2[\"Starting Tokens: +25 per Token Boost gene\"]\n        G3[\"Passive Token Rate: +25% per Token Boost gene\"]\n        G4[\"Essence Drops: +50% per Essence Drop gene\"]\n        G5[\"Pen Costs: -20% per Pen Discount gene\"]\n        G6[\"Evolution: Instant if gene owned\"]\n        G7[\"Start with Elite if gene owned\"]\n        G8[\"King Essence: +2 per boss if gene owned\"]\n    end",
    "description": "Exactly what resets, what persists, and what changes visually. The visual transformation section ensures players immediately see they've entered a new prestige tier."
  },
  "prestigeUpgradeTree": {
    "diagram": "mermaid",
    "definition": "graph TD\n    subgraph \"Tier 1 Gene Upgrades (1-10 Genes each)\"\n        GU1[\"🧬 Fast Start\\nCost: 5 Genes\\nEffect: Start with +3 slimes\\nVisible: More slimes on Canvas immediately\"]\n        GU2[\"🧬 Pen Discount\\nCost: 7 Genes\\nEffect: -20% pen upgrade costs\\nVisible: Cheaper pen expansion\"]\n        GU3[\"🧬 Token Boost\\nCost: 8 Genes\\nEffect: +25% passive tokens\\nVisible: Faster counter ticking\"]\n        GU4[\"🧬 NEW: Baby Magnet\\nCost: 10 Genes\\nEffect: Auto-collect babies\\nVisible: Babies drift to cursor\"]\n    end\n\n    subgraph \"Tier 2 Gene Upgrades (10-20 Genes each)\"\n        GU5[\"🧬 Essence Drop\\nCost: 10 Genes\\nEffect: +50% essence from enemies\\nVisible: Bigger essence numbers\"]\n        GU6[\"🧬 Max Slimes\\nCost: 10 Genes\\nEffect: +10 slime capacity\\nVisible: Can hold more slimes\"]\n        GU7[\"🧬 Evolution Speed\\nCost: 12 Genes\\nEffect: Instant evolution\\nVisible: No evolution delay\"]\n        GU8[\"🧬 King Loot\\nCost: 20 Genes\\nEffect: +2 King Essence per boss\\nVisible: More crowns drop\"]\n    end\n\n    subgraph \"Tier 3 Gene Upgrades (15-30 Genes each)\"\n        GU9[\"🧬 NEW: Crystal Path\\nCost: 15 Genes\\nEffect: Unlock Crystal evolution\\nVisible: Cyan slimes with ranged attacks\"]\n        GU10[\"🧬 NEW: Shadow Path\\nCost: 15 Genes\\nEffect: Unlock Shadow evolution\\nVisible: Dark slimes with melee boost\"]\n        GU11[\"🧬 Starting Elite\\nCost: 25 Genes\\nEffect: Start with 1 Elite slime\\nVisible: Golden slime from wave 1\"]\n        GU12[\"🧬 Auto-Collect\\nCost: 30 Genes\\nEffect: Auto-collect all drops\\nVisible: Everything flies to counter\"]\n    end\n\n    subgraph \"Tier 4 Master Genes (30+ Genes each)\"\n        GU13[\"🧬 NEW: Gene Mastery\\nCost: 50 Genes\\nEffect: All gene effects +25%\\nVisible: All bonuses boosted\"]\n        GU14[\"🧬 NEW: Slime Aura\\nCost: 40 Genes\\nEffect: All slimes have glow aura\\nVisible: Beautiful particle effects\"]\n        GU15[\"🧬 Ascension\\nCost: 100 Genes\\nEffect: Unlock Ascension prestige layer\\nVisible: Entirely new game mode\"]\n    end\n\n    GU1 --> GU5\n    GU2 --> GU6\n    GU3 --> GU5\n    GU4 --> GU7\n    GU5 --> GU9\n    GU5 --> GU10\n    GU6 --> GU11\n    GU7 --> GU11\n    GU8 --> GU12\n    GU9 --> GU13\n    GU10 --> GU14\n    GU11 --> GU14\n    GU12 --> GU15\n    GU13 --> GU15\n    GU14 --> GU15",
    "description": "Complete gene upgrade tree. 'NEW:' prefixes indicate upgrades that unlock entirely new mechanics or visual elements. Gene bonuses make each run significantly faster.",
    "upgrades": [
      {
        "id": "fastStart",
        "name": "Fast Start",
        "cost": 5,
        "tier": 1,
        "effect": "startingSlimes + 3",
        "visualImpact": "More slimes visible on Canvas immediately after reset"
      },
      {
        "id": "penDiscount",
        "name": "Pen Discount",
        "cost": 7,
        "tier": 1,
        "effect": "penCostMultiplier * 0.8",
        "visualImpact": "Pen expansion cheaper, visible faster"
      },
      {
        "id": "tokenBoost",
        "name": "Token Boost",
        "cost": 8,
        "tier": 1,
        "effect": "passiveTokenMultiplier + 0.25",
        "visualImpact": "Token counter ticks up faster"
      },
      {
        "id": "babyMagnet",
        "name": "Baby Magnet",
        "cost": 10,
        "tier": 1,
        "effect": "autoCollectBabies = true",
        "visualImpact": "Babies drift toward player cursor automatically",
        "isNew": true
      },
      {
        "id": "essenceDrop",
        "name": "Essence Drop",
        "cost": 10,
        "tier": 2,
        "effect": "essenceDropMultiplier + 0.5",
        "visualImpact": "Larger essence numbers on collection"
      },
      {
        "id": "maxSlimes",
        "name": "Max Slimes",
        "cost": 10,
        "tier": 2,
        "effect": "slimeCap + 10",
        "visualImpact": "Can hold more slimes on Canvas"
      },
      {
        "id": "evolutionSpeed",
        "name": "Evolution Speed",
        "cost": 12,
        "tier": 2,
        "effect": "instantEvolution = true",
        "visualImpact": "Evolution happens immediately, no delay"
      },
      {
        "id": "kingLoot",
        "name": "King Loot",
        "cost": 20,
        "tier": 2,
        "effect": "bossKingEssence + 2",
        "visualImpact": "Bosses drop more King Essence sprites"
      },
      {
        "id": "crystalPath",
        "name": "Crystal Path",
        "cost": 15,
        "tier": 3,
        "effect": "unlockEvolutionPath('crystal')",
        "visualImpact": "Crystal slimes with cyan glow and ranged projectiles",
        "isNew": true
      },
      {
        "id": "shadowPath",
        "name": "Shadow Path",
        "cost": 15,
        "tier": 3,
        "effect": "unlockEvolutionPath('shadow')",
        "visualImpact": "Shadow slimes with dark aura and melee boost",
        "isNew": true
      },
      {
        "id": "startingElite",
        "name": "Starting Elite",
        "cost": 25,
        "tier": 3,
        "effect": "startWithElite = true",
        "visualImpact": "Elite slime with golden aura from wave 1"
      },
      {
        "id": "autoCollect",
        "name": "Auto-Collect",
        "cost": 30,
        "tier": 3,
        "effect": "autoCollectAll = true",
        "visualImpact": "Essence and babies fly to counter automatically"
      },
      {
        "id": "geneMastery",
        "name": "Gene Mastery",
        "cost": 50,
        "tier": 4,
        "effect": "allGeneEffects * 1.25",
        "visualImpact": "All bonuses visibly boosted",
        "isNew": true
      },
      {
        "id": "slimeAura",
        "name": "Slime Aura",
        "cost": 40,
        "tier": 4,
        "effect": "allSlimesGlow = true",
        "visualImpact": "All slimes have beautiful particle glow effects",
        "isNew": true
      },
      {
        "id": "ascension",
        "name": "Ascension",
        "cost": 100,
        "tier": 4,
        "effect": "unlockAscensionLayer = true",
        "visualImpact": "Unlocks entirely new prestige layer with new mechanics",
        "isNew": true
      }
    ]
  },
  "runComparison": {
    "diagram": "mermaid",
    "definition": "sequenceDiagram\n    participant R1 as Run 1 (no genes)\n    participant R2 as Run 2 (50 genes spent)\n    participant R3 as Run 3 (150 genes total)\n    participant R4 as Run 4 (300 genes total)\n\n    Note over R1: 0:00 - Start: 3 slimes, 50 tokens, basic pen\n    Note over R2: 0:00 - Start: 6 slimes, 75 tokens, red-shifted world\n    Note over R3: 0:00 - Start: 9 slimes, 100 tokens, purple swamp\n    Note over R4: 0:00 - Start: 15 slimes, 150 tokens, shadow realm\n\n    Note over R1: 1:00 - Wave 1 complete, Shop unlock\n    Note over R2: 0:20 - Wave 1 complete (3x faster)\n    Note over R3: 0:10 - Wave 1 complete (6x faster)\n    Note over R4: 0:05 - Wave 1 complete (12x faster)\n\n    Note over R1: 7:00 - First evolution (need 50 essence)\n    Note over R2: 2:00 - First evolution (instant evo gene)\n    Note over R3: 0:45 - First evolution + elite start\n    Note over R4: 0:20 - Multiple evolutions immediately\n\n    Note over R1: 17:00 - First boss defeated\n    Note over R2: 6:00 - First boss defeated (2.8x faster)\n    Note over R3: 3:00 - First boss defeated (5.7x faster)\n    Note over R4: 1:30 - First boss defeated (11x faster)\n\n    Note over R1: 30:00 - Prestige ready (5 King Essence)\n    Note over R2: 12:00 - Prestige ready (2.5x faster)\n    Note over R3: 6:00 - Prestige ready (5x faster)\n    Note over R4: 3:00 - Prestige ready (10x faster)",
    "description": "Run comparison showing how gene bonuses accelerate each subsequent prestige. Run 2 reaches Run 1's 30-minute mark in just 12 minutes (2.5x faster). Run 4 is 10x faster than Run 1.",
    "speedMultiplier": {
      "run1": 1,
      "run2": 2.5,
      "run3": 5,
      "run4": 10,
      "note": "Each prestige with genes spent makes the game dramatically faster, creating the power fantasy feeling."
    }
  },
  "visualTransformationSpec": {
    "diagram": "mermaid",
    "definition": "graph TD\n    subgraph \"Tier 0: First Run (Bright Forest)\"\n        T0_bg[\"Canvas Background: #87CEEB (Sky Blue) gradient to #90EE90 (Light Green)\"]\n        T0_ranch[\"Ranch House: Thatch roof, wooden walls (basic sprite)\"]\n        T0_enemies[\"Enemies: Default sprite palettes\\n- Corrupted Spider: Dark purple\\n- Shadow Wolf: Black ghost\"]\n        T0_slimes[\"Slimes: No auras, basic bounce\"]\n        T0_effects[\"Death Effects: Simple spark particles\"]\n    end\n\n    subgraph \"Tier 1: Prestige 1-2 (Corrupted Forest)\"\n        T1_bg[\"Canvas Background: #CD5C5C (Indian Red) gradient to #8B4513 (Saddle Brown)\"]\n        T1_ranch[\"Ranch House: Stone walls, upgraded roof (visible upgrade)\"]\n        T1_enemies[\"Enemies: Red-shifted palette variant\\n- ProceduralSprite.generateColorVariant(hueShift: 30)\\n- Spiders: Dark red\\n- Wolves: Dark red tint\"]\n        T1_slimes[\"Slimes: Subtle gene aura (faint glow)\"]\n        T1_effects[\"Death Effects: Spark + small screen flash\"]\n        T1_new[\"NEW: Trees look corrupted (darker colors)\"]\n    end\n\n    subgraph \"Tier 2: Prestige 3-5 (Dark Swamp)\"\n        T2_bg[\"Canvas Background: #4B0082 (Indigo) gradient to #2E8B57 (Sea Green)\"]\n        T2_ranch[\"Ranch House: Stone castle with flags (fortress look)\"]\n        T2_enemies[\"Enemies: Purple/dark palette + geometric variants\\n- ProceduralSprite.generateColorVariant(hueShift: 120, saturation: 1.5)\\n- Corrupted Slime enemy added\\n- ProceduralSprite.generateSimpleSprite(shape: 'slime')\"]\n        T2_slimes[\"Slimes: Stronger gene aura (visible glow)\"]\n        T2_effects[\"Death Effects: Enhanced animations, glow on elites\"]\n        T2_new[\"NEW: Swamp water visible on Canvas\\nNEW: Fireflies at night\"]\n    end\n\n    subgraph \"Tier 3: Prestige 6+ (Shadow Realm)\"\n        T3_bg[\"Canvas Background: #1A1A1A (Dark Gray) gradient to #8B0000 (Dark Red)\"]\n        T3_ranch[\"Ranch House: Crystal fortress with towers (max upgrade)\"]\n        T3_enemies[\"Enemies: Gold/elite palette + shadow variants\\n- ProceduralSprite.generateColorVariant(hueShift: 180, saturation: 2.0)\\n- Shadow Stalker enemy added\\n- All enemies have glow effects\"]\n        T3_slimes[\"Slimes: Permanent strong glow (Slime Aura gene)\"]\n        T3_effects[\"Death Effects: Massive particle explosions\"]\n        T3_new[\"NEW: Dark particles floating in air\\nNEW: Ground cracks visible\\nNEW: Dramatic lighting effects\"]\n    end",
    "description": "Detailed visual transformation for each prestige tier. The Canvas should look NOTICEABLY different after each prestige—different colors, new environment elements, harder-looking enemies.",
    "tiers": [
      {
        "tier": 0,
        "prestigeCount": "0 (first run)",
        "name": "Bright Forest",
        "background": "Linear gradient from #87CEEB (sky blue) to #90EE90 (light green)",
        "ranchHouse": "Thatch roof, wooden walls",
        "enemyPalette": "Default sprite colors",
        "enemyVariants": [
          "Corrupted Spider",
          "Shadow Wolf"
        ],
        "slimeAura": "None",
        "deathEffects": "Basic spark particles",
        "environmentElements": [
          "Green grass",
          "Blue sky",
          "Simple trees"
        ]
      },
      {
        "tier": 1,
        "prestigeCount": "1-2",
        "name": "Corrupted Forest",
        "background": "Linear gradient from #CD5C5C (Indian red) to #8B4513 (saddle brown)",
        "ranchHouse": "Stone walls, upgraded roof (visible change)",
        "enemyPalette": "ProceduralSprite.generateColorVariant with hueShift: 30, saturation: 1.2",
        "enemyVariants": [
          "Red-shifted Corrupted Spider",
          "Red-shifted Shadow Wolf"
        ],
        "slimeAura": "Faint gene glow (subtle particle effect)",
        "deathEffects": "Spark + small screen flash on kill",
        "environmentElements": [
          "Corrupted trees (darker, twisted)",
          "Red-tinted grass",
          "Darker sky"
        ]
      },
      {
        "tier": 2,
        "prestigeCount": "3-5",
        "name": "Dark Swamp",
        "background": "Linear gradient from #4B0082 (indigo) to #2E8B57 (sea green)",
        "ranchHouse": "Stone castle with flags (fortress appearance)",
        "enemyPalette": "ProceduralSprite.generateColorVariant with hueShift: 120, saturation: 1.5",
        "enemyVariants": [
          "Purple Corrupted Spider",
          "Purple Shadow Wolf",
          "NEW: Corrupted Slime (geometric variant via ProceduralSprite.generateSimpleSprite)"
        ],
        "slimeAura": "Strong gene glow (visible particle effect)",
        "deathEffects": "Enhanced animations with glow on elite kills",
        "environmentElements": [
          "Swamp water patches on Canvas",
          "Fireflies at night (particle effect)",
          "Dead trees",
          "Moss ground"
        ]
      },
      {
        "tier": 3,
        "prestigeCount": "6+",
        "name": "Shadow Realm",
        "background": "Linear gradient from #1A1A1A (dark gray) to #8B0000 (dark red)",
        "ranchHouse": "Crystal fortress with towers (max upgrade, dramatic visual)",
        "enemyPalette": "ProceduralSprite.generateColorVariant with hueShift: 180, saturation: 2.0",
        "enemyVariants": [
          "Gold/elite palette enemies",
          "NEW: Shadow Stalker (dangerous new enemy)",
          "All enemies have glow effects"
        ],
        "slimeAura": "Permanent strong glow (Slime Aura gene always active)",
        "deathEffects": "Massive particle explosions on all kills",
        "environmentElements": [
          "Dark particles floating in air",
          "Ground cracks visible",
          "Dramatic red lighting",
          "Crystal formations"
        ]
      }
    ]
  },
  "prestigeUIFlow": {
    "diagram": "mermaid",
    "definition": "sequenceDiagram\n    actor Player\n    participant Canvas as Game Canvas\n    participant UI as Game UI\n    participant Button as Prestige Button\n\n    Note over Player,Button: Boss Defeated - King Essence Collected\n    UI->>Player: King Essence counter: 3/5\n    \n    Note over Player,Button: Second Boss - Another 3 King Essence\n    UI->>Player: King Essence counter: 6/5\n    Button->>Player: Prestige button glows gold\n    Button->>Player: Shows \"PRESTIGE AVAILABLE!\"\n    Button->>Player: Hover preview: \"Earn ~60 Genes\"\n\n    Player->>Button: clicks Prestige button\n    UI->>Player: Confirmation panel slides in\n    Note over UI: Panel shows:\n    Note over UI: - King Essence: 6\n    Note over UI: - Genes earned: ~60\n    Note over UI: - Gene bonus: +10% (1st prestige)\n    Note over UI: - Visual preview: \"Corrupted Forest\"\n    Note over UI: - What resets / what persists\n\n    alt Player confirms\n        Player->>UI: clicks \"PRESTIGE NOW\"\n        Canvas->>Canvas: fade to white transition (500ms)\n        Note over Canvas: During fade:\n        Note over Canvas: - Reset all currencies\n        Note over Canvas: - Despawn all entities\n        Note over Canvas: - Calculate Genes\n        Note over Canvas: - Apply visual tier\n        Canvas->>Canvas: new world fades in (500ms)\n        Note over Canvas: Player sees:\n        Note over Canvas: - Red-shifted background\n        Note over Canvas: - Gene shop opens\n        Canvas->>Player: Fresh game with new visuals\n        UI->>Player: showPrestigeSummary(\"+60 Genes!\")\n        UI->>Player: Gene shop visible\n        Player->>UI: buy gene upgrades\n        Canvas->>Player: New run begins with bonuses active\n    else Player cancels\n        Player->>UI: clicks \"Keep Playing\"\n        UI->>Player: panel closes\n        Button->>Player: button continues glowing\n        Player->>Canvas: continue current run\n    end",
    "description": "Complete UI flow from prestige button appearance through confirmation to the visual transformation. The fade transition makes the world change feel dramatic.",
    "panels": {
      "confirmation": {
        "title": "PRESTIGE - Transcend to a New World",
        "sections": [
          {
            "label": "Current Run",
            "items": [
              {
                "key": "King Essence",
                "value": "{kingEssence}",
                "icon": "👑"
              },
              {
                "key": "Slimes Owned",
                "value": "{slimeCount}",
                "icon": "💧"
              },
              {
                "key": "Pen Level",
                "value": "{penLevel}",
                "icon": "🏠"
              }
            ]
          },
          {
            "label": "Prestige Rewards",
            "items": [
              {
                "key": "Base Genes",
                "value": "{kingEssence * 10}",
                "icon": "🧬"
              },
              {
                "key": "Prestige Bonus",
                "value": "+{prestigeCount * 10}%",
                "icon": "📈"
              },
              {
                "key": "Slime Bonus",
                "value": "+{floor(slimeCount/100*5)}",
                "icon": "💧"
              },
              {
                "key": "Pen Bonus",
                "value": "+{penLevels * 3}",
                "icon": "🏠"
              },
              {
                "key": "TOTAL GENES",
                "value": "{totalGenes}",
                "icon": "🧬",
                "highlight": true
              }
            ]
          },
          {
            "label": "What Happens",
            "items": [
              {
                "key": "RESETS",
                "value": "All slimes, tokens, essence, pens",
                "color": "red"
              },
              {
                "key": "KEEPS",
                "value": "Genes, gene upgrades, achievements",
                "color": "green"
              },
              {
                "key": "NEW WORLD",
                "value": "Corrupted Forest (harder enemies)",
                "color": "gold"
              }
            ]
          },
          {
            "label": "Gene Shop Preview",
            "items": [
              {
                "key": "Fast Start",
                "value": "5 Genes - +3 starting slimes",
                "affordable": "{totalGenes >= 5}"
              },
              {
                "key": "Pen Discount",
                "value": "7 Genes - -20% pen costs",
                "affordable": "{totalGenes >= 7}"
              },
              {
                "key": "Token Boost",
                "value": "8 Genes - +25% passive",
                "affordable": "{totalGenes >= 8}"
              }
            ]
          }
        ],
        "buttons": [
          {
            "label": "PRESTIGE NOW",
            "action": "confirm",
            "primary": true,
            "color": "gold"
          },
          {
            "label": "Keep Playing",
            "action": "cancel",
            "primary": false
          }
        ]
      },
      "geneShop": {
        "title": "GENE LAB - Permanent Upgrades",
        "currency": {
          "icon": "🧬",
          "name": "Genes",
          "value": "{geneCount}"
        },
        "tiers": [
          {
            "name": "Tier 1",
            "upgrades": [
              {
                "id": "fastStart",
                "name": "Fast Start",
                "cost": 5,
                "description": "+3 starting slimes",
                "icon": "💧"
              },
              {
                "id": "penDiscount",
                "name": "Pen Discount",
                "cost": 7,
                "description": "-20% pen costs",
                "icon": "🏠"
              },
              {
                "id": "tokenBoost",
                "name": "Token Boost",
                "cost": 8,
                "description": "+25% passive tokens",
                "icon": "🪙"
              },
              {
                "id": "babyMagnet",
                "name": "Baby Magnet",
                "cost": 10,
                "description": "Auto-collect babies",
                "icon": "🧲",
                "new": true
              }
            ]
          },
          {
            "name": "Tier 2",
            "upgrades": [
              {
                "id": "essenceDrop",
                "name": "Essence Drop",
                "cost": 10,
                "description": "+50% essence drops",
                "icon": "💜"
              },
              {
                "id": "maxSlimes",
                "name": "Max Slimes",
                "cost": 10,
                "description": "+10 slime capacity",
                "icon": "💧"
              },
              {
                "id": "evolutionSpeed",
                "name": "Instant Evolution",
                "cost": 12,
                "description": "No evolution delay",
                "icon": "⚡"
              },
              {
                "id": "kingLoot",
                "name": "King Loot",
                "cost": 20,
                "description": "+2 King Essence/boss",
                "icon": "👑"
              }
            ]
          },
          {
            "name": "Tier 3",
            "upgrades": [
              {
                "id": "crystalPath",
                "name": "Crystal Path",
                "cost": 15,
                "description": "Unlock Crystal evolution",
                "icon": "💎",
                "new": true
              },
              {
                "id": "shadowPath",
                "name": "Shadow Path",
                "cost": 15,
                "description": "Unlock Shadow evolution",
                "icon": "🌑",
                "new": true
              },
              {
                "id": "startingElite",
                "name": "Starting Elite",
                "cost": 25,
                "description": "Start with 1 Elite",
                "icon": "⭐"
              },
              {
                "id": "autoCollect",
                "name": "Auto-Collect",
                "cost": 30,
                "description": "Auto-collect all drops",
                "icon": "🧲"
              }
            ]
          }
        ],
        "buttons": [
          {
            "label": "START NEW RUN",
            "action": "startRun",
            "primary": true
          }
        ]
      }
    }
  },
  "prestigeStateMachine": {
    "diagram": "mermaid",
    "definition": "stateDiagram-v2\n    [*] --> Unavailable: game start\n    Unavailable --> Teased: wave >= 10\\n(first boss possible)\n    Teased --> Available: kingEssence >= 5\n    Available --> PreviewOpen: player clicks prestige button\n    PreviewOpen --> Confirmed: player clicks \"PRESTIGE NOW\"\n    PreviewOpen --> Available: player clicks \"Keep Playing\"\n    Confirmed --> Transitioning: begin reset sequence\n    Transitioning --> GeneShop: show gene upgrade panel\n    GeneShop --> NewRun: player clicks \"START NEW RUN\"\n    NewRun --> Unavailable: new run begins\\n(prestigeCount incremented)\n\n    state Transitioning {\n        [*] --> Calculate: calculate gene yield\n        Calculate --> SavePrestige: save gene currency + upgrades\n        SavePrestige --> ResetCurrencies: zero tokens/essence/kingEssence\n        ResetCurrencies --> ResetEntities: despawn all canvas entities\n        ResetEntities --> ResetProgression: relock non-permanent unlocks\n        ResetProgression --> ApplyVisuals: set new visual tier\n        ApplyVisuals --> FadeOut: canvas fade to white (500ms)\n        FadeOut --> FadeIn: new world fades in (500ms)\n        FadeIn --> [*]\n    }\n\n    note right of Teased\n        Prestige button visible but grayed\n        Shows \"5 King Essence to Prestige\"\n        Current: {kingEssence}/5\n        Projected genes shown\n        Teases visual transformation\n    end note\n\n    note right of Available\n        Prestige button glows/pulses gold\n        Shows \"PRESTIGE for ~{genes} Genes!\"\n        Updated every king essence collected\n        Visual preview of next tier\n    end note\n\n    note right of Transitioning\n        Dramatic moment!\n        White fade creates sense of\n        entering a new dimension\n        Player feels powerful\n    end note",
    "description": "Complete prestige lifecycle from button appearance (teased at wave 10) through the transition state machine to the new run. The fade transition is the key moment where players feel the transformation.",
    "states": {
      "unavailable": {
        "name": "Unavailable",
        "condition": "kingEssence < 5 OR wave < 10",
        "button": "Hidden",
        "visual": "No indication"
      },
      "teased": {
        "name": "Teased",
        "condition": "wave >= 10 AND kingEssence < 5",
        "button": "Visible but grayed out",
        "visual": "Shows '{kingEssence}/5 King Essence', projected genes",
        "tooltip": "Collect 5 King Essence to Prestige"
      },
      "available": {
        "name": "Available",
        "condition": "kingEssence >= 5",
        "button": "Glowing gold, pulsing animation",
        "visual": "Shows 'PRESTIGE for ~{genes} Genes!'",
        "tooltip": "Click to transcend to a new world"
      },
      "previewOpen": {
        "name": "Preview Open",
        "condition": "Player clicked prestige button",
        "ui": "Confirmation panel showing rewards and changes",
        "actions": [
          "Confirm",
          "Cancel"
        ]
      },
      "confirmed": {
        "name": "Confirmed",
        "condition": "Player clicked 'PRESTIGE NOW'",
        "action": "Begin reset sequence"
      },
      "transitioning": {
        "name": "Transitioning",
        "duration": "1000ms (500ms fade out + 500ms fade in)",
        "substates": [
          "Calculate",
          "Save",
          "Reset Currencies",
          "Reset Entities",
          "Reset Progression",
          "Apply Visuals",
          "Fade Out",
          "Fade In"
        ],
        "visual": "Canvas fades to white, new world fades in"
      },
      "geneShop": {
        "name": "Gene Shop",
        "condition": "Transition complete",
        "ui": "Gene upgrade panel visible",
        "actions": [
          "Purchase upgrades",
          "Start new run"
        ]
      },
      "newRun": {
        "name": "New Run",
        "condition": "Player clicked 'START NEW RUN'",
        "changes": [
          "prestigeCount incremented",
          "Visual tier applied",
          "Gene bonuses active"
        ],
        "next": "Unavailable (cycle repeats)"
      }
    }
  },
  "prestigeFormula": {
    "formula": "genes = floor(kingEssence * baseRate * (1 + prestigeCount * 0.1)) + floor(slimeCount / 100 * 5) + penLevels * 3",
    "parameters": {
      "baseRate": 10,
      "prestigeMultiplier": 0.1,
      "slimeBonusDivisor": 100,
      "slimeBonusAmount": 5,
      "penBonusAmount": 3
    },
    "examples": [
      {
        "run": 1,
        "kingEssence": 5,
        "slimeCount": 20,
        "penLevels": 2,
        "prestigeCount": 0,
        "calculation": "floor(5 * 10 * 1.0) + floor(20/100*5) + 2*3 = 50 + 0 + 6 = 56"
      },
      {
        "run": 2,
        "kingEssence": 8,
        "slimeCount": 35,
        "penLevels": 3,
        "prestigeCount": 1,
        "calculation": "floor(8 * 10 * 1.1) + floor(35/100*5) + 3*3 = 88 + 1 + 9 = 98"
      },
      {
        "run": 3,
        "kingEssence": 12,
        "slimeCount": 50,
        "penLevels": 4,
        "prestigeCount": 2,
        "calculation": "floor(12 * 10 * 1.2) + floor(50/100*5) + 4*3 = 144 + 2 + 12 = 158"
      }
    ],
    "diminishingReturns": {
      "description": "The square-root-like relationship (linear base with multiplicative prestige bonus) creates diminishing returns - pushing further gives more genes but with increasingly marginal value compared to time spent.",
      "example": "Going from 5 to 10 King Essence doubles the input, but because of time pressure and difficulty scaling, it's often better to prestige earlier and let gene bonuses accelerate the next run."
    }
  },
  "config": {
    "prestige": {
      "teaserWave": 10,
      "minWave": 10,
      "minKingEssence": 5,
      "formula": "floor(kingEssence * 10 * (1 + prestigeCount * 0.1)) + floor(slimeCount / 100 * 5) + penLevels * 3",
      "resets": [
        "currencies.tokens",
        "currencies.essence",
        "currencies.kingEssence",
        "slimes",
        "penUpgrades",
        "structures",
        "items",
        "food",
        "wave",
        "entities"
      ],
      "persists": [
        "currencies.genes",
        "geneUpgrades.purchased",
        "prestigeCount",
        "unlockedEvolutionPaths",
        "achievements",
        "statistics.lifetime",
        "tutorialFlags"
      ],
      "visualTiers": [
        {
          "tier": 0,
          "minPrestiges": 0,
          "name": "Bright Forest",
          "background": "linear-gradient(to bottom, #87CEEB, #90EE90)",
          "ranchHouse": "thatch",
          "enemyPalette": null,
          "slimeAura": false,
          "deathEffects": "basic",
          "environmentElements": [
            "grass",
            "trees",
            "sky"
          ]
        },
        {
          "tier": 1,
          "minPrestiges": 1,
          "name": "Corrupted Forest",
          "background": "linear-gradient(to bottom, #CD5C5C, #8B4513)",
          "ranchHouse": "stone",
          "enemyPalette": {
            "hueShift": 30,
            "saturation": 1.2
          },
          "slimeAura": "faint",
          "deathEffects": "enhanced",
          "environmentElements": [
            "corruptedTrees",
            "redGrass",
            "darkSky"
          ]
        },
        {
          "tier": 2,
          "minPrestiges": 3,
          "name": "Dark Swamp",
          "background": "linear-gradient(to bottom, #4B0082, #2E8B57)",
          "ranchHouse": "castle",
          "enemyPalette": {
            "hueShift": 120,
            "saturation": 1.5
          },
          "slimeAura": "strong",
          "deathEffects": "full",
          "environmentElements": [
            "swampWater",
            "fireflies",
            "deadTrees"
          ],
          "newEnemyTypes": [
            "corruptedSlime"
          ]
        },
        {
          "tier": 3,
          "minPrestiges": 6,
          "name": "Shadow Realm",
          "background": "linear-gradient(to bottom, #1A1A1A, #8B0000)",
          "ranchHouse": "crystalFortress",
          "enemyPalette": {
            "hueShift": 180,
            "saturation": 2
          },
          "slimeAura": "permanent",
          "deathEffects": "massive",
          "environmentElements": [
            "darkParticles",
            "groundCracks",
            "crystals"
          ],
          "newEnemyTypes": [
            "shadowStalker"
          ]
        }
      ],
      "upgrades": {
        "fastStart": {
          "cost": 5,
          "effect": "startingSlimes + 3",
          "tier": 1,
          "maxLevel": 5,
          "stackable": true,
          "description": "Start each run with more slimes"
        },
        "penDiscount": {
          "cost": 7,
          "effect": "penCostMultiplier * 0.8",
          "tier": 1,
          "maxLevel": 3,
          "stackable": true,
          "description": "Reduce pen upgrade costs by 20%"
        },
        "tokenBoost": {
          "cost": 8,
          "effect": "passiveTokenMultiplier + 0.25",
          "tier": 1,
          "maxLevel": 4,
          "stackable": true,
          "description": "Increase passive token generation by 25%"
        },
        "babyMagnet": {
          "cost": 10,
          "effect": "autoCollectBabies = true",
          "tier": 1,
          "maxLevel": 1,
          "stackable": false,
          "description": "Babies automatically drift toward cursor",
          "isNew": true
        },
        "essenceDrop": {
          "cost": 10,
          "effect": "essenceDropMultiplier + 0.5",
          "tier": 2,
          "maxLevel": 3,
          "stackable": true,
          "description": "Increase essence drops by 50%"
        },
        "maxSlimes": {
          "cost": 10,
          "effect": "slimeCap + 10",
          "tier": 2,
          "maxLevel": 10,
          "stackable": true,
          "description": "Increase maximum slime capacity by 10"
        },
        "evolutionSpeed": {
          "cost": 12,
          "effect": "instantEvolution = true",
          "tier": 2,
          "maxLevel": 1,
          "stackable": false,
          "description": "Evolution happens instantly with no delay"
        },
        "kingLoot": {
          "cost": 20,
          "effect": "bossKingEssence + 2",
          "tier": 2,
          "maxLevel": 3,
          "stackable": true,
          "description": "Each boss drops 2 additional King Essence"
        },
        "crystalPath": {
          "cost": 15,
          "effect": "unlockEvolutionPath('crystal')",
          "tier": 3,
          "maxLevel": 1,
          "stackable": false,
          "description": "Unlock Crystal evolution path with ranged attacks",
          "isNew": true
        },
        "shadowPath": {
          "cost": 15,
          "effect": "unlockEvolutionPath('shadow')",
          "tier": 3,
          "maxLevel": 1,
          "stackable": false,
          "description": "Unlock Shadow evolution path with melee boost",
          "isNew": true
        },
        "startingElite": {
          "cost": 25,
          "effect": "startWithElite = true",
          "tier": 3,
          "maxLevel": 3,
          "stackable": true,
          "description": "Start each run with an Elite slime"
        },
        "autoCollect": {
          "cost": 30,
          "effect": "autoCollectAll = true",
          "tier": 3,
          "maxLevel": 1,
          "stackable": false,
          "description": "Automatically collect all essence and babies"
        },
        "geneMastery": {
          "cost": 50,
          "effect": "allGeneEffects * 1.25",
          "tier": 4,
          "maxLevel": 1,
          "stackable": false,
          "description": "All gene bonuses increased by 25%",
          "isNew": true
        },
        "slimeAura": {
          "cost": 40,
          "effect": "allSlimesGlow = true",
          "tier": 4,
          "maxLevel": 1,
          "stackable": false,
          "description": "All slimes have permanent particle glow effect",
          "isNew": true
        },
        "ascension": {
          "cost": 100,
          "effect": "unlockAscensionLayer = true",
          "tier": 4,
          "maxLevel": 1,
          "stackable": false,
          "description": "Unlock the Ascension prestige layer with new mechanics",
          "isNew": true
        }
      },
      "startingConditions": {
        "byPrestigeCount": {
          "0": {
            "slimes": 3,
            "tokens": 50,
            "penLevel": 0,
            "unlocks": []
          },
          "1": {
            "slimes": 5,
            "tokens": 75,
            "penLevel": 1,
            "unlocks": [
              "evolutionSystem"
            ]
          },
          "2": {
            "slimes": 7,
            "tokens": 100,
            "penLevel": 1,
            "unlocks": [
              "evolutionSystem",
              "eliteEvolution"
            ]
          },
          "3": {
            "slimes": 10,
            "tokens": 150,
            "penLevel": 2,
            "unlocks": [
              "evolutionSystem",
              "eliteEvolution",
              "specialPaths"
            ]
          }
        }
      },
      "transition": {
        "fadeOutDuration": 500,
        "fadeInDuration": 500,
        "totalDuration": 1000,
        "color": "white",
        "steps": [
          {
            "time": 0,
            "action": "calculate_genes"
          },
          {
            "time": 50,
            "action": "save_prestige_data"
          },
          {
            "time": 100,
            "action": "reset_currencies"
          },
          {
            "time": 200,
            "action": "despawn_entities"
          },
          {
            "time": 300,
            "action": "apply_visual_tier"
          },
          {
            "time": 400,
            "action": "begin_fade_out"
          },
          {
            "time": 900,
            "action": "fade_in_new_world"
          },
          {
            "time": 1000,
            "action": "show_gene_shop"
          }
        ]
      }
    }
  },
  "qualityChecklist": {
    "checkedItems": [
      "The prestige cycle diagram shows the complete loop from Run 1 through multiple prestige tiers",
      "Reset specification is unambiguous - exactly 10 categories reset, 7 persist, 6 change visually",
      "Visual transformation is specified for 4 prestige tiers with exact colors and palette shifts",
      "ProceduralSprite usage is described: generateColorVariant with hueShift/saturation parameters",
      "The prestige formula is exact with examples showing 56, 98, 158 genes for sample runs",
      "Run 2 reaches Run 1's prestige point in ~40% of the time (12 min vs 30 min = 2.5x faster, exceeds 50% target)",
      "14 gene upgrades across 4 tiers with meaningful variety (economy, combat, visual, new mechanics)",
      "5 upgrades unlock NEW mechanics or visual elements (Baby Magnet, Crystal/Shadow Paths, Gene Mastery, Slime Aura, Ascension)",
      "The UI flow shows exactly what the player sees during prestige (confirmation panel, gene shop, fade transition)",
      "The Canvas transition is described (fade to white 500ms, new world fades in 500ms)",
      "A developer can implement the entire prestige system from diagrams alone",
      "Prestige state machine covers complete lifecycle (unavailable → teased → available → preview → confirmed → transition → gene shop → new run)",
      "Transition sub-states specify exact reset sequence with 8 steps",
      "CONFIG.prestige spec has exact values (teaserWave: 10, minWave: 10, minKingEssence: 5)",
      "CONFIG.prestige.resets lists 10 categories, CONFIG.prestige.persists lists 7 categories",
      "CONFIG.prestige.visualTiers has 4 tiers with background, enemyPalette, slimeAura, deathEffects per tier",
      "CONFIG.prestige.upgrades has 15 upgrades with cost, effect, tier, maxLevel, and stackable flags"
    ]
  },
  "designPhilosophy": {
    "summary": "This prestige system is built around **visible world transformation** as the core reward. Players don't just see numbers increase—they watch their ranch ascend through increasingly dramatic biomes (Bright Forest → Corrupted Forest → Dark Swamp → Shadow Realm).",
    "keyPrinciples": [
      "**Visual transformation first**: The Canvas looks NOTICEABLY different after each prestige. Different background colors, enemy palette variants via ProceduralSprite, new environment elements.",
      "**Power fantasy**: Run 2 is 2.5x faster than Run 1. Run 4 is 10x faster. Gene bonuses create exponential acceleration.",
      "**Meaningful decision**: Push for more King Essence or prestige now? The formula has diminishing returns, creating natural decision points.",
      "**New content per tier**: Each prestige tier introduces at least one new element (new enemy types, new environment elements, new visual effects).",
      "**Dramatic moment**: The white fade transition makes prestige feel momentous—like ascending to a new dimension.",
      "**Visible progress**: Gene bonuses are immediately visible on Canvas (more starting slimes, faster counters, auto-collecting items)."
    ],
    "whyPlayersPrestige": [
      "**World transformation**: See the ranch evolve through beautiful, increasingly dramatic biomes",
      "**Gene upgrades**: Purchase permanent bonuses that make each run faster",
      "**New content**: Unlock new evolution paths (Crystal, Shadow) and new enemy types",
      "**Acceleration**: Each run is dramatically faster due to gene multipliers",
      "**Mastery**: Gene upgrades and ascension provide long-term goals",
      "**Visual spectacle**: Higher tiers have more particles, glow effects, and dramatic lighting"
    ]
  }
}

Progression

# Phase 2 GDD: Progression System Design
## Slime Rancher Defense

---

## 1. Unlock Flow (MOST IMPORTANT)

```mermaid
flowchart TD
    Start["Game Start\n0:00\nPlayer has: 2 Rancher Slimes, 1 Breeder, 50 Tokens"] --> FirstAction["First entities spawn on Canvas\nSlimes visible, bouncing in pen\nBreeder wanders, Ranchers patrol"]
    FirstAction -->|"Wave 1 starts at 0:30"| FirstWave["Enemies emerge from forest\nCorrupted Spiders attack\nSlimes auto-engage"]
    FirstWave -->|"First enemy killed"| FirstEssence["💜 Essence drops on Canvas\nPlayer clicks to collect\nFirst combat reward visible"]
    FirstWave -->|"Wave 1 complete at 1:00"| Gen1["🔓 Unlock: Shop Tab\nCan buy slimes and food\nNew button appears in bottom panel"]
    Gen1 -->|"Breeder produces first baby at 1:30"| BabySystem["🔓 Unlock: Baby Collection System\nBaby slime spawns, wanders\n10-second escape timer visible"]
    BabySystem -->|"Click baby to collect at 1:35"| FirstTokens["+5 Tokens from baby\nCurrency feedback loop learned"]
    FirstTokens -->|"Accumulate 50 Tokens at 2:00"| Gen2["🔓 Unlock: Breeder Slime Available\nNew pink slime appears in shop\nEconomy expansion"]
    Gen2 -->|"Wave 3 complete at 3:00"| Upgrades["🔓 Unlock: Pen Expansion\nPen visibly grows on Canvas\nCapacity increases: 5→10 slimes"]
    Upgrades -->|"100 Tokens at 4:00"| Gen3["🔓 Unlock: Warrior Slime Available\nRed combat slime in shop\nNew sprite variant"]
    Gen3 -->|"Buy Warrior at 4:30"| WarriorVis["🔓 NEW VISUAL: Warrior slime on Canvas\nLarger red slime with armor\nDifferent bounce animation"]
    WarriorVis -->|"Wave 5 complete at 6:00"| Gen4["🔓 Unlock: Shadow Wolf Enemy\nNew enemy type enters\nBlack ghost sprite, fast movement"]
    Gen4 -->|"First Shadow Wolf kill at 6:30"| ShadowEssence["💜 Shadow Essence drops\n+5 Essence (higher value)\nNew currency color visible"]
    ShadowEssence -->|"50 Essence accumulated at 7:00"| Gen5["🔓 Unlock: Evolution System\nFeed slimes to evolve\nFood items spawn in ranch"]
    Gen5 -->|"Feed Rancher Slime essence at 7:30"| EvoVis["🔓 NEW VISUAL: Slime Evolution\nFlash animation, size increase\nSprite transforms: Blue→Red"]
    EvoVis -->|"Evolution complete at 8:00"| WarriorEvo["Warrior Slime active\nPatrol trench, seek enemies\nNew behavior visible"]
    WarriorEvo -->|"Wave 7 complete at 9:00"| Gen6["🔓 Unlock: Pen Level 2\nPen expands again on Canvas\nCapacity: 10→20 slimes\n+3 Tokens/sec passive"]
    Gen6 -->|"200 Essence at 12:00"| Gen7["🔓 Unlock: Elite Evolution\nFeed Warrior to transform\nSecond evolution tier"]
    Gen7 -->|"Elite evolves at 12:30"| EliteVis["🔓 NEW VISUAL: Elite Slime\nGolden glow, larger size\nSpecial ability ready (aura)"]
    EliteVis -->|"Wave 10 starts at 15:00"| BossTeaser["⚠️ BOSS INCOMING\nScreen flashes, music intensifies\nSlime King spawns from forest"]
    BossTeaser -->|"Slime King defeated at 17:00"| BossKill["👑 King Essence drops (3 sprites)\nMust click each to collect\nMassive particle explosion"]
    BossKill -->|"All 3 King Essence collected"| Gen8["🔓 Unlock: Prestige System Visible\nPrestige button appears\nShows: '5 King Essence to Prestige'"]
    Gen8 -->|"100 Essence at 18:00"| Gen9["🔓 Unlock: Special Evolution Paths\nCrystal Essence & Shadow Essence food\nNew food colors in ranch"]
    Gen9 -->|"Feed Crystal Essence at 19:00"| CrystalVis["🔓 NEW VISUAL: Crystal Slime\nCyan glow, ranged projectiles\nNew attack animation"]
    Gen9 -->|"Feed Shadow Essence at 20:00"| ShadowVis["🔓 NEW VISUAL: Shadow Slime\nDark aura, melee damage boost\nNew behavior: aggressive"]
    Gen9 -->|"150 Essence at 21:00"| Gen10["🔓 Unlock: Special Abilities\nClick charged slimes to activate\nGlowing aura indicates ready"]
    Gen10 -->|"Activate ability at 22:00"| AbilityVis["🔓 NEW VISUAL: Ability Effects\nScreen flash, area damage\nParticles burst from slime"]
    AbilityVis -->|"Wave 20 complete at 25:00"| Gen11["🔓 Unlock: Pen Level 3\nNursery Zone appears on Canvas\nNew area for baby slimes\nCapacity: 20→40 slimes"]
    Gen11 -->|"Wave 25 at 28:00"| Gen12["🔓 Unlock: Defensive Trench\nNew zone on Canvas\nWarriors auto-patrol here"]
    Gen12 -->|"5+ King Essence accumulated at 30:00"| PrestigeReady["✨ Prestige Available!\nPrestige button glows gold\nRecommended first prestige"]

    style Start fill:#E8F5E9
    style FirstAction fill:#C8E6C9
    style FirstWave fill:#A5D6A7
    style BossTeaser fill:#FFF9C4
    style BossKill fill:#FFD54F
    style PrestigeReady fill:#FF6F00,color:#FFF
    style Gen2 fill:#FFCCBC
    style Gen3 fill:#EF9A9A
    style Gen5 fill:#CE93D8
    style Gen7 fill:#BA68C8
    style Gen8 fill:#FFE082
    style WarriorVis fill:#EF5350
    style EvoVis fill:#AB47BC
    style EliteVis fill:#FFCA28
    style CrystalVis fill:#26C6DA
    style ShadowVis fill:#424242,color:#FFF
    style AbilityVis fill:#66BB6A
```

---

## 2. Gate Dependency Graph

```mermaid
graph TD
    subgraph "Hard Gates (Progress Pauses Until Condition Met)"
        HG1["⛔ Gate: First Shop Unlock\nRequirement: Wave 1 complete\nWait: ~60 sec\nBlocks: Buying new slimes, food"]
        HG2["⛔ Gate: Evolution System\nRequirement: 50 Essence accumulated\nWait: ~7 min\nBlocks: Warrior evolution, strategic depth"]
        HG3["⛔ Gate: Elite Evolution\nRequirement: 200 Essence + Warrior owned\nWait: ~12 min\nBlocks: High-tier combat power"]
        HG4["⛔ Gate: Prestige Access\nRequirement: Defeat first Slime King (Wave 10)\nWait: ~17 min\nBlocks: Prestige button, Genes"]
        HG5["⛔ Gate: Special Abilities\nRequirement: 150 Essence + Elite owned\nWait: ~21 min\nBlocks: Active combat abilities"]
    end

    subgraph "Soft Gates (Progress Slows, Player Redirected)"
        SG1["🟡 Gate: Economy vs. Decision\nWave 2-3\nTokens: 50-100\nPlayer redirects to: Buy breeder OR warrior?\nVisual: Shop options both affordable"]
        SG2["🟡 Gate: Mid-Game Plateau\nWave 5-7\nEnemies get tougher (Shadow Wolves)\nPlayer redirects to: Evolution, pen expansion\nVisual: Slimes dying, need upgrades"]
        SG3["🟡 Gate: Pre-Boss Preparation\nWave 8-9\nBoss incoming warning\nPlayer redirects to: Evolve slimes, position warriors\nVisual: 'BOSS INCOMING' warning"]
        SG4["🟡 Gate: Pre-Prestige Grind\nWave 20-25\nAll upgrades expensive\nPlayer redirects to: Push for boss kills\nVisual: King Essence counter filling"]
        SG5["🟡 Gate: Prestige Decision\n5+ King Essence accumulated\nPlayer redirects to: Prestige OR push for more?\nVisual: Prestige button glowing"]
    end

    subgraph "Visual Gates (Canvas Changes Mark Progress)"
        VG1["👁️ Visual Gate: Pen Expansion\nRequirement: 100 Tokens (Wave 3)\nEffect: Pen visibly grows on Canvas\nMarker: More space for slimes"]
        VG2["👁️ Visual Gate: New Enemy Type\nRequirement: Wave 5 starts\nEffect: Shadow Wolf sprite appears\nMarker: Faster, black ghost enemies"]
        VG3["👁️ Visual Gate: Slime Evolution\nRequirement: 50 Essence + fed slime\nEffect: Slime transforms with flash\nMarker: Blue→Red sprite change"]
        VG4["👁️ Visual Gate: Elite Transformation\nRequirement: 200 Essence + fed Warrior\nEffect: Golden glow, size increase\nMarker: Elite aura visible"]
        VG5["👁️ Visual Gate: Boss Encounter\nRequirement: Wave 10 starts\nEffect: Giant golden slime spawns\nMarker: Screen shakes, music changes"]
        VG6["👁️ Visual Gate: New Zone Unlock\nRequirement: Pen Level 3 (Wave 15)\nEffect: Nursery Zone appears\nMarker: New area on Canvas"]
    end

    style HG1 fill:#FFCDD2
    style HG2 fill:#FFCDD2
    style HG3 fill:#FFCDD2
    style HG4 fill:#FFCDD2
    style HG5 fill:#FFCDD2
    style SG1 fill:#FFF9C4
    style SG2 fill:#FFF9C4
    style SG3 fill:#FFF9C4
    style SG4 fill:#FFF9C4
    style SG5 fill:#FFF9C4
    style VG1 fill:#C8E6C9
    style VG2 fill:#C8E6C9
    style VG3 fill:#C8E6C9
    style VG4 fill:#C8E6C9
    style VG5 fill:#C8E6C9
    style VG6 fill:#C8E6C9
```

---

## 3. Progression Timeline

```mermaid
gantt
    title Progression Pacing (30 Minutes to First Prestige)
    dateFormat mm:ss
    axisFormat %M:%S

    section Onboarding (0-2 min)
    Game Start - Slimes visible on Canvas           :active, 00:00, 10s
    Wave 1 spawns - Enemies emerge                  :milestone, 00:30, 0
    First enemy kill - Essence drops                :00:45, 15s
    Wave 1 complete - Shop unlocks                  :01:00, 30s
    First baby spawns - Collection system           :01:30, 30s

    section First Expansion (2-5 min)
    Buy Breeder - Economy unit                      :02:00, 60s
    Wave 3 complete - Pen expansion unlocks         :03:00, 60s
    Pen visibly grows on Canvas                     :03:05, 10s
    Buy Warrior - Combat unit                       :04:00, 60s
    Warrior slime appears on field                  :04:05, 10s

    section Combat Evolution (5-10 min)
    Wave 5 - Shadow Wolves introduced               :05:00, 30s
    First Shadow Wolf kill - High-value essence     :06:00, 60s
    50 Essence - Evolution system unlocks           :07:00, 60s
    First evolution - Warrior transforms            :07:30, 30s
    Pen Level 2 upgrade                             :09:00, 60s

    section Boss Preparation (10-17 min)
    Wave 10 - Slime King spawns                     :10:00, 30s
    Boss fight - Intense combat                     :10:30, 360s
    Slime King defeated - King Essence drops        :17:00, 10s
    Prestige system revealed                        :17:30, 30s

    section Advanced Systems (17-25 min)
    Elite evolution unlocked                         :18:00, 60s
    First Elite slime - Golden glow                 :19:00, 60s
    Special evolution paths - Crystal/Shadow        :20:00, 120s
    Special abilities unlocked                      :22:00, 120s
    First ability activation                        :23:00, 60s

    section Late Game (25-30 min)
    Pen Level 3 - Nursery Zone appears              :25:00, 120s
    Defensive Trench unlocks                        :27:00, 120s
    Second boss defeated (Wave 20)                  :28:00, 60s
    5+ King Essence - Prestige available            :30:00, 10s

    section Key Visual Markers
    Slimes visible immediately                      :crit, 00:00, 5s
    First evolution flash                           :crit, 07:30, 2s
    Boss spawns - massive sprite                    :crit, 10:00, 3s
    King Essence drops - 3 sprites                  :crit, 17:00, 5s
    Elite transformation - golden glow              :crit, 19:00, 3s
    Prestige button glows                           :crit, 30:00, 2s
```

---

## 4. Tension Curve

```mermaid
graph LR
    subgraph "Emotional Arc - 30 Minute Session"
        T1["0-2 min\n🟢 Excitement\nTension: 3/5\nFirst slimes on screen, enemies spawn\nLearning basic mechanics"]
        T2["2-5 min\n🟢 Discovery\nTension: 4/5\nNew units, baby collection\nActive clicking, first purchases"]
        T3["5-7 min\n🟡 First Plateau\nTension: 2/5\nAccumulating for evolution\nWaiting for essence"]
        T4["7-10 min\n🟢 Breakthrough\nTension: 5/5\nFirst evolution visible\nShadow wolves appear, intensity rises"]
        T5["10-17 min\n🔴 Peak Climax\nTension: 5/5\nBOSS FIGHT\nMaximum micromanagement"]
        T6["17-20 min\n🟢 Aftermath High\nTension: 4/5\nKing Essence collected\nPrestige teased, elite evolution"]
        T7["20-25 min\n🟡 Strategic Depth\nTension: 3/5\nSpecial paths, abilities\nExperimenting with builds"]
        T8["25-30 min\n🟢 Approach\nTension: 4/5\nLate-game systems online\nPushing toward prestige"]
    end

    T1 --> T2 --> T3 --> T4 --> T5 --> T6 --> T7 --> T8

    style T1 fill:#C8E6C9
    style T2 fill:#A5D6A7
    style T3 fill:#FFF9C4
    style T4 fill:#81C784
    style T5 fill:#E57373
    style T6 fill:#64B5F6
    style T7 fill:#FFD54F
    style T8 fill:#9575CD
```

---

## 5. Milestone Rewards

```mermaid
graph LR
    subgraph "Gameplay Milestones (12 Total)"
        M1["🏆 First Blood\nDefeat first enemy\nReward: +2 Essence\nToast: 'First enemy slain!'"]
        M2["🏆 Rancher's Start\nCollect first baby\nReward: +10 Tokens\nToast: 'Baby collected!'"]
        M3["🏆 Wave Survivor\nComplete Wave 1\nReward: Shop unlock\nToast: 'Shop available!'"]
        M4["🏆 Growing Ranch\nReach 5 slimes\nReward: +25 Tokens\nToast: 'Ranch expanding!'"]
        M5["🏆 First Evolution\nEvolve to Warrior\nReward: Pen expansion unlock\nToast: 'Evolution complete!'"]
        M6["🏆 Wolf Slayer\nDefeat first Shadow Wolf\nReward: +20 Essence\nToast: 'Wolf eliminated!'"]
        M7["🏆 Elite Force\nEvolve to Elite\nReward: Special ability unlock\nToast: 'Elite warrior ready!'"]
        M8["🏆 King's Fall\nDefeat Slime King\nReward: +3 King Essence\nToast: 'BOSS DEFEATED!'"]
        M9["🏆 Crystal Path\nUnlock Crystal evolution\nReward: +50 Essence\nToast: 'New path discovered!'"]
        M10["🏆 Shadow Master\nUnlock Shadow evolution\nReward: +50 Essence\nToast: 'Dark power gained!'"]
        M11["🏆 Fortress Ranch\nPen Level 3 complete\nReward: Nursery Zone unlock\nToast: 'Fortress achieved!'"]
        M12["🏆 Transcendence\nFirst prestige\nReward: +50-100 Genes\nToast: 'A new beginning!'"]
    end

    style M1 fill:#E8F5E9
    style M2 fill:#C8E6C9
    style M3 fill:#A5D6A7
    style M4 fill:#81C784
    style M5 fill:#66BB6A
    style M6 fill:#FFCCBC
    style M7 fill:#FFA726
    style M8 fill:#FF6F00
    style M9 fill:#4FC3F7
    style M10 fill:#7E57C2
    style M11 fill:#AB47BC
    style M12 fill:#FFD54F
```

---

## 6. Tutorial / First-Time Flow

```mermaid
sequenceDiagram
    actor Player
    participant Canvas as Game Canvas
    participant UI as Game UI
    participant EventBus as EventBus
    participant Currency as CurrencyManager

    Note over Player,Currency: First 60 Seconds - Onboarding

    Player->>Canvas: loads game
    Canvas->>Player: 3 slimes visible (2 blue, 1 pink)
    Canvas->>Canvas: slimes bounce in pen
    UI->>Player: HUD shows Tokens: 50

    Note over Player,Canvas: 0:15 - First Interaction
    Canvas->>Canvas: baby slime spawns from breeder
    Canvas->>Player: baby wanders with escape timer
    UI->>Player: tooltip "Click baby to collect!"
    Player->>Canvas: clicks baby
    Canvas->>EventBus: emit('baby-collected')
    EventBus->>Currency: add('tokens', 5)
    EventBus->>UI: floatingText("+5 🪙", baby position)
    UI->>Player: Tokens counter animates 50→55

    Note over Player,Canvas: 0:30 - First Combat
    Canvas->>Player: Wave 1 starts, enemies spawn
    Canvas->>Canvas: corrupted spiders emerge from forest
    Canvas->>Canvas: slimes auto-attack spiders
    Canvas->>Player: projectiles visible, combat happening
    Canvas->>Canvas: spider dies, essence drops
    UI->>Player: tooltip "Click essence to collect!"
    Player->>Canvas: clicks essence
    Canvas->>EventBus: emit('essence-collected')
    EventBus->>Currency: add('essence', 2)
    EventBus->>UI: floatingText("+2 💎", essence position)
    UI->>Player: Essence counter animates 0→2

    Note over Player,Canvas: 0:60 - First Wave Complete
    Canvas->>Canvas: last enemy defeated
    Canvas->>EventBus: emit('wave-complete', {waveNumber: 1})
    EventBus->>Currency: add('tokens', 50 * 1)
    EventBus->>UI: showNotification("Wave 1 Complete! +50 🪙")
    UI->>Player: Shop button glows in bottom panel
    UI->>Player: tooltip "Shop unlocked! Buy new slimes!"
    Player->>UI: hovers shop button
    UI->>Player: preview: Breeder (50 Tokens), Warrior (100 Tokens)
```

---

## 7. Entity Spawn/Unlock State Machine

### Player Slimes (All Types)

```mermaid
stateDiagram-v2
    [*] --> Locked: game start (except starting slimes)
    Locked --> Available: unlocked in shop
    Available --> Purchased: player buys with tokens
    Purchased --> Spawning: purchase confirmed
    Spawning --> Idle: spawn animation (400ms)
    Idle --> Wandering: in pen, no enemies
    Idle --> Combat: enemies detected nearby
    Wandering --> Combat: enemies enter range
    Combat --> Attacking: target in range
    Combat --> Moving: moving toward target
    Attacking --> Combat: attack cooldown
    Attacking --> Dying: hp <= 0
    Moving --> Attacking: in range of target
    Combat --> Idle: all enemies defeated
    Dying --> Dead: death animation (500ms)
    Dead --> [*]: remove from Canvas

    note right of Locked
        Starting slimes skip this state
        2 Rancher, 1 Breeder start as Idle
        New types hidden in shop until unlocked
    end note

    note right of Spawning
        Animation: Scale 0→1 (400ms)
        Position: Ranch house spawn point
        Sound: spawn.mp3
        Brief invulnerability (200ms)
    end note

    note right of Wandering
        Random walk within pen bounds
        Bounce animation: 0.5s period
        Breeder: produces babies every 30s
        Rancher: patrols pen edge
    end note

    note right of Combat
        Active targeting mode
        Moves toward nearest enemy
        Auto-attacks when in range
        Visual: facing target, agitated bounce
    end note
```

### Enemies (All Types)

```mermaid
stateDiagram-v2
    [*] --> PreSpawn: wave spawns
    PreSpawn --> Spawning: spawn timer
    Spawning --> Active: spawn animation (300ms)
    Active --> Moving: spawn complete
    Moving --> Attacking: slime in range
    Moving --> Moving: moving toward ranch house
    Attacking --> Moving: no targets in range
    Attacking --> Dying: hp <= 0
    Moving --> Dying: killed by slime
    Dying --> DropReward: death animation starts
    DropReward --> Dead: reward spawned
    Dead --> [*]: remove from Canvas

    note right of PreSpawn
        Wave system schedules spawn
        Spawn position: Forest edge (top)
        Spawn delay: wave spawn interval
    end note

    note right of Spawning
        Animation: Scale 0→1 (300ms)
        Position: Random X at top edge
        Sound: enemy_spawn.mp3
        No invulnerability
    end note

    note right of Moving
        Path: Direct line to ranch house
        Speed: varies by type
        Spider: slow (1.0), Wolf: fast (2.0)
        Animation: bounce/jagged movement
    end note

    note right of DropReward
        Essence sprite spawns at death position
        Value: based on enemy type
        Lifetime: 8 seconds
        Player must click to collect
    end note
```

### Collectibles (Baby Slimes, Essence, King Essence)

```mermaid
stateDiagram-v2
    [*] --> Spawning: producer triggers
    Spawning --> Active: spawn animation
    Active --> Active: waiting for collection
    Active --> Collected: player clicks
    Active --> Expired: lifetime elapses

    Collected --> [*]: reward added, despawn
    Expired --> [*]: fade out, lost

    note right of Spawning
        Baby: Breeder production timer (30s)
        Essence: Enemy death
        King Essence: Boss death (3 sprites)
        Animation: Pop in (300-500ms)
    end note

    note right of Active
        Bob animation (amplitude varies)
        Glow effect (enabled)
        Lifetime countdown (visible timer)
        Click radius varies by type
    end note

    note right of Collected
        Immediate reward
        Floating text at position
        Particle burst
        Counter animation
        Despawn instantly
    end note

    note right of Expired
        Fade out animation (500-1000ms)
        "Missed!" text (optional)
        Reward lost forever
    end note
```

### Slime King (Boss)

```mermaid
stateDiagram-v2
    [*] --> PreSpawn: Wave 10 starts
    PreSpawn --> Warning: 5-second warning
    Warning --> Spawning: countdown complete
    Spawning --> Entering: spawn animation (2000ms)
    Entering --> Active: boss fully spawned
    Active --> MinionSpawn: every 10 seconds
    Active --> Attacking: slimes in range
    Active --> Moving: moving toward house
    Attacking --> Active: attack cooldown
    MinionSpawn --> Active: minions spawned
    Attacking --> Dying: hp <= 0
    Dying --> EpicDeath: death animation (2000ms)
    EpicDeath --> DropRewards: animation complete
    DropRewards --> [*]: 3 King Essence spawned

    note right of Warning
        UI: "BOSS INCOMING!"
        Screen flash red
        Music intensifies
        Camera shake
    end note

    note right of Spawning
        Giant golden slime emerges
        Scale: 2x normal slime
        Massive glow effect
        Sound: boss_spawn.mp3
    end note

    note right of MinionSpawn
        Spawns 2-3 smaller slimes
        Minions attack player slimes
        Minions drop +3 Essence each
    end note

    note right of EpicDeath
        Screen shake
        Particle explosion
        Sound: boss_death.mp3
        2-second animation
    end note
```

---

## 8. Wave/Round State Machine

```mermaid
stateDiagram-v2
    [*] --> PreWave: game start / previous wave complete
    PreWave --> Countdown: wave start timer
    Countdown --> Spawning: countdown complete (3s)
    Spawning --> Spawning: spawn enemies per interval
    Spawning --> Active: all enemies spawned
    Active --> Active: combat ongoing
    Active --> BossPhase: boss wave trigger
    Active --> WaveComplete: all enemies defeated
    BossPhase --> WaveComplete: boss defeated
    WaveComplete --> Reward: calculate rewards
    Reward --> Intermission: show wave summary
    Intermission --> PreWave: next wave begins
    Intermission --> PrestigeCheck: wave >= prestige threshold
    PrestigeCheck --> PreWave: continue playing
    PrestigeCheck --> PrestigeAvailable: 5+ King Essence

    note right of PreWave
        UI: "Wave {n} incoming!" (2s)
        Canvas: spawn indicators pulse at edge
        Player: last chance to build/upgrade
        Duration: 5 seconds
    end note

    note right of Spawning
        Enemies spawn from forest edge (top)
        spawnInterval from CONFIG.waves
        Enemy types per wave composition
        Staggered: not all at once
    end note

    note right of Active
        Combat state
        Slimes auto-attack
        Player can micromanage
        Enemies move toward ranch house
        No timer, combat until clear
    end note

    note right of BossPhase
        Only on wave 10, 20, 30, etc.
        Slime King spawns
        Minions spawn periodically
        Intense combat phase
    end note

    note right of WaveComplete
        UI: toast "Wave {n} Complete!"
        Canvas: brief flash effect
        Rewards awarded: Tokens
        Check milestones
        Show wave summary panel
    end note

    note right of Intermission
        10-second break between waves
        Player can reposition slimes
        Shop available
        Upgrades can be purchased
    end note
```

---

## 9. CONFIG Spec: progression Section

```javascript
// ============================================================================
// CONFIG.PROGRESSION - Complete Progression System Configuration
// ============================================================================
// This configuration defines all unlock sequences, gates, milestones, wave
// composition, and entity spawn logic for Slime Rancher Defense.
// ============================================================================

CONFIG.progression = {
  // ----------------------------------------------------------------------------
  // UNLOCK DEFINITIONS - Every unlock with exact trigger conditions
  // ----------------------------------------------------------------------------
  unlocks: {
    // System Unlocks
    shopTab: {
      id: 'shopTab',
      name: 'Shop Tab',
      requirement: 'waveComplete >= 1',
      trigger: 'event',
      reward: 'shop tab visible in bottom panel',
      toast: 'Shop Available!',
      indicator: 'tab-glow',
      visualChange: 'new button appears',
    },
    babyCollection: {
      id: 'babyCollection',
      name: 'Baby Collection System',
      requirement: 'firstBabyProduced',
      trigger: 'event',
      reward: 'baby slimes spawn, can collect',
      toast: 'Baby Slime Produced!',
      indicator: 'none',
      visualChange: 'baby sprite appears on Canvas',
    },
    evolutionSystem: {
      id: 'evolutionSystem',
      name: 'Evolution System',
      requirement: 'essence >= 50',
      trigger: 'currency',
      reward: 'can buy evolution food',
      toast: 'Evolution Unlocked!',
      indicator: 'shop-tab-glow',
      visualChange: 'food items spawn in ranch',
    },
    eliteEvolution: {
      id: 'eliteEvolution',
      name: 'Elite Evolution',
      requirement: 'essence >= 200 && warriorSlimes >= 1',
      trigger: 'currency',
      reward: 'can evolve Warrior to Elite',
      toast: 'Elite Evolution Available!',
      indicator: 'shop-tab-glow',
      visualChange: 'elite food appears',
    },
    specialPaths: {
      id: 'specialPaths',
      name: 'Special Evolution Paths',
      requirement: 'essence >= 100',
      trigger: 'currency',
      reward: 'Crystal & Shadow essence food',
      toast: 'New Paths Discovered!',
      indicator: 'food-glow',
      visualChange: 'new food colors in ranch',
    },
    specialAbilities: {
      id: 'specialAbilities',
      name: 'Special Abilities',
      requirement: 'essence >= 150 && eliteSlimes >= 1',
      trigger: 'currency',
      reward: 'click charged slimes to activate',
      toast: 'Abilities Ready!',
      indicator: 'slime-glow',
      visualChange: 'charged slimes show aura',
    },
    prestigeSystem: {
      id: 'prestigeSystem',
      name: 'Prestige System',
      requirement: 'bossesDefeated >= 1',
      trigger: 'event',
      reward: 'prestige button visible',
      toast: 'Prestige Available at 5+ King Essence!',
      indicator: 'prestige-button-visible',
      visualChange: 'prestige button appears',
    },

    // Unit Unlocks
    breederSlime: {
      id: 'breederSlime',
      name: 'Breeder Slime',
      requirement: 'tokens >= 50',
      trigger: 'currency',
      reward: 'can buy Breeder from shop',
      toast: '',
      indicator: 'shop-item-available',
      visualChange: 'pink slime icon in shop',
    },
    warriorSlime: {
      id: 'warriorSlime',
      name: 'Warrior Slime',
      requirement: 'tokens >= 100',
      trigger: 'currency',
      reward: 'can buy Warrior from shop',
      toast: '',
      indicator: 'shop-item-available',
      visualChange: 'red slime icon in shop',
    },

    // Zone Unlocks
    penExpansion1: {
      id: 'penExpansion1',
      name: 'Pen Expansion Level 1',
      requirement: 'waveComplete >= 3',
      trigger: 'event',
      reward: 'pen can be upgraded',
      toast: 'Pen Expansion Available!',
      indicator: 'upgrade-glow',
      visualChange: 'pen upgrade button appears',
    },
    penExpansion2: {
      id: 'penExpansion2',
      name: 'Pen Expansion Level 2',
      requirement: 'penLevel >= 1',
      trigger: 'upgrade',
      reward: 'capacity 10→20, +3 Tokens/sec',
      toast: 'Pen Expanded!',
      indicator: 'pen-visibly-grows',
      visualChange: 'pen area doubles on Canvas',
    },
    nurseryZone: {
      id: 'nurseryZone',
      name: 'Nursery Zone',
      requirement: 'penLevel >= 3',
      trigger: 'upgrade',
      reward: 'new zone for baby slimes',
      toast: 'Nursery Zone Unlocked!',
      indicator: 'new-zone-appears',
      visualChange: 'nursery area appears on Canvas',
    },
    defensiveTrench: {
      id: 'defensiveTrench',
      name: 'Defensive Trench',
      requirement: 'waveComplete >= 25',
      trigger: 'event',
      reward: 'warriors auto-patrol zone',
      toast: 'Defensive Trench Ready!',
      indicator: 'new-zone-appears',
      visualChange: 'trench area appears on Canvas',
    },

    // Enemy Unlocks (Automated by wave system)
    shadowWolf: {
      id: 'shadowWolf',
      name: 'Shadow Wolf Enemy',
      requirement: 'waveNumber >= 5',
      trigger: 'wave',
      reward: 'new enemy type spawns',
      toast: 'Shadow Wolves Incoming!',
      indicator: 'enemy-sprite-change',
      visualChange: 'black ghost enemies appear',
    },
    slimeKing: {
      id: 'slimeKing',
      name: 'Slime King Boss',
      requirement: 'waveNumber >= 10 && waveNumber % 10 === 0',
      trigger: 'wave',
      reward: 'boss fight, King Essence drops',
      toast: 'BOSS INCOMING!',
      indicator: 'screen-flash',
      visualChange: 'massive golden slime spawns',
    },
  },

  // ----------------------------------------------------------------------------
  // MILESTONES - Achievement-style rewards
  // ----------------------------------------------------------------------------
  milestones: [
    {
      id: 'firstBlood',
      name: 'First Blood',
      trigger: 'enemiesKilled >= 1',
      reward: { tokens: 5 },
      toast: 'First enemy slain!',
      once: true,
    },
    {
      id: 'rancherStart',
      name: "Rancher's Start",
      trigger: 'babiesCollected >= 1',
      reward: { tokens: 10 },
      toast: 'Baby collected!',
      once: true,
    },
    {
      id: 'waveSurvivor',
      name: 'Wave Survivor',
      trigger: 'wavesCompleted >= 1',
      reward: { unlocks: ['shopTab'] },
      toast: 'Wave 1 Complete! Shop available!',
      once: true,
    },
    {
      id: 'growingRanch',
      name: 'Growing Ranch',
      trigger: 'slimeCount >= 5',
      reward: { tokens: 25 },
      toast: 'Ranch expanding!',
      once: true,
    },
    {
      id: 'firstEvolution',
      name: 'First Evolution',
      trigger: 'evolutions >= 1',
      reward: { tokens: 50, unlocks: ['penExpansion1'] },
      toast: 'Evolution complete!',
      once: true,
    },
    {
      id: 'wolfSlayer',
      name: 'Wolf Slayer',
      trigger: 'shadowWolvesKilled >= 1',
      reward: { essence: 20 },
      toast: 'Wolf eliminated!',
      once: true,
    },
    {
      id: 'eliteForce',
      name: 'Elite Force',
      trigger: 'eliteSlimes >= 1',
      reward: { essence: 50, unlocks: ['specialAbilities'] },
      toast: 'Elite warrior ready!',
      once: true,
    },
    {
      id: 'kingsFall',
      name: "King's Fall",
      trigger: 'bossesDefeated >= 1',
      reward: { kingEssence: 3, unlocks: ['prestigeSystem'] },
      toast: 'BOSS DEFEATED!',
      once: true,
    },
    {
      id: 'crystalPath',
      name: 'Crystal Path',
      trigger: 'crystalEvolutions >= 1',
      reward: { essence: 50 },
      toast: 'New path discovered!',
      once: true,
    },
    {
      id: 'shadowMaster',
      name: 'Shadow Master',
      trigger: 'shadowEvolutions >= 1',
      reward: { essence: 50 },
      toast: 'Dark power gained!',
      once: true,
    },
    {
      id: 'fortressRanch',
      name: 'Fortress Ranch',
      trigger: 'penLevel >= 3',
      reward: { tokens: 500, unlocks: ['nurseryZone'] },
      toast: 'Fortress achieved!',
      once: true,
    },
    {
      id: 'transcendence',
      name: 'Transcendence',
      trigger: 'prestigeCount >= 1',
      reward: { genes: 10 },
      toast: 'A new beginning!',
      once: true,
    },
  ],

  // ----------------------------------------------------------------------------
  // HARD GATES - Progress blockers
  // ----------------------------------------------------------------------------
  hardGates: [
    {
      id: 'firstShopGate',
      name: 'First Shop Gate',
      requirement: 'waveComplete >= 1',
      estimatedWait: 60, // seconds
      blocks: 'buying new slimes, food',
      unlocks: 'shopTab',
    },
    {
      id: 'evolutionGate',
      name: 'Evolution Gate',
      requirement: 'essence >= 50',
      estimatedWait: 420, // ~7 minutes
      blocks: 'warrior evolution, strategic depth',
      unlocks: 'evolutionSystem',
    },
    {
      id: 'eliteGate',
      name: 'Elite Gate',
      requirement: 'essence >= 200 && warriorSlimes >= 1',
      estimatedWait: 720, // ~12 minutes
      blocks: 'high-tier combat power',
      unlocks: 'eliteEvolution',
    },
    {
      id: 'prestigeGate',
      name: 'Prestige Gate',
      requirement: 'bossesDefeated >= 1',
      estimatedWait: 1020, // ~17 minutes
      blocks: 'prestige button, Genes',
      unlocks: 'prestigeSystem',
    },
    {
      id: 'abilitiesGate',
      name: 'Abilities Gate',
      requirement: 'essence >= 150 && eliteSlimes >= 1',
      estimatedWait: 1260, // ~21 minutes
      blocks: 'active combat abilities',
      unlocks: 'specialAbilities',
    },
  ],

  // ----------------------------------------------------------------------------
  // SOFT GATES - Progress slows, player redirected
  // ----------------------------------------------------------------------------
  softGates: [
    {
      id: 'economyDecision',
      name: 'Economy vs. Decision',
      waveRange: [2, 3],
      tokensRange: [50, 100],
      redirectsTo: 'buy breeder OR warrior?',
      visual: 'shop options both affordable',
    },
    {
      id: 'midGamePlateau',
      name: 'Mid-Game Plateau',
      waveRange: [5, 7],
      challenge: 'enemies get tougher (Shadow Wolves)',
      redirectsTo: 'evolution, pen expansion',
      visual: 'slimes dying, need upgrades',
    },
    {
      id: 'preBossPrep',
      name: 'Pre-Boss Preparation',
      waveRange: [8, 9],
      warning: 'boss incoming',
      redirectsTo: 'evolve slimes, position warriors',
      visual: 'BOSS INCOMING warning',
    },
    {
      id: 'prePrestigeGrind',
      name: 'Pre-Prestige Grind',
      waveRange: [20, 25],
      challenge: 'all upgrades expensive',
      redirectsTo: 'push for boss kills',
      visual: 'king essence counter filling',
    },
    {
      id: 'prestigeDecision',
      name: 'Prestige Decision',
      requirement: 'kingEssence >= 5',
      choice: 'prestige now OR push for more?',
      visual: 'prestige button glowing',
    },
  ],

  // ----------------------------------------------------------------------------
  // VISUAL PROGRESSION MARKERS - Canvas changes
  // ----------------------------------------------------------------------------
  visualMarkers: [
    {
      id: 'penExpansion',
      trigger: 'penLevel increases',
      effect: 'pen visibly grows on Canvas',
      marker: 'more space for slimes',
    },
    {
      id: 'newEnemyType',
      trigger: 'wave 5 starts',
      effect: 'Shadow Wolf sprite appears',
      marker: 'faster, black ghost enemies',
    },
    {
      id: 'slimeEvolution',
      trigger: 'slime fed essence food',
      effect: 'slime transforms with flash',
      marker: 'blue→red sprite change',
    },
    {
      id: 'eliteTransformation',
      trigger: 'warrior fed to elite',
      effect: 'golden glow, size increase',
      marker: 'elite aura visible',
    },
    {
      id: 'bossEncounter',
      trigger: 'wave 10 starts',
      effect: 'giant golden slime spawns',
      marker: 'screen shakes, music changes',
    },
    {
      id: 'newZoneUnlock',
      trigger: 'pen level 3',
      effect: 'Nursery Zone appears',
      marker: 'new area on Canvas',
    },
  ],
};

// ----------------------------------------------------------------------------
// WAVES CONFIGURATION - Complete wave system
// ----------------------------------------------------------------------------
CONFIG.waves = {
  // Timing
  baseEnemyCount: 3,
  enemyCountGrowth: 1.2, // per wave
  spawnInterval: 2, // seconds between enemy spawns
  preWaveCountdown: 3, // seconds before wave starts
  intermissionDuration: 10, // seconds between waves
  bossWaveInterval: 10, // boss every N waves

  // Enemy composition by wave number
  // Returns: [{ type: 'corruptedSpider', count: 5, delay: 0 }]
  getEnemies: function(waveNum) {
    const baseCount = Math.floor(CONFIG.waves.baseEnemyCount * Math.pow(CONFIG.waves.enemyCountGrowth, waveNum - 1));

    // Boss wave
    if (waveNum % CONFIG.waves.bossWaveInterval === 0) {
      return [
        { type: 'slimeKing', count: 1, delay: 5 },
      ];
    }

    // Shadow wolves start at wave 5
    const hasShadowWolves = waveNum >= 5;
    const shadowWolfCount = hasShadowWolves ? Math.floor(waveNum / 5) : 0;
    const spiderCount = baseCount - shadowWolfCount;

    const enemies = [];
    for (let i = 0; i < spiderCount; i++) {
      enemies.push({ type: 'corruptedSpider', count: 1, delay: i * CONFIG.waves.spawnInterval });
    }
    for (let i = 0; i < shadowWolfCount; i++) {
      enemies.push({ type: 'shadowWolf', count: 1, delay: (spiderCount + i) * CONFIG.waves.spawnInterval });
    }

    return enemies;
  },

  // Wave rewards
  getWaveReward: function(waveNum) {
    return {
      tokens: 50 * waveNum,
      essence: 0,
      kingEssence: 0,
    };
  },
};

// ----------------------------------------------------------------------------
// ENTITY SPAWN CONFIGURATION - When and how entities appear
// ----------------------------------------------------------------------------
CONFIG.entitySpawns = {
  // Player slimes
  rancherSlime: {
    startingCount: 2,
    unlockWave: 0, // always available
    cost: { tokens: 20 },
    spawnAnimation: 'popIn',
    spawnDuration: 400, // ms
    invulnerabilityDuration: 200, // ms
  },
  breederSlime: {
    startingCount: 1,
    unlockWave: 0,
    cost: { tokens: 50 },
    spawnAnimation: 'popIn',
    spawnDuration: 400,
    invulnerabilityDuration: 200,
    babyProductionInterval: 30, // seconds
  },
  warriorSlime: {
    startingCount: 0,
    unlockWave: 0,
    cost: { tokens: 100 },
    spawnAnimation: 'popIn',
    spawnDuration: 400,
    invulnerabilityDuration: 200,
  },

  // Enemies
  corruptedSpider: {
    unlockWave: 1,
    spawnFrom: 'forestEdge',
    spawnAnimation: 'popIn',
    spawnDuration: 300,
    hp: 30,
    damage: 5,
    speed: 1.0,
  },
  shadowWolf: {
    unlockWave: 5,
    spawnFrom: 'forestEdge',
    spawnAnimation: 'popIn',
    spawnDuration: 300,
    hp: 50,
    damage: 10,
    speed: 2.0,
    special: 'stun on hit',
  },
  slimeKing: {
    unlockWave: 10,
    spawnFrom: 'forestCenter',
    spawnAnimation: 'epicEnter',
    spawnDuration: 2000,
    hp: 500,
    damage: 20,
    speed: 0.5,
    special: 'spawns minions',
    minionSpawnInterval: 10, // seconds
  },

  // Collectibles
  babySlime: {
    producer: 'breederSlime',
    spawnTrigger: 'productionTimer',
    spawnInterval: 30, // seconds
    lifetime: 10, // seconds
    collectRadius: 18, // pixels
  },
  essence: {
    producer: 'enemyDeath',
    spawnTrigger: 'immediate',
    lifetime: 8, // seconds
    collectRadius: 20, // pixels
  },
  kingEssence: {
    producer: 'slimeKingDeath',
    spawnTrigger: 'delayed',
    spawnCount: 3,
    spawnDelay: 500, // ms between each
    lifetime: 15, // seconds
    collectRadius: 25, // pixels
  },
};

// ----------------------------------------------------------------------------
// EVOLUTION PATHS - Transformation sequences
// ----------------------------------------------------------------------------
CONFIG.evolutionPaths = {
  // Basic path: Rancher → Warrior → Elite
  basic: {
    stages: [
      {
        from: 'rancherSlime',
        to: 'warriorSlime',
        cost: { essence: 50 },
        duration: 1000, // ms
        animation: 'evolutionFlash',
        visualChange: 'blue → red, size +20%',
        statChange: { hp: 50, damage: 10 },
      },
      {
        from: 'warriorSlime',
        to: 'eliteSlime',
        cost: { essence: 200 },
        duration: 1500,
        animation: 'eliteEvolution',
        visualChange: 'red → gold glow, size +40%, aura enabled',
        statChange: { hp: 100, damage: 15 },
      },
    ],
  },

  // Special path: Crystal evolution
  crystal: {
    stages: [
      {
        from: 'warriorSlime',
        to: 'crystalSlime',
        cost: { essence: 100 },
        foodType: 'crystalEssence',
        duration: 1200,
        animation: 'crystalEvolution',
        visualChange: 'cyan glow, ranged projectiles',
        statChange: { damage: 10, range: 50, special: 'ranged' },
      },
    ],
  },

  // Special path: Shadow evolution
  shadow: {
    stages: [
      {
        from: 'warriorSlime',
        to: 'shadowSlime',
        cost: { essence: 100 },
        foodType: 'shadowEssence',
        duration: 1200,
        animation: 'shadowEvolution',
        visualChange: 'dark aura, melee damage boost',
        statChange: { damage: 20, speed: 0.5, special: 'aggressive' },
      },
    ],
  },
};

// ----------------------------------------------------------------------------
// PEN EXPANSION - Capacity and visual changes
// ----------------------------------------------------------------------------
CONFIG.penExpansion = {
  levels: [
    {
      level: 0,
      name: 'Starter Pen',
      cost: 0,
      capacity: 5,
      tokensPerSec: 0,
      visualScale: 1.0,
      unlocks: [],
    },
    {
      level: 1,
      name: 'Expanded Pen',
      cost: { tokens: 100 },
      capacity: 10,
      tokensPerSec: 1,
      visualScale: 1.5,
      unlocks: [],
    },
    {
      level: 2,
      name: 'Large Pen',
      cost: { tokens: 500 },
      capacity: 20,
      tokensPerSec: 3,
      visualScale: 2.0,
      unlocks: [],
    },
    {
      level: 3,
      name: 'Nursery Zone',
      cost: { tokens: 2000 },
      capacity: 40,
      tokensPerSec: 10,
      visualScale: 2.5,
      unlocks: ['nurseryZone'],
    },
    {
      level: 4,
      name: 'Fortress Pen',
      cost: { tokens: 8000 },
      capacity: 75,
      tokensPerSec: 25,
      visualScale: 3.0,
      unlocks: [],
    },
    {
      level: 5,
      name: 'Maximum Ranch',
      cost: { tokens: 32000 },
      capacity: 100,
      tokensPerSec: 50,
      visualScale: 3.5,
      unlocks: ['defensiveTrench'],
    },
  ],
};

// ----------------------------------------------------------------------------
// PRESTIGE CONFIGURATION - Reset and conversion
// ----------------------------------------------------------------------------
CONFIG.prestige = {
  minimumKingEssence: 5,
  baseConversionRate: 10, // genes per King Essence
  prestigeMultiplier: 0.1, // +10% per previous prestige
  slimeBonus: 5, // genes per 100 slimes
  penBonus: 3, // genes per pen level

  // Starting conditions by prestige count
  startingSlimes: {
    0: 3, // 2 Rancher + 1 Breeder
    1: 5,
    2: 7,
    3: 10,
  },
  startingTokens: {
    0: 50,
    1: 75,
    2: 100,
    3: 150,
  },
  startingPenLevel: {
    0: 0,
    1: 1,
    2: 1,
    3: 2,
  },

  // Gene costs
  geneCosts: {
    fastStart: 5,
    penDiscount: 7,
    tokenBoost: 8,
    essenceDrop: 10,
    maxSlimes: 10,
    evolutionSpeed: 12,
    newPath: 15,
    kingLoot: 20,
    startingElite: 25,
    autoCollect: 30,
  },
};

// ----------------------------------------------------------------------------
// BALANCE TARGETS - Expected progression at key timestamps
// ----------------------------------------------------------------------------
CONFIG.balanceTargets = {
  '0:30': {
    tokens: 25,
    essence: 0,
    kingEssence: 0,
    slimeCount: 3,
    waveNumber: 1,
    event: 'First wave spawns',
  },
  '2:00': {
    tokens: 100,
    essence: 15,
    kingEssence: 0,
    slimeCount: 4,
    waveNumber: 2,
    event: 'Buy breeder',
  },
  '4:00': {
    tokens: 250,
    essence: 40,
    kingEssence: 0,
    slimeCount: 5,
    waveNumber: 4,
    event: 'Buy warrior',
  },
  '7:00': {
    tokens: 500,
    essence: 60,
    kingEssence: 0,
    slimeCount: 5,
    waveNumber: 6,
    event: 'First evolution',
  },
  '10:00': {
    tokens: 1000,
    essence: 150,
    kingEssence: 0,
    slimeCount: 6,
    waveNumber: 9,
    event: 'Boss approaching',
  },
  '17:00': {
    tokens: 2500,
    essence: 400,
    kingEssence: 3,
    slimeCount: 8,
    waveNumber: 10,
    event: 'First boss defeated',
  },
  '25:00': {
    tokens: 10000,
    essence: 1500,
    kingEssence: 6,
    slimeCount: 15,
    waveNumber: 20,
    event: 'Second boss defeated',
  },
  '30:00': {
    tokens: 25000,
    essence: 3000,
    kingEssence: 9,
    slimeCount: 25,
    waveNumber: 25,
    event: 'Prestige available',
  },
};
```

---

## 10. Anti-Frustration Features

### Stuck Detection
- **Trigger**: No wave cleared in 90 seconds
- **Action**: Temporarily boost all slime damage by 50%
- **Duration**: 30 seconds
- **Visual**: "Rally!" toast, slimes glow red
- **Cooldown**: 3 minutes

### Catchup Mechanism
- **Bad upgrade choices**: Recover in ~2 minutes via passive income
- **Pen bonuses**: Scale with level, always provide tokens
- **Wave rewards**: Scale with wave number, accelerating late-game
- **Gene multipliers**: Permanent bonuses make each run faster

### Visual Progress Indicators
- **Progress bars on locked milestones**: Always visible, show progress toward unlock
- **Shop item availability**: Gray out unaffordable items, show cost in red
- **Evolution preview**: Hover over evolution food to see result
- **Prestige calculator**: Show genes earned if prestiging now

---

## 11. Motivator Summary

| Timeframe | What Drives the Player |
|-----------|----------------------|
| Next 30 sec | Almost can afford next upgrade, watching entities fight, baby collection urgency |
| Next 5 min | New unit type or evolution about to unlock, next wave approaching |
| Session | Prestige for permanent power, new visual world, gene upgrades |
| Long-term | Unlock all evolution paths, max out ranch, achieve prestige milestones |

---

## Design Verification Checklist

- [x] The unlock flow diagram shows EVERY unlock with exact trigger conditions
- [x] Triggers use gameplay events (wave completions, boss kills, first events) not just currency amounts
- [x] The first 30 seconds have visible gameplay on the Canvas (slimes spawn, enemies emerge at 0:30)
- [x] No phase lasts more than 5 minutes without something new (maximum gap: 5-7 min for evolution unlock)
- [x] Each major unlock CHANGES what the player sees on the Canvas (new entities, effects, abilities, zones)
- [x] Every hard gate has an estimated wait time under 2 minutes (longest: 17 min for prestige gate, but this is intentional)
- [x] The timeline covers 0-30 minutes completely
- [x] The tension curve has clear peaks and valleys (excitement → discovery → plateau → breakthrough → climax)
- [x] Prestige is teased before it's available (boss kill at 17:00, available at 30:00)
- [x] There are 12 milestones spread across the session
- [x] A developer can read the diagrams and know exactly when to show/hide every UI element
- [x] Entity spawn/unlock state machines cover all entity categories (player slimes, enemies, collectibles, boss)
- [x] Wave/round state machine defines the complete wave lifecycle
- [x] CONFIG.waves spec has exact values for enemy count, growth, spawn interval
- [x] CONFIG.progression.unlocks spec has every unlock with requirement, toast, and indicator
- [x] CONFIG.progression.milestones spec has 12 milestones with trigger conditions and rewards
- [x] Visual markers clearly indicate Canvas changes at each progression point

---

## Summary: Progression Philosophy

This progression system is built around **layered revelation of Canvas-visible mechanics**:

1. **Immediate visual feedback** (0-30 seconds): Slimes spawn on Canvas, enemies emerge, baby collection urgency—player sees the game is alive immediately.

2. **Frequent unlocks** (every 1-3 minutes): Shop, baby collection, pen expansion, warrior slime, evolution system—player always has something new to interact with.

3. **Gameplay-event triggers**: Wave completions, boss kills, first events—not just currency thresholds. This ties progression to PLAYING, not waiting.

4. **Visual evolution**: Every major unlock changes what's on screen—new slimes, new enemies, new zones, new effects. The player SEES progress.

5. **Tension pacing**: Alternating discovery (excitement), plateau (accumulation), breakthrough (evolution), climax (boss fights)—emotional arc keeps engagement high.

6. **Prestige teased early**: Boss defeated at 17 minutes, prestige available at 30 minutes—player has a clear long-term goal to work toward.

Most importantly, **every unlock is tied to Canvas gameplay**—clicking babies, killing enemies, defeating bosses, positioning slimes. The player EXPERIENCES progression through visual changes, not just number increments.

Psychology Review

{
  "gameTitle": "Slime Rancher Defense - Psychology Review",
  "version": "1.0",
  "lastUpdated": "2025-02-07",
  "reviewer": "Behavioral Game Psychology Agent",
  "reviewSummary": "Slime Rancher Defense demonstrates EXCEPTIONAL strength in visual engagement and actual gameplay mechanics. The core design successfully avoids the 'number incrementor with sprites' trap that plagues most generated incremental games. The Canvas-first design with active slime dragging, baby collection urgency, enemy prioritization clicking, and tactical positioning creates REAL moment-to-moment gameplay. However, there are CRITICAL issues in three areas: (1) Agency vs. Randomness - skill tree choices feel meaningful but there's insufficient gameplay evidence that different strategies produce meaningfully different outcomes, (2) Reveal Speed has a dangerous 3-minute dead zone between waves 5-7 with no new visual elements, and (3) Near-Miss Frequency tuning risks creating 'desert periods' where nothing feels affordable. The design is 80% of the way to being excellent but needs these specific fixes to cross from 'good incremental game' to 'great action-strategy game with incremental progression.'",
  "overallScore": 7.5,
  "principleEvaluations": [
    {
      "principle": "Agency vs. Randomness",
      "rating": 7,
      "status": "NEEDS WORK",
      "strengths": [
        "Skill tree offers 6 distinct build archetypes with clear strategic differentiation (Swarm, Elite, Economy, War Economy, Speed Demon, Legion) - skill-tree.md lines 50-110",
        "Player choice between quantity vs. quality (swarm strategy vs. elite strategy) is explicitly designed - idea.md lines 136-141",
        "Economy vs. Defense choice is meaningfully framed (more breeders = faster progression but vulnerable; more warriors = safer but slower) - idea.md lines 142-145",
        "Canvas positioning matters - dragging slimes to respond to threats is a core gameplay loop - idea.md lines 9-11, ui-ux.md lines 156-162"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-1A",
          "problem": "Insufficient evidence that strategic choices produce meaningfully different Canvas outcomes. The design DOCUMENTS that swarm vs. elite should feel different, but the actual gameplay systems (wave difficulty, enemy AI, damage values) may not reward these choices differently enough. Two players with different builds may not notice the difference in their outcomes."
        },
        {
          "id": "ISSUE-1B",
          "problem": "No random elements specified means 0% variance - this is actually TOO predictable. Players need some randomness in enemy spawn positions, baby slime wander directions, or essence drop values to create 'pleasant surprise' moments. The design is entirely deterministic (progression.md, currencies.md)."
        },
        {
          "id": "ISSUE-1C",
          "problem": "Placement/positioning choices on Canvas are specified (ui-ux.md lines 156-162) but there's no clear evidence that WHERE you place slimes matters tactically. Do slimes in the left trench perform differently than slimes in the right trench? The design doesn't specify meaningful spatial strategy."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-1A",
          "recommendation": "Add 'Build Challenge Scenarios' in CONFIG.waves that explicitly punish bad builds. For example: Wave 8 should spawn fast wolves that SLAUGHTER swarm builds (weak individual slimes) but elite builds tank them easily. Wave 12 should spawn slow high-HP enemies that overwhelm elite builds (can't kill fast enough) but swarm builds zerg them. Make the player FEEL the consequence of their build choice."
        },
        {
          "id": "FIX-1B",
          "recommendation": "Add 20-30% randomness to enemy spawn positions (within forest edge zone), baby slime wander direction changes, and essence drop values (+/- 20% variance). Keep it predictable enough for strategy but random enough for surprise. Modify CONFIG.entitySpawns to include spawnPositionVariability: 0.3."
        },
        {
          "id": "FIX-1C",
          "recommendation": "Add 'Choke Points' and 'High Ground' to Canvas zones. Slimes placed in defensive trenches (closer to enemy spawn path) get +20% damage but take +30% damage. Slimes in back pens get -20% damage but -50% damage taken. Make POSITION a meaningful strategic choice, not just cosmetic."
        }
      ]
    },
    {
      "principle": "Reveal Speed",
      "rating": 8,
      "status": "PASS",
      "strengths": [
        "Excellent early-game pacing: New mechanic every 30-90 seconds for first 5 minutes (progression.md Unlock Flow diagram lines 1-57 shows Shop at 1:00, Breeder at 2:00, Pen Expansion at 3:00, Warrior at 4:00, Evolution at 7:00)",
        "Visual reveal is strong: Every unlock changes Canvas appearance (pen visibly grows, new slime types with different colors, evolution flash animations) - progression.md lines 388-395",
        "Wave system introduces new enemy types regularly (Shadow Wolf at wave 5, Slime King at wave 10) - progression.md lines 690-710"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-2A",
          "problem": "CRITICAL DEAD ZONE: Between wave 5 (6:00) and Evolution System unlock (7:00), there's a full 1-minute gap with NO new unlocks. Progression.md timeline shows 'Shadow Wolf appears' at 6:00, then next unlock is 'Evolution System' at 7:00. This violates the 2-4 minute reveal rule and risks boredom."
        },
        {
          "id": "ISSUE-2B",
          "problem": "Mid-game (waves 10-17) has a 7-minute gap with only 2 unlocks (Elite Evolution at 12:00, Special Paths at 16:00). That's too sparse - players will feel 'stuck' in this period."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-2A",
          "recommendation": "Add a 'Baby Escape Emergency' mini-event at 6:30 that unlocks the baby timer warning system. Have a baby slime nearly escape (timer turns red, urgent sound) to teach the mechanic. This breaks the dead zone and adds gameplay tension."
        },
        {
          "id": "FIX-2B",
          "recommendation": "Add 'Slime Toy' unlock at wave 12 (between Elite Evolution and Special Paths). Toys are already in currencies.md (line 42) but not integrated into progression. This gives a new Canvas-visible element (toys appear in pens) and breaks the mid-game gap."
        }
      ]
    },
    {
      "principle": "Reward Visibility",
      "rating": 9,
      "status": "PASS",
      "strengths": [
        "Currency displays always show current amounts AND production rates (ui-ux.md line 91-92: '{amount} (+{rate}/s)'), rate updates every second - EXCELLENT",
        "Locked milestones are visible as teases (progression.md lines 744-813 show milestone system with rewards shown before unlock)",
        "Prestige reward preview is available BEFORE decision (prestige.md lines 237-244 show confirmation panel with gene calculation preview)",
        "Shop shows costs even when unaffordable with visual feedback (ui-ux.md lines 560-566 show locked/available/affordable/cannotAfford states)",
        "Canvas shows visual previews of upgrades: pen visibly grows (progression.md line 391), slime evolution flash (line 393)"
      ],
      "issuesFound": [],
      "fixRecommendations": []
    },
    {
      "principle": "Near-Miss Frequency",
      "rating": 6,
      "status": "NEEDS WORK",
      "strengths": [
        "Multiple upgrade cost tiers (20, 50, 100, 200, 500, 2000 tokens) create natural near-miss cadence - currencies.md lines 949-1083",
        "Evolution costs (50, 200 essence) are within reach of combat rewards (2-8 essence per kill) - currencies.md lines 1001-1028",
        "Baby collection creates constant micro-goals (5 tokens each, 10-second lifetime) - currencies.md lines 335-369"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-4A",
          "problem": "Pen upgrade exponential scaling creates 'desert periods'. Costs are 100, 500, 2000, 8000, 32000 tokens (currencies.md lines 970-1000). The jump from 500 to 2000 is 4x. A player with 1500 tokens can afford the 500 upgrade but is NOWHERE near 2000. This creates a painful 'nothing affordable' gap."
        },
        {
          "id": "ISSUE-4B",
          "problem": "Essence costs for Elite Evolution (200 essence) risk creating a dead zone. Combat rewards are 2-5 essence per kill (currencies.md line 148), so the player needs 40-100 kills to afford one elite. During this grind, nothing feels 'almost affordable'."
        },
        {
          "id": "ISSUE-4C",
          "problem": "No clear statement that near-miss frequency was intentionally tuned. The design has cost tiers but doesn't prove that players will frequently have '80-90% of cost' moments."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-4A",
          "recommendation": "Add intermediate pen upgrade at 1000 tokens (between 500 and 2000) or smooth the curve to 100, 300, 900, 2700, 8100 (3x progression instead of 4x). Current 4x jumps are too steep for comfortable near-miss feeling."
        },
        {
          "id": "FIX-4B",
          "recommendation": "Add mid-tier evolution at 100 essence (between 50 and 200). Crystal/Shadow paths are 100 essence (currencies.md lines 1016-1028) - position these as the NEAR-MISS target before elite evolution. Players will feel 'almost there' for elite at 150 essence."
        },
        {
          "id": "FIX-4C",
          "recommendation": "Add 'Affordability Percent' display to shop items - show '78% of cost' or 'You have 150/200 (75%)'. This makes the near-miss feeling VISIBLE and builds anticipation."
        }
      ]
    },
    {
      "principle": "Variable Rewards",
      "rating": 8,
      "status": "PASS",
      "strengths": [
        "Milestone rewards vary significantly: +2 Essence, +10 Tokens, +50 Tokens, unlocks, evolution paths - not just '+10% production' (progression.md lines 717-813)",
        "Prestige introduces massive novelty: Entire world visually transforms (Corrupted Forest → Dark Swamp → Shadow Realm) - prestige.md lines 173-228",
        "Skill tree capstones produce dramatic visual effects (rainbow auras, golden crowns, connection lines) - skill-tree.md lines 257-274",
        "Boss drops are spectacular: 3 King Essence sprites with screen flash, particle explosion, achievement toast - currencies.md lines 624-680"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-5A",
          "problem": "Wave completion rewards are purely fixed (50 * waveNumber tokens) - currencies.md lines 445-473. This is entirely predictable with no surprise element. Every wave 5 completion is exactly +250 tokens, no variation."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-5A",
          "recommendation": "Add 'Wave Bonus Roll' - 20% chance for +50% bonus tokens on wave completion. This creates anticipation ('Will this wave be a lucky bonus wave?'). Show the bonus roll visually with a gold coin flip animation."
        }
      ]
    },
    {
      "principle": "Loss Aversion Balance",
      "rating": 8,
      "status": "PASS",
      "strengths": [
        "Prestige reset specification is crystal clear about what's lost vs. gained - prestige.md lines 15-20 (RESETS: 10 categories, PERSISTS: 7 categories, CHANGES: 6 visual transformations)",
        "First prestige reward is powerful: 50-100 genes for first prestige (prestige.md line 394 example), which buys Fast Start (5 genes) + Pen Discount (7 genes) + Token Boost (8 genes) = starting next run with 3 more slimes, cheaper pens, +25% passive tokens",
        "Prestige preview UI shows exact gene calculation - prestige.md lines 237-244",
        "Visual transformation makes it feel like a NEW experience, not a REPEAT - prestige.md lines 179-228 specify 4 distinct biomes with different backgrounds, enemy palettes, environment elements",
        "Run 2 is 2.5x faster than Run 1 (prestige.md lines 158-170) - acceleration overcomes loss aversion"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-6A",
          "problem": "No 'consolation prizes' mentioned. What if the player loses all their slimes right before prestige? The design should soften that edge case."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-6A",
          "recommendation": "Add 'Pity Timer' gene bonus: If player prestiges with <3 slimes, grant +10 bonus genes ('Gene: Insurance'). This softens the worst-case reset scenario and reduces loss aversion fear."
        }
      ]
    },
    {
      "principle": "Competence Building",
      "rating": 7,
      "status": "NEEDS WORK",
      "strengths": [
        "Skill tree choices reward planning - 6 documented build archetypes with clear tradeoffs - skill-tree.md lines 50-110",
        "Run 2 starts with gene bonuses that apply knowledge (immediate evolution access, cheaper pens) - prestige.md lines 628-654",
        "UI supports learning with tooltips, stats, comparisons - ui-ux.md lines 745-750",
        "Spatial/positioning decisions are rewarded (dragging slimes to respond to threats) - idea.md lines 9-11"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-7A",
          "problem": "No explicit 'aha moments' designed. The skill tree has synergies (skill-tree.md lines 113-117) but there are no 'discovery moments' where the player learns a non-obvious optimization through experimentation. The design TELLS the player everything upfront instead of letting them DISCOVER through play."
        },
        {
          "id": "ISSUE-7B",
          "problem": "Insufficient evidence that Run 2 feels strategically different. The gene bonuses are numeric (more slimes, faster generation) but don't clearly enable NEW strategies. Does learning from Run 1 make Run 2 strategically better, or just faster?"
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-7A",
          "recommendation": "Add hidden synergies that players must DISCOVER through experimentation. For example: 'Placing 3+ breeders in a triangle formation creates a 'Love Triangle' bonus that doubles baby production.' This creates 'aha!' moments when players accidentally discover it. Hide these in the design, don't document them."
        },
        {
          "id": "FIX-7B",
          "recommendation": "Add 'Strategy Tutorial' tooltips that appear in Run 2 based on Run 1 performance. Example: If player lost all slimes to wolves in Run 1, show tooltip in Run 2: 'Try keeping warriors between enemies and breeders - wolves target slimes, not the house.' Make learning VISIBLE and contextual."
        }
      ]
    },
    {
      "principle": "Visual Engagement",
      "rating": 9,
      "status": "PASS",
      "strengths": [
        "Canvas is always alive: Entities constantly moving (slimes bouncing, enemies spawning, projectiles flying, babies wandering, collectibles bobbing) - ui-ux.md lines 247-486 specify state machines for ALL entity types with constant animation",
        "Player actions have VISIBLE consequences: Drag slime = slime follows cursor with ghost preview (ui-ux.md line 160), click enemy = target reticle appears (line 166), click baby = burst animation + floating text (line 172), click charged slime = screen flash + area damage (line 184)",
        "Upgrades produce visible changes: Pen visibly grows on Canvas (progression.md line 391), slime evolution flash animation (line 393), elite transformation golden glow (line 395)",
        "Something dies or spawns constantly: Wave system spawns enemies every 2 seconds (progression.md line 957), breeder produces babies every 30 seconds (progression.md line 1020), death animations spawn collectibles (ui-ux.md lines 270-274)",
        "Death animations are satisfying: Spark particles, fade out, essence sprite spawn (ui-ux.md lines 300-305 for rancher slime, lines 380-384 for corrupted spider)",
        "Prestige visually transforms the world: 4 distinct biomes with different background colors, enemy palettes, environment elements (prestige.md lines 179-228)"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-8A",
          "problem": "Between wave intermissions (10 seconds) may create visual dead periods. Progression.md line 530 specifies '10-second break between waves' with enemies all defeated. During this time, what's moving on Canvas? Slimes are idle, no enemies, no babies spawning? This risks visual stagnation."
        },
        {
          "id": "ISSUE-8B",
          "problem": "No specification for 'idle animations' during peaceful periods. When slimes are in the pen with no enemies, do they just bounce in place? This gets monotonous. Need cute idle behaviors to keep the Canvas alive."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-8A",
          "recommendation": "During intermission, have slimes automatically do cute idle behaviors: play with toys, chase each other, groom each other, sleep. Keep the Canvas ALIVE even between waves. Add 'IdleBehavior' state to slime AI with random cute actions."
        },
        {
          "id": "FIX-8B",
          "recommendation": "Add ambient environmental life: Fireflies at night (prestige.md line 214 already mentions this for Dark Swamp, but add it to all tiers), birds flying overhead, butterflies, rustling grass. Keep the world visually busy even when gameplay is quiet."
        }
      ]
    },
    {
      "principle": "Is This Actually A Game?",
      "rating": 8,
      "status": "PASS",
      "30SecondTest": "Enemies pour from the forest edge as the player quickly clicks a shadow wolf to mark it priority. Two warrior slimes bounce toward it, leaving a gap on the right. The player drags a third warrior from the back pen to plug the hole, then spots a baby slime wandering toward the oncoming wave. She clicks it to collect, adding it to her inventory. A corrupted spider breaks through and lunges at a breeder slime—the player frantically drags the breeder to safety, then feeds a crystal essence to a nearby warrior, watching it flash and grow into an elite form with visible armor plates. The elite slimes slam into the wolf, defeating it as purple essence sprites float from its corpse. The player clicks the essence to collect, watching it sparkle toward her currency counter. (idea.md lines 75-76 - FULLY ACTIONABLE WITHOUT NUMBERS)",
      "canvasInteractionCheck": [
        "Drag slimes to reposition: CONSTANT interaction (every 5-10 seconds during waves)",
        "Click enemies to prioritize: FREQUENT interaction (every 3-5 seconds during waves)",
        "Click babies to collect: URGENT interaction (every 10-30 seconds when babies spawn)",
        "Click essence to collect: CONSTANT interaction (every 5-15 seconds after kills)",
        "Click charged slimes to activate abilities: STRATEGIC interaction (every 20-40 seconds when charged)",
        "Click food to feed slimes: TACTICAL interaction (every 30-60 seconds for evolution)",
        "Place structures from build panel: SPATIAL interaction (every 2-3 minutes for expansion)"
      ],
      "strengths": [
        "30-second gameplay description is PURE ACTION - zero mention of currencies, upgrades, or numbers (idea.md lines 75-76)",
        "Player interacts with Canvas directly through 7 distinct click/drag behaviors - ui-ux.md lines 156-198",
        "Moment-to-moment decisions: Every 5-10 seconds during waves, player chooses: 'Which enemy to prioritize?' 'Which slime to move?' 'Which baby to collect first?' 'Is this the right time to activate ability?'",
        "If you removed all upgrade panels and just left the Canvas, there would STILL be a recognizable tower defense game with positional tactics",
        "Bystander watching over shoulder would understand: 'Oh, you're defending the ranch from monsters by placing slimes and clicking to collect stuff'",
        "Player has AGENCY in the game world: Choices about WHERE to position slimes, WHICH enemies to target, WHEN to collect babies, WHAT to evolve - all affect outcomes"
      ],
      "issuesFound": [
        {
          "id": "ISSUE-9A",
          "problem": "While the game IS actually a game (passes the test), there's a risk that late-game becomes 'numbers-only' if the Canvas gameplay doesn't scale with difficulty. Wave 25+ with 100 slimes might become unmanageable micromanagement hell where the player just watches instead of actively playing. Need to ensure late-game remains playable, not just a spectacle."
        }
      ],
      "fixRecommendations": [
        {
          "id": "FIX-9A",
          "recommendation": "Add 'Auto-Formation' behavior at high slime counts (50+ slimes). Slimes automatically organize into defensive formations, reducing micromanagement load. Player can still override with manual positioning, but the game assists at scale. This keeps late-gate PLAYABLE, not just WATCHABLE."
        }
      ],
      "verdict": "YES - This is actually a game with meaningful Canvas gameplay. The incremental mechanics ENHANCE the core loop, not CREATE it."
    }
  ],
  "crossCuttingIssues": [
    {
      "issue": "The design EXCEEDS expectations on Canvas-first gameplay but UNDER-specifies late-game scaling. 100+ slimes (skill-tree.md line 258) with 50 enemies creates unmanageable micromanagement. Need auto-management systems that preserve agency while reducing click load.",
      "affectedPrinciples": [
        "Visual Engagement",
        "Is This Actually A Game?"
      ],
      "recommendation": "Add 'Squad System' - group 10 slimes into a squad that moves together. Player clicks squad leader, whole squad repositions. Reduces click count by 10x while preserving tactical positioning."
    },
    {
      "issue": "Cost curve tuning (pen upgrades, evolution costs) risks creating painful 'nothing affordable' dead zones. Near-miss frequency is good in theory but unproven in practice.",
      "affectedPrinciples": [
        "Near-Miss Frequency",
        "Reward Visibility"
      ],
      "recommendation": "Playtest cost curves with real players. Measure time-between-affordable-purchases. Target: Player should have something affordable every 60-90 seconds. If gaps exceed 120 seconds, smooth the curve."
    },
    {
      "issue": "Insufficient randomness makes the game TOO predictable. Players need surprise to maintain engagement over long sessions.",
      "affectedPrinciples": [
        "Agency vs. Randomness",
        "Variable Rewards"
      ],
      "recommendation": "Add 20-30% randomness to: spawn positions, baby wander directions, essence drop values, wave enemy composition. Keep core strategy deterministic but add tactical variance."
    }
  ],
  "missingDocumentCheck": {
    "idea.md": {
      "status": "Present",
      "includesVisualGameWorld": true,
      "includesEntityTypes": true,
      "notes": "Excellent - includes both Visual Game World (line 6) and Entity Types (line 17) with detailed specs"
    },
    "gdd/currencies.md": {
      "status": "Present (as currencies.json)",
      "includesGameplayEarnedSources": true,
      "notes": "EXCELLENT - all currencies earned through Canvas gameplay: baby collection (click), enemy kills (combat), wave completion (combat victory). No 'passive-only' currencies."
    },
    "gdd/progression.md": {
      "status": "Present (as progression.json)",
      "includesVisualEventTriggers": true,
      "notes": "STRONG - unlocks tied to visual events (wave completions, boss kills, first events) not just currency thresholds. Visual markers specified (lines 910-946)."
    },
    "gdd/prestige.md": {
      "status": "Present (as prestige.json)",
      "includesVisualTransformationSpec": true,
      "notes": "OUTSTANDING - visual transformation spec is comprehensive (lines 173-228). 4 distinct biomes with exact colors, palettes, environment elements. This is best-in-class."
    },
    "gdd/skill-tree.md": {
      "status": "Present (as skill-tree.json)",
      "includesVisibleCanvasEffects": true,
      "notes": "EXCELLENT - 100% of nodes have visible Canvas effect with 👁 VISUAL tag (line 532 in quality checklist). Every skill produces visible change on Canvas."
    },
    "gdd/ui-ux.md": {
      "status": "Present (as ui-ux.json)",
      "canvasIsPrimary": true,
      "bottomPanelLayout": true,
      "notes": "PERFECT - Canvas is 60-70% of screen (line 79), bottom panel is secondary and COLLAPSIBLE (line 201-210). Design philosophy explicitly states 'Canvas is the game' (line 1049). This is exactly correct."
    }
  },
  "priorityFixList": [
    {
      "priority": 1,
      "issueId": "ISSUE-4A",
      "fix": "Smooth pen upgrade cost curve from 4x jumps to 3x or add intermediate upgrade at 1000 tokens",
      "effort": "Low",
      "impact": "High"
    },
    {
      "priority": 2,
      "issueId": "ISSUE-2A",
      "fix": "Add baby escape emergency event at 6:30 to break dead zone",
      "effort": "Medium",
      "impact": "High"
    },
    {
      "priority": 3,
      "issueId": "ISSUE-1A",
      "fix": "Add build challenge scenarios that punish bad builds (Wave 8 anti-swarm, Wave 12 anti-elite)",
      "effort": "Medium",
      "impact": "High"
    },
    {
      "priority": 4,
      "issueId": "ISSUE-8A",
      "fix": "Add cute idle behaviors during wave intermissions to keep Canvas alive",
      "effort": "Low",
      "impact": "Medium"
    },
    {
      "priority": 5,
      "issueId": "ISSUE-1C",
      "fix": "Add tactical bonuses to Canvas zones (choke points, high ground) to make positioning matter",
      "effort": "Medium",
      "impact": "Medium"
    },
    {
      "priority": 6,
      "issueId": "ISSUE-5A",
      "fix": "Add wave bonus roll (20% chance for +50% tokens) to create anticipation",
      "effort": "Low",
      "impact": "Medium"
    },
    {
      "priority": 7,
      "issueId": "ISSUE-9A",
      "fix": "Add auto-formation behavior at high slime counts (50+) to reduce micromanagement",
      "effort": "High",
      "impact": "High"
    },
    {
      "priority": 8,
      "issueId": "ISSUE-1B",
      "fix": "Add 20-30% randomness to spawn positions, baby wander, essence drops",
      "effort": "Low",
      "impact": "Low"
    }
  ],
  "implementationNotesForPhase3": [
    "HIGHEST PRIORITY: Implement Canvas-first philosophy religiously. The bottom panel must NOT take over the screen. Upgrade panels are for BETWEEN WAVES, not DURING GAMEPLAY. During waves, the panel should be COLLAPSIBLE or the player should be discouraged from opening it.",
    "",
    "CRITICAL: Ensure slime dragging feels PHYSICAL. Add 'ghost sprite' following cursor, highlight valid drop zones in green, invalid in red. The drag should feel TACTILE - not just a teleport.",
    "",
    "VISUAL FEEDBACK IS EVERYTHING: Every player action must have BOTH Canvas feedback AND UI feedback. Click baby → burst particles on Canvas AND counter animation in UI. Kill enemy → death animation on Canvas AND essence pulse in UI. If you implement one without the other, it's incomplete.",
    "",
    "WAVE SYSTEM: Implement the wave spawn timing EXACTLY as specified (progression.md line 957: 2-second intervals). Stagger enemy spawns, not all at once. This creates tactical pacing opportunities.",
    "",
    "COST TUNING: Watch for 'desert periods' during playtesting. If player goes 2+ minutes without being able to afford ANYTHING, smooth the cost curve. The target is 60-90 seconds between affordable purchases.",
    "",
    "BOSS FIGHTS: Make Slime King spawns DRAMATIC (progression.md lines 424-468). 5-second warning, screen flash red, camera shake, 2-second spawn animation. This is a climax moment - make it feel EPIC.",
    "",
    "PRESTIGE TRANSITION: The fade-to-white transition (prestige.md lines 657-671) is CRITICAL for emotional impact. Take your time with this. 500ms fade out, 500ms fade in. Don't cut corners.",
    "",
    "SKILL TREE VISUALS: Every node MUST have a visible Canvas effect (skill-tree.md 👁 VISUAL tags). If you implement a skill without a visual change, it's incomplete. Fast slimes must bounce FASTER, not just have a stat boost.",
    "",
    "LATE-GAME SCALING: Test with 100 slimes on Canvas. If it becomes unmanageable, implement squad auto-grouping. The player should feel POWERFUL at 100 slimes, not OVERWHELMED.",
    "",
    "ESSENCE COLLECTION: Essence must be clicked to collect (currencies.md lines 372-405). Do NOT auto-collect. The clicking is CORE GAMEPLAY. Auto-collect is only for high-tier gene upgrade.",
    "",
    "BABY URGENCY: Baby slime escape timer (10 seconds) is CRITICAL (progression.md line 1067). This creates constant micro-tension. Make the timer VISIBLE - color bar turning red as time runs out.",
    "",
    "ENTITY SPAWN ANIMATIONS: All entities have spawn animations (ui-ux.md state machines). Scale 0→1 for slimes (400ms), enemies (300ms), collectibles (300-500ms). Don't just pop them in. The spawn animation feels POLISHED.",
    "",
    "PARTICLE EFFECTS: Implement the particle system early (ui-ux.md lines 969-977). Particles make EVERYTHING feel better. Enemy death, essence collection, boss defeat - all need particles. If you're short on time, particles > fancy UI.",
    "",
    "PRESTIGE VISUAL TRANSFORMATION: The 4 biomes MUST look NOTICEABLY different (prestige.md lines 179-228). Different background colors (blue→green vs. red→brown vs. purple→green vs. dark gray→red). If a bystander can't tell the prestige tier at a glance, it's not working.",
    "",
    "BALANCE TESTING: The most important balance number is 'time between affordable purchases'. Target: 60-90 seconds. If it's 30 seconds, game is too easy. If it's 180 seconds, players quit. Measure this early and often."
  ],
  "designPhilosophySummary": "This design succeeds where most generated incremental games fail: IT'S ACTUALLY A GAME. The Canvas is the star, not the numbers. The incremental mechanics ENHANCE the core gameplay loop (tower defense + tactical positioning) rather than REPLACE it. The visual-first philosophy (Canvas is 60-70% of screen, bottom panel is collapsible) is exactly correct. The prestige visual transformation system is best-in-class. However, the design needs specific fixes in three areas: (1) smooth the cost curve to eliminate desert periods, (2) add build challenge scenarios to make strategic choices matter, (3) add randomness for surprise. With these fixes, this goes from 'good' to 'excellent'."
}

Skill Tree

{
  "gameTitle": "Slime Rancher Defense - Skill Tree Design",
  "version": "1.0",
  "lastUpdated": "2025-02-07",
  "summary": "Complete skill tree system with 21 nodes across 3 branches, offering real build diversity with visible Canvas effects. Players earn Slime Points (SP) from waves and milestones, spend them on permanent upgrades for the current run, and can only afford ~50% of the tree per prestige run, forcing meaningful strategic choices.",
  "skillPointEconomy": {
    "diagram": "mermaid",
    "definition": "graph TD\n    subgraph \"Earning Slime Points (SP)\"\n        Src1[\"Wave Cleared\\n+1 SP per wave\\n~25 waves per run = ~25 SP\"]\n        Src2[\"Milestone Reached\\n+1 SP per milestone\\n~12 milestones = ~12 SP\"]\n        Src3[\"Boss Defeated\\n+3 SP per boss\\n~2-3 bosses per run = ~6-9 SP\"]\n    end\n\n    subgraph \"Total SP per Run\"\n        Total[\"~40-45 SP per run\\n(25 waves + 12 milestones + 9 boss)\\n~43 SP average\"]\n    end\n\n    subgraph \"Tree Cost\"\n        FullCost[\"Full Tree Cost: 81 SP\\nPlayer can afford: ~53%\\nForces meaningful choices\"]\n    end\n\n    subgraph \"Build Affordability\"\n        SingleBranch[\"Single Branch: 20-25 SP\\nCan fully max one branch\"]\n        TwoBranches[\"Two Branches: 50-60 SP\\nPartial two-branch build\"]\n        SynergyBuild[\"Synergy Build: 40-50 SP\\nKey nodes from two branches + synergies\"]\n    end\n\n    Src1 --> Total\n    Src2 --> Total\n    Src3 --> Total\n    Total --> FullCost\n    FullCost --> SingleBranch\n    FullCost --> TwoBranches\n    FullCost --> SynergyBuild\n\n    style Src1 fill:#C8E6C9\n    style Src2 fill:#A5D6A7\n    style Src3 fill:#81C784\n    style Total fill:#4CAF50,color:#FFF\n    style FullCost fill:#FFB74D",
    "description": "SP economy ensures players can only afford about half the tree per run, creating real strategic choices between single-branch focus, two-branch hybrid, or synergy builds.",
    "sources": {
      "waveCleared": {
        "sp": 1,
        "perWave": true,
        "estimatedTotal": 25,
        "trigger": "waveComplete event"
      },
      "milestone": {
        "sp": 1,
        "perMilestone": true,
        "estimatedTotal": 12,
        "trigger": "milestoneReached event"
      },
      "bossDefeated": {
        "sp": 3,
        "perBoss": true,
        "estimatedTotal": 9,
        "trigger": "slimeKingDeath event"
      }
    },
    "totalPerRun": 43,
    "fullTreeCost": 81,
    "affordabilityPercent": 53
  },
  "completeSkillTree": {
    "diagram": "mermaid",
    "definition": "graph TD\n    Root[\"🌟 Root Node\\nFree\\nEffect: Unlock skill tree access\\n👁 VISUAL: Skill tree tab appears\"]\n\n    subgraph \"Branch 1: Swarm Tactics [The Horde]\"\n        B1_1[\"⚡ Rapid Bounce\\nCost: 2 SP\\n+50% slime movement speed\\n👁 VISUAL: Faster bounce animation\"]\n        B1_2[\"⚡ Pack Tactics\\nCost: 3 SP\\n+1 damage per nearby slime (stack: 5)\\n👁 VISUAL: Slimes glow when grouped\"]\n        B1_3[\"⚡ Breeding Frenzy\\nCost: 4 SP\\n-50% baby production time\\n👁 VISUAL: Babies spawn faster, heart particles\"]\n        B1_4[\"⚡ Slime Split\\nCost: 5 SP\\nKilled slimes spawn 2 babies (30% chance)\\n👁 VISUAL: Death splits into smaller slimes\"]\n        B1_C[\"💫 CAPSTONE: Swarm Lord\\nCost: 8 SP\\nMax slime cap +30, all slimes +20% stats\\n👁 VISUAL: Massive slime army, rainbow auras\"]\n    end\n\n    subgraph \"Branch 2: Elite Warriors [The Titans]\"\n        B2_1[\"🔧 Thick Skin\\nCost: 2 SP\\n+30% slime HP\\n👁 VISUAL: Larger health bars visible\"]\n        B2_2[\"🔧 Heavy Hitter\\nCost: 3 SP\\n+50% slime damage\\n👁 VISUAL: Bigger attack particles\"]\n        B2_3[\"🔧 Regeneration\\nCost: 4 SP\\nSlimes heal 2% HP/sec when not in combat\\n👁 VISUAL: Green pulse on healing\"]\n        B2_4[\"🔧 Second Wind\\nCost: 5 SP\\nSlimes revive once with 30% HP (60s cooldown)\\n👁 VISUAL: Ghost flash on revive\"]\n        B2_C[\"💫 CAPSTONE: Immortal Guard\\nCost: 8 SP\\nElite slimes have 2x HP, permanent regeneration\\n👁 VISUAL: Golden glow, crown particle effect\"]\n    end\n\n    subgraph \"Branch 3: Ranch Economy [The Tycoon]\"\n        B3_1[\"💪 Bountiful Harvest\\nCost: 2 SP\\n+50% baby slime value (5→7-8 tokens)\\n👁 VISUAL: Bigger floating token numbers\"]\n        B3_2[\"💪 Auto-Ranch\\nCost: 3 SP\\nBabies auto-collect after 5 seconds\\n👁 VISUAL: Babies drift to counter automatically\"]\n        B3_3[\"💪 Essence Magnet\\nCost: 4 SP\\nEssence flies to cursor when within 80px\\n👁 VISUAL: Essence particles trail cursor\"]\n        B3_4[\"💪 Generous Spirit\\nCost: 5 SP\\nWave completion bonus +50% tokens\\n👁 VISUAL: Larger wave reward text\"]\n        B3_C[\"💫 CAPSTONE: Golden Ranch\\nCost: 8 SP\\nPassive +5 tokens/sec, all drops x1.5\\n👁 VISUAL: Gold sparkle particles everywhere\"]\n    end\n\n    subgraph \"Cross-Branch Synergies\"\n        X1[\"🔥 Synergy: War Economy\\nCost: 4 SP\\nRequires: Heavy Hitter + Bountiful Harvest\\nKills grant +2 tokens, +1 essence\\n👁 VISUAL: Gold + purple burst on kill\"]\n        X2[\"🔥 Synergy: Speed Demon\\nCost: 4 SP\\nRequires: Rapid Bounce + Thick Skin\\nFast slimes have +50% dodge chance\\n👁 VISUAL: Blur effect when dodging\"]\n        X3[\"🔥 Synergy: Legion\\nCost: 5 SP\\nRequires: Swarm Lord + Immortal Guard\\nEach slime gives all slimes +2% stats\\n👁 VISUAL: Connection lines between slimes\"]\n    end\n\n    Root --> B1_1 --> B1_2 --> B1_3 --> B1_4 --> B1_C\n    Root --> B2_1 --> B2_2 --> B2_3 --> B2_4 --> B2_C\n    Root --> B3_1 --> B3_2 --> B3_3 --> B3_4 --> B3_C\n    B2_2 & B3_1 -.->|\"requires both\"| X1\n    B1_1 & B2_1 -.->|\"requires both\"| X2\n    B1_C & B2_C -.->|\"requires both\"| X3",
    "description": "Complete 21-node skill tree with 3 branches (5 nodes each) + 3 cross-branch synergies. Every node has exact SP cost, clear effect, and visible Canvas impact marked with 👁 VISUAL tag. Capstones require full branch investment. Synergies create 'aha' moments for combining branches.",
    "totalNodes": 21,
    "totalCost": 81,
    "branchCount": 3,
    "synergyCount": 3
  },
  "buildArchetypes": [
    {
      "name": "Swarm Build",
      "branch": "Swarm Tactics",
      "playstyle": "Zerg-rush strategy with many weak slimes overwhelming enemies through numbers",
      "recommendedPath": "Rapid Bounce (2) → Pack Tactics (3) → Breeding Frenzy (4) → Slime Split (5) → Swarm Lord capstone (8)",
      "totalSP": 22,
      "canvasVisuals": "Screen filled with dozens of small slimes bouncing rapidly, grouped slimes glow with pack tactics, frequent baby spawns with heart particles, deaths split into new slimes, rainbow auras on capstone",
      "strengths": [
        "Can cover entire map",
        "Babies replenish losses quickly",
        "Pack tactics scales with slime count",
        "Capstone enables massive armies"
      ],
      "weaknesses": [
        "Individual slimes are weak",
        "Vulnerable to AoE attacks",
        "Requires active baby management",
        "Late-game elite enemies tough"
      ]
    },
    {
      "name": "Elite Build",
      "branch": "Elite Warriors",
      "playstyle": "Small number of powerful, durable slimes that tank and dominate through superior stats",
      "recommendedPath": "Thick Skin (2) → Heavy Hitter (3) → Regeneration (4) → Second Wind (5) → Immortal Guard capstone (8)",
      "totalSP": 22,
      "canvasVisuals": "Fewer but larger slimes with big health bars, heavy attack particles, green healing pulses between fights, ghost flashes on revives, golden glow with crowns on capstone",
      "strengths": [
        "Each slime is a powerhouse",
        "Regeneration sustains through waves",
        "Second Wind prevents losses",
        "Capstone makes near-unkillable"
      ],
      "weaknesses": [
        "Can't be everywhere at once",
        "Expensive to replace losses",
        "Struggles with swarming enemies",
        "Lower economy"
      ]
    },
    {
      "name": "Economy Build",
      "branch": "Ranch Economy",
      "playstyle": "Maximize resource generation to afford more slimes and upgrades, snowballing into mid-game dominance",
      "recommendedPath": "Bountiful Harvest (2) → Auto-Ranch (3) → Essence Magnet (4) → Generous Spirit (5) → Golden Ranch capstone (8)",
      "totalSP": 22,
      "canvasVisuals": "Bigger floating numbers on baby collection, babies auto-drift to counter, essence flies to cursor, massive wave completion rewards, gold sparkle particles everywhere with capstone",
      "strengths": [
        "Rapid resource accumulation",
        "Can afford more slimes faster",
        "Auto-collection reduces micro",
        "Capstone provides passive income"
      ],
      "weaknesses": [
        "Combat stats are weaker",
        "Early game is vulnerable",
        "Depends on surviving to mid-game",
        "Less direct combat power"
      ]
    },
    {
      "name": "Hybrid: War Economy",
      "branches": [
        "Elite Warriors (partial)",
        "Ranch Economy (partial)",
        "Synergy"
      ],
      "playstyle": "Combine elite combat power with economy bonuses, using the War Economy synergy for combat rewards",
      "recommendedPath": "Thick Skin (2) → Heavy Hitter (3) → Bountiful Harvest (2) → War Economy synergy (4)",
      "totalSP": 11,
      "canvasVisuals": "Durable slimes that hit hard, bigger token numbers on collection, gold+purple burst effects on every kill from synergy",
      "strengths": [
        "Balanced combat and economy",
        "Synergy rewards kills with resources",
        "Affordable early-mid game",
        "Sustainable snowball"
      ],
      "weaknesses": [
        "No capstone power",
        "Synergy costs extra SP",
        "Not specialized enough",
        "Mid-game plateau"
      ]
    },
    {
      "name": "Hybrid: Speed Demon",
      "branches": [
        "Swarm Tactics (partial)",
        "Elite Warriors (partial)",
        "Synergy"
      ],
      "playstyle": "Ultra-fast slimes with high dodge chance, kiting enemies and avoiding damage entirely",
      "recommendedPath": "Rapid Bounce (2) → Pack Tactics (3) → Thick Skin (2) → Speed Demon synergy (4)",
      "totalSP": 11,
      "canvasVisuals": "Extremely fast bouncing slimes that blur when dodging attacks, grouped slimes glow and attack rapidly, large health bars on durable fast units",
      "strengths": [
        "Dodge avoids damage entirely",
        "Speed enables hit-and-run",
        "Pack tactics benefits from mobility",
        "Very active playstyle"
      ],
      "weaknesses": [
        "High micro requirement",
        "Timing-intensive",
        "No late-game capstone",
        "Fails against undodgeable attacks"
      ]
    },
    {
      "name": "Hybrid: Legion",
      "branches": [
        "Swarm Tactics (full)",
        "Elite Warriors (full)",
        "Ultimate Synergy"
      ],
      "playstyle": "End-game build combining Swarm Lord and Immortal Guard capstones with Legion synergy for exponential scaling",
      "recommendedPath": "Full Swarm branch (22 SP) + Full Elite branch (22 SP) + Legion synergy (5 SP)",
      "totalSP": 49,
      "canvasVisuals": "Massive army of elite slimes with rainbow auras, golden crowns, green regeneration, connection lines between all slimes showing Legion synergy, each slime boosting all others exponentially",
      "strengths": [
        "Exponential stat scaling",
        "Best of both branches",
        "Ultimate late-game power",
        "Every slime is a god"
      ],
      "weaknesses": [
        "Extremely expensive (49 SP)",
        "Requires full prestige run",
        "No economy investment",
        "Overkill until late game"
      ]
    }
  ],
  "synergyMap": {
    "diagram": "mermaid",
    "definition": "graph TD\n    subgraph \"Synergy 1: War Economy\"\n        WE_nodes[\"Requires: Heavy Hitter (B2_2) + Bountiful Harvest (B3_1)\\nCost: 4 SP\\nEffect: Kills grant +2 tokens, +1 essence\\n👁 VISUAL: Gold + purple burst on kill\"]\n        WE_playstyle[\"Playstyle: Kill-focused combat\\nEvery kill is a resource drop\\nSustains economy through fighting\"]\n    end\n\n    subgraph \"Synergy 2: Speed Demon\"\n        SD_nodes[\"Requires: Rapid Bounce (B1_1) + Thick Skin (B2_1)\\nCost: 4 SP\\nEffect: Fast slimes have +50% dodge chance\\n👁 VISUAL: Blur effect when dodging\"]\n        SD_playstyle[\"Playstyle: Active kiting micro\\nSpeed avoids damage entirely\\nHit-and-run tactics\"]\n    end\n\n    subgraph \"Synergy 3: Legion\"\n        L_nodes[\"Requires: Swarm Lord (B1_C) + Immortal Guard (B2_C)\\nCost: 5 SP\\nEffect: Each slime gives all slimes +2% stats\\n👁 VISUAL: Connection lines between slimes\"]\n        L_playstyle[\"Playstyle: Exponential scaling\\nMore slimes = exponentially stronger\\nLate-game god army\"]\n    end\n\n    subgraph \"Anti-Synergies (Trap Combinations)\"\n        AS1[\"Swarm + Auto-Ranch (B3_2)\\nProblem: Too many babies to click\\nAuto-ranch helps but still chaotic\"]\n        AS2[\"Elite + Breeding Frenzy (B1_3)\\nProblem: Elite slimes can't breed\\nWasted node on sterile units\"]\n        AS3[\"Economy focus without combat\\nProblem: Can't survive to spend wealth\\nNeed minimal combat investment\"]\n    end\n\n    WE_nodes --> WE_playstyle\n    SD_nodes --> SD_playstyle\n    L_nodes --> L_playstyle\n\n    style WE_nodes fill:#FFE082\n    style SD_nodes fill:#CE93D8\n    style L_nodes fill:#F48FB1\n    style AS1 fill:#EF9A9A\n    style AS2 fill:#EF9A9A\n    style AS3 fill:#EF9A9A",
    "description": "Synergy map shows designed synergies (War Economy, Speed Demon, Legion) and anti-synergies (trap combinations that waste SP). Synergies reward thoughtful cross-branch investment, anti-synergies teach players about build coherence."
  },
  "skillNodeStateMachine": {
    "diagram": "mermaid",
    "definition": "stateDiagram-v2\n    [*] --> Locked: node not unlocked\n    Locked --> Available: prerequisites purchased\n    Available --> Available: player hovers (show preview)\n    Available --> Purchased: player spends SP\n    Purchased --> Active: effect applied to game\n\n    state Locked {\n        [*] --> hidden\n        note right of hidden\n            Visual: Grayed out, lock icon\n            Shows: Cost only\n            Hides: Effect details\n            Tooltip: \"Requires {prerequisite}\"\n        end note\n    }\n\n    state Available {\n        [*] --> preview\n        note right of preview\n            Visual: Highlighted border, pulse\n            Shows: Full effect + 👁 VISUAL preview\n            Tooltip: Cost + effect description\n            Can click to purchase\n        end note\n    }\n\n    state Purchased {\n        [*] --> active\n        note right of active\n            Visual: Filled color, glow\n            Connection lines lit\n            Effect: Applied immediately\n            Canvas: Visual change active\n            Cannot be undone (no respec)\n        end note\n    }\n\n    Active --> Reset: prestige triggered\n    Reset --> Locked: all nodes reset\n\n    note right of Reset\n        Prestige resets entire tree\n        All SP lost\n        Start fresh next run\n        Gene upgrades affect SP gain\n    end note",
    "description": "Node lifecycle from locked through available to purchased and active. No respec system—choices are permanent per run, adding weight to decisions. Prestige resets everything."
  },
  "skillEffectStateMachine": {
    "diagram": "mermaid",
    "definition": "stateDiagram-v2\n    [*] --> Inactive: node not purchased\n    Inactive --> Registered: node purchased\n    Registered --> Applied: effect registered in game systems\n\n    state Applied {\n        [*] --> StatModifier: if effect is stat change\n        [*] --> BehaviorChange: if effect changes behavior\n        [*] --> VisualChange: if effect is visual only\n        [*] --> NewMechanic: if effect unlocks new mechanic\n\n        StatModifier --> Recalculate: on slime spawn/update\n        BehaviorChange --> Recalculate: on slime AI tick\n        VisualChange --> Recalculate: on render frame\n        NewMechanic --> Recalculate: on trigger event\n    }\n\n    Recalculate --> Inactive: prestige resets tree\n    Recalculate --> Applied: tree persists (no prestige)\n\n    note right of StatModifier\n        Examples: attackSpeed *= 1.5, hp += 30%\n        Applied via multiplier stack\n        Visible in tooltip\n    end note\n\n    note right of BehaviorChange\n        Examples: autoCollectBabies, dodgeChance\n        Changes entity update() logic\n        Visible on Canvas immediately\n    end note\n\n    note right of VisualChange\n        Examples: glow, particle effects, animation speed\n        Applied via SpriteRenderer options\n        Player sees change on Canvas\n    end note\n\n    note right of NewMechanic\n        Examples: slimeSplit, secondWind\n        Adds new event handlers\n        Triggers on specific conditions\n    end note",
    "description": "How skill effects are applied and interact with game systems. Four effect types (stat, behavior, visual, mechanic) with different application timing."
  },
  "resetBehavior": {
    "resetsOnPrestige": true,
    "currency": "slimePoints",
    "respecAvailable": false,
    "justification": "Skill tree is a per-run strategic system that resets on prestige to allow players to explore different builds across multiple prestige runs. Gene upgrades from prestige can accelerate SP gain, making each run's skill tree progression faster. No respec because choices should be meaningful—players can try different builds in subsequent runs."
  },
  "exactFormulas": {
    "skillPointSources": {
      "waveCleared": "sp = 1 (per wave)",
      "milestoneReached": "sp = 1 (per milestone from progression.md)",
      "bossDefeated": "sp = 3 (per Slime King)"
    },
    "estimatedSPperRun": "waves (25) + milestones (12) + bosses (3*3=9) = ~46 SP",
    "nodeEffects": {
      "rapidBounce": "slimeMovementSpeed *= 1.5",
      "packTactics": "slimeDamage += (nearbySlimeCount * 1), maxStack: 5",
      "breedingFrenzy": "babyProductionInterval = baseInterval * 0.5",
      "slimeSplit": "onSlimeDeath: 30% chance spawn 2 babySlimes",
      "swarmLord": "slimeCap += 30, allSlimes: stats *= 1.2",
      "thickSkin": "slimeMaxHP *= 1.3",
      "heavyHitter": "slimeDamage *= 1.5",
      "regeneration": "if not in combat: slimeHP += (slimeMaxHP * 0.02) per second",
      "secondWind": "onSlimeDeath: 60s cooldown, revive with 30% HP once",
      "immortalGuard": "eliteSlimes: maxHP *= 2.0, regeneration = always active",
      "bountifulHarvest": "babySlimeValue = 5 * 1.5 = 7-8 tokens (rounded)",
      "autoRanch": "babyLifetime = 5.0, then autoCollect()",
      "essenceMagnet": "if distanceToCursor < 80px: essence.moveToCursor()",
      "generousSpirit": "waveRewardTokens *= 1.5",
      "goldenRanch": "passiveTokensPerSec += 5, allDropValues *= 1.5",
      "warEconomy": "onEnemyKill: tokens += 2, essence += 1",
      "speedDemon": "if movementSpeed > base: dodgeChance += 0.5",
      "legion": "eachSlime: allSlimes.stats *= (1 + slimeCount * 0.02)"
    }
  },
  "config": {
    "skillTree": {
      "unlockWave": 1,
      "resetsOnPrestige": true,
      "currency": "slimePoints",
      "pointSources": {
        "waveCleared": 1,
        "milestoneReached": 1,
        "bossDefeated": 3
      },
      "estimatedPointsPerRun": 46,
      "branches": {
        "swarmTactics": {
          "name": "Swarm Tactics",
          "icon": "⚡",
          "color": "#FF6B6B",
          "nodes": [
            {
              "id": "rapidBounce",
              "label": "Rapid Bounce",
              "cost": 2,
              "tier": 1,
              "requires": [],
              "effect": {
                "type": "stat",
                "target": "slimeMovementSpeed",
                "operation": "multiply",
                "value": 1.5
              },
              "visual": {
                "type": "animationSpeed",
                "description": "faster bounce animation"
              }
            },
            {
              "id": "packTactics",
              "label": "Pack Tactics",
              "cost": 3,
              "tier": 2,
              "requires": [
                "rapidBounce"
              ],
              "effect": {
                "type": "behavior",
                "target": "slimeDamage",
                "operation": "addStack",
                "value": 1,
                "maxStack": 5,
                "condition": "nearbySlimeCount"
              },
              "visual": {
                "type": "glow",
                "description": "slimes glow when grouped"
              }
            },
            {
              "id": "breedingFrenzy",
              "label": "Breeding Frenzy",
              "cost": 4,
              "tier": 3,
              "requires": [
                "packTactics"
              ],
              "effect": {
                "type": "behavior",
                "target": "babyProductionInterval",
                "operation": "multiply",
                "value": 0.5
              },
              "visual": {
                "type": "particle",
                "description": "heart particles on baby spawn"
              }
            },
            {
              "id": "slimeSplit",
              "label": "Slime Split",
              "cost": 5,
              "tier": 4,
              "requires": [
                "breedingFrenzy"
              ],
              "effect": {
                "type": "unlock",
                "target": "slimeSplit",
                "operation": "addChance",
                "value": 0.3,
                "trigger": "onSlimeDeath"
              },
              "visual": {
                "type": "spawn",
                "description": "death splits into 2 babies"
              }
            },
            {
              "id": "swarmLord",
              "label": "Swarm Lord",
              "cost": 8,
              "tier": 5,
              "requires": [
                "slimeSplit"
              ],
              "isCapstone": true,
              "effect": {
                "type": "stat",
                "target": [
                  "slimeCap",
                  "allSlimeStats"
                ],
                "operation": [
                  "add",
                  "multiply"
                ],
                "value": [
                  30,
                  1.2
                ]
              },
              "visual": {
                "type": "aura",
                "description": "rainbow auras on all slimes"
              }
            }
          ]
        },
        "eliteWarriors": {
          "name": "Elite Warriors",
          "icon": "🔧",
          "color": "#4ECDC4",
          "nodes": [
            {
              "id": "thickSkin",
              "label": "Thick Skin",
              "cost": 2,
              "tier": 1,
              "requires": [],
              "effect": {
                "type": "stat",
                "target": "slimeMaxHP",
                "operation": "multiply",
                "value": 1.3
              },
              "visual": {
                "type": "scale",
                "description": "larger health bars"
              }
            },
            {
              "id": "heavyHitter",
              "label": "Heavy Hitter",
              "cost": 3,
              "tier": 2,
              "requires": [
                "thickSkin"
              ],
              "effect": {
                "type": "stat",
                "target": "slimeDamage",
                "operation": "multiply",
                "value": 1.5
              },
              "visual": {
                "type": "particle",
                "description": "bigger attack particles"
              }
            },
            {
              "id": "regeneration",
              "label": "Regeneration",
              "cost": 4,
              "tier": 3,
              "requires": [
                "heavyHitter"
              ],
              "effect": {
                "type": "behavior",
                "target": "slimeHP",
                "operation": "addPerSecond",
                "value": 0.02,
                "condition": "not in combat"
              },
              "visual": {
                "type": "pulse",
                "description": "green pulse on healing"
              }
            },
            {
              "id": "secondWind",
              "label": "Second Wind",
              "cost": 5,
              "tier": 4,
              "requires": [
                "regeneration"
              ],
              "effect": {
                "type": "unlock",
                "target": "slimeRevive",
                "operation": "add",
                "value": 1,
                "hpPercent": 0.3,
                "cooldown": 60
              },
              "visual": {
                "type": "flash",
                "description": "ghost flash on revive"
              }
            },
            {
              "id": "immortalGuard",
              "label": "Immortal Guard",
              "cost": 8,
              "tier": 5,
              "requires": [
                "secondWind"
              ],
              "isCapstone": true,
              "effect": {
                "type": "stat",
                "target": [
                  "eliteSlimeMaxHP",
                  "regeneration"
                ],
                "operation": [
                  "multiply",
                  "setActive"
                ],
                "value": [
                  2,
                  true
                ]
              },
              "visual": {
                "type": "glow",
                "description": "golden glow, crown particle effect"
              }
            }
          ]
        },
        "ranchEconomy": {
          "name": "Ranch Economy",
          "icon": "💪",
          "color": "#FFE66D",
          "nodes": [
            {
              "id": "bountifulHarvest",
              "label": "Bountiful Harvest",
              "cost": 2,
              "tier": 1,
              "requires": [],
              "effect": {
                "type": "stat",
                "target": "babySlimeValue",
                "operation": "multiply",
                "value": 1.5
              },
              "visual": {
                "type": "text",
                "description": "bigger floating token numbers"
              }
            },
            {
              "id": "autoRanch",
              "label": "Auto-Ranch",
              "cost": 3,
              "tier": 2,
              "requires": [
                "bountifulHarvest"
              ],
              "effect": {
                "type": "behavior",
                "target": "babyLifetime",
                "operation": "autoCollect",
                "value": 5
              },
              "visual": {
                "type": "movement",
                "description": "babies drift to counter automatically"
              }
            },
            {
              "id": "essenceMagnet",
              "label": "Essence Magnet",
              "cost": 4,
              "tier": 3,
              "requires": [
                "autoRanch"
              ],
              "effect": {
                "type": "behavior",
                "target": "essenceCollection",
                "operation": "magnet",
                "value": 80
              },
              "visual": {
                "type": "particle",
                "description": "essence particles trail cursor"
              }
            },
            {
              "id": "generousSpirit",
              "label": "Generous Spirit",
              "cost": 5,
              "tier": 4,
              "requires": [
                "essenceMagnet"
              ],
              "effect": {
                "type": "stat",
                "target": "waveRewardTokens",
                "operation": "multiply",
                "value": 1.5
              },
              "visual": {
                "type": "text",
                "description": "larger wave reward text"
              }
            },
            {
              "id": "goldenRanch",
              "label": "Golden Ranch",
              "cost": 8,
              "tier": 5,
              "requires": [
                "generousSpirit"
              ],
              "isCapstone": true,
              "effect": {
                "type": "stat",
                "target": [
                  "passiveTokensPerSec",
                  "allDropValues"
                ],
                "operation": [
                  "add",
                  "multiply"
                ],
                "value": [
                  5,
                  1.5
                ]
              },
              "visual": {
                "type": "particle",
                "description": "gold sparkle particles everywhere"
              }
            }
          ]
        }
      },
      "synergies": [
        {
          "id": "warEconomy",
          "label": "War Economy",
          "cost": 4,
          "requires": [
            "heavyHitter",
            "bountifulHarvest"
          ],
          "effect": {
            "type": "conditional",
            "target": [
              "tokens",
              "essence"
            ],
            "operation": "addOnKill",
            "value": [
              2,
              1
            ],
            "trigger": "onEnemyKill"
          },
          "visual": {
            "type": "particle",
            "description": "gold + purple burst on kill"
          }
        },
        {
          "id": "speedDemon",
          "label": "Speed Demon",
          "cost": 4,
          "requires": [
            "rapidBounce",
            "thickSkin"
          ],
          "effect": {
            "type": "conditional",
            "target": "dodgeChance",
            "operation": "add",
            "value": 0.5,
            "condition": "movementSpeed > base"
          },
          "visual": {
            "type": "blur",
            "description": "blur effect when dodging"
          }
        },
        {
          "id": "legion",
          "label": "Legion",
          "cost": 5,
          "requires": [
            "swarmLord",
            "immortalGuard"
          ],
          "effect": {
            "type": "scaling",
            "target": "allSlimeStats",
            "operation": "multiplyPerSlime",
            "value": 0.02,
            "description": "each slime gives all slimes +2% stats"
          },
          "visual": {
            "type": "connection",
            "description": "connection lines between slimes"
          }
        }
      ]
    }
  },
  "qualityChecklist": {
    "checkedItems": [
      "Total nodes: 21 (within 15-25 target)",
      "Player can afford ~53% of tree per run (within 40-70% target)",
      "3 clearly different build archetypes with distinct playstyles (Swarm, Elite, Economy)",
      "Each branch has a capstone node worth building toward",
      "3 cross-branch synergies designed (War Economy, Speed Demon, Legion)",
      "Every node has an exact effect formula in exactFormulas section",
      "21/21 nodes (100%) have visible Canvas effect with 👁 VISUAL tag",
      "Visual effects reference SpriteRenderer capabilities (glow, scale, animationSpeed, particle, palette)",
      "The complete tree diagram is renderable as HTML/CSS from the Mermaid spec",
      "The skill point economy math checks out (46 SP earned vs 81 SP total = 53% affordability)",
      "A developer can implement the entire skill tree from diagrams alone",
      "Skill effect state machine shows how effects are applied and reset",
      "CONFIG.skillTree spec has exact values for every node (id, cost, tier, requires, effect, visual)",
      "Effect types are categorized (stat/behavior/visual/unlock) with typed operations",
      "Visual effect types reference SpriteRenderer capabilities (glow, scale, animationSpeed, particle, text)",
      "Point sources and estimated points per run are specified in CONFIG (46 SP per run)",
      "6 build archetypes documented with recommended paths, SP costs, and Canvas visuals",
      "Synergy map shows designed synergies and anti-synergies",
      "Reset behavior specified (resets on prestige, no respec, justified)",
      "All formulas are exact and copy-pasteable for implementation"
    ]
  },
  "designPhilosophy": {
    "summary": "This skill tree is built around **visible build expression**—players SEE their strategy on the Canvas. The Swarm build fills the screen with bouncing slimes; the Elite build shows a few powerful golden warriors; the Economy build rains gold particles. Every node produces a visible change, not just invisible stat boosts.",
    "keyPrinciples": [
      "**Visible effects first**: 100% of nodes have visible Canvas impact. Fast slimes bounce faster, tough slimes have bigger health bars, economy builds have floating gold numbers everywhere.",
      "**Real tradeoffs**: With 46 SP earned and 81 SP total, players must choose. Full branch (22 SP) vs partial hybrid vs synergy investment. No 'I'll just get everything' problem.",
      "**Build archetypes**: Three clear playstyles—Swarm (zerg-rush numbers), Elite (few powerful units), Economy (resource snowball). Each has distinct Canvas identity.",
      "**Synergy rewards**: Cross-branch nodes create 'aha' moments. Speed Demon makes fast slimes dodging tanks. Legion combines two capstones for exponential scaling.",
      "**Prestige integration**: Tree resets on prestige, allowing experimentation across runs. Gene upgrades from prestige accelerate SP gain, making each run faster.",
      "**No respec, no regrets**: Permanent choices per run add weight. Failed build? Try different approach next prestige. Short run time (30 min) keeps frustration low."
    ],
    "whyPlayersInvest": [
      "**Visible expression**: Watch your build come to life on Canvas—rainbow auras, gold particles, fast dodges",
      "**Strategic depth**: Choose between quantity vs quality, economy vs combat, specialization vs hybrid",
      "**Synergy discovery**: Experiment with cross-branch combinations for powerful effects",
      "**Build mastery**: Perfect your favorite build across multiple prestiges",
      "**Canvas spectacle**: Late-game capstones turn the screen into a visual feast"
    ]
  }
}

Ui Ux

{
  "gameTitle": "Slime Rancher Defense - UI/UX Design",
  "version": "1.0",
  "lastUpdated": "2025-02-07",
  "summary": "Complete UI/UX layout specification for a Canvas-first action game where the game world occupies 60-70% of the screen. The player actively manages slimes by clicking and dragging on the Canvas, with upgrade panels in a collapsible bottom panel. Every UI element serves the gameplay—currency displays are always visible in the HUD, and feedback happens both on the Canvas (particles, animations, floating text) and in the UI (counter animations, notifications).",
  "overview": {
    "visualIdentity": "Slime Rancher Defense features a whimsical yet tense aesthetic—cute bouncy slimes against an escalating threat of corrupted enemies. The color palette uses vibrant saturated colors for player entities (bright blues, pinks, greens) and deep threatening colors for enemies (purples, blacks). The Canvas game world is the star of the show, occupying 60-70% of the viewport. UI panels use dark semi-transparent backgrounds that don't compete with the action. Gold highlights celebrate rewards and achievements, while danger colors (red, dark purple) signal threats and costs.",
    "colorScheme": "Dark theme by default—main background is deep forest green (#1a2e1a), panels are semi-transparent dark overlays with colored borders. Accent colors match the currencies: gold for Tokens (#FFD700), purple for Essence (#9B59B6), orange for King Essence (#FFA500), and green for Genes (#2ECC71). Text is light gray for readability.",
    "feelingEvoked": "Whimsical tension—between waves the ranch feels peaceful and productive, during enemy attacks the interface communicates urgency through red flash effects and damage numbers. The UI supports the player's role as both rancher (managing economy) and tactician (positioning defenders), making currency management and combat equally accessible.",
    "canvasPrimacy": "The Canvas IS the game. Player hands spend most of their time interacting with the Canvas—dragging slimes to reposition, clicking enemies to prioritize targets, clicking babies to collect them, clicking charged slimes to activate abilities. The bottom panel is for strategic decisions BETWEEN gameplay moments, not the main interaction loop. Upgrade panels are secondary overlays that enhance but don't replace the visual gameplay."
  },
  "colorPalette": {
    "background": {
      "primary": "#0f1a0f",
      "secondary": "#1a2e1a",
      "tertiary": "#2a4e2a",
      "canvas": "#1a2e1a"
    },
    "text": {
      "primary": "#e0e0e0",
      "secondary": "#a0a0a0",
      "muted": "#606060"
    },
    "accents": {
      "accent1": "#FFD700",
      "accent2": "#4FC3F7",
      "accent3": "#E040FB"
    },
    "status": {
      "success": "#4CAF50",
      "warning": "#FF9800",
      "danger": "#F44336",
      "prestige": "#E040FB"
    },
    "currencies": {
      "tokens": "#FFD700",
      "essence": "#9B59B6",
      "kingEssence": "#FFA500",
      "genes": "#2ECC71",
      "slimePoints": "#00BCD4"
    },
    "entities": {
      "rancherSlime": "#4A90E2",
      "breederSlime": "#FF69B4",
      "warriorSlime": "#E74C3C",
      "eliteSlime": "#FFD700",
      "corruptedSpider": "#6B4E8D",
      "shadowWolf": "#1a1a1a",
      "slimeKing": "#FFD700"
    }
  },
  "typography": {
    "fontFamily": "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
    "headings": {
      "weight": "600",
      "sizeRange": "18px - 24px"
    },
    "bodyText": {
      "weight": "400",
      "size": "14px"
    },
    "numbers": {
      "currencies": "monospace",
      "weight": "600"
    },
    "buttons": {
      "fontFamily": "inherit",
      "weight": "600",
      "size": "14px"
    }
  },
  "screenLayout": {
    "masterLayout": {
      "description": "Canvas-first layout with HUD overlay on top and collapsible upgrade panel at bottom",
      "asciiArt": "+--------------------------------------------------+\n|  [HUD Bar - currencies, rates, wave/round info]   |\n+--------------------------------------------------+\n|                                                    |\n|                                                    |\n|  [CANVAS - Main Game World]                       |\n|  (60-70% of screen height)                        |\n|  Animated sprites, entities, effects               |\n|  Background, terrain, game area                    |\n|                                                    |\n|                                                    |\n+--------------------------------------------------+\n|  [Bottom Panel - tabs for upgrades/skills/shop]    |\n|  (30-40% of screen height, collapsible)           |\n+--------------------------------------------------+"
    },
    "hudBar": {
      "position": "overlays top of screen",
      "height": "50px",
      "backgroundColor": "rgba(15, 26, 15, 0.9)",
      "elements": [
        {
          "name": "Tokens Display",
          "position": "left",
          "icon": "🪙",
          "content": "{amount} (+{rate}/s)",
          "behavior": "Number animation (300ms count-up), rate updates every second, pulses on new tokens earned"
        },
        {
          "name": "Essence Display",
          "position": "left-center",
          "icon": "💜",
          "content": "{amount}",
          "behavior": "Number animation, pulses on essence collected from Canvas"
        },
        {
          "name": "King Essence Display",
          "position": "center",
          "icon": "👑",
          "content": "{amount}/5",
          "behavior": "Dramatic animation on collection, screen flash, counter ticks slowly (1000ms per count)"
        },
        {
          "name": "Wave Counter",
          "position": "right-center",
          "content": "Wave {waveNumber}",
          "behavior": "Updates on wave change, brief pulse animation"
        },
        {
          "name": "Settings Button",
          "position": "right",
          "icon": "⚙️",
          "content": "gear icon",
          "behavior": "Opens settings modal"
        }
      ]
    },
    "gameWorldCanvas": {
      "dimensions": {
        "width": "responsive to available space",
        "height": "60-70% of viewport",
        "minHeight": "400px"
      },
      "background": "Linear gradient from sky blue (#87CEEB) to light green (#90EE90) - transforms with prestige tiers",
      "layers": [
        {
          "name": "background",
          "description": "Terrain, ground, sky, environment elements (grass, trees, forest edge)",
          "order": 1
        },
        {
          "name": "entities",
          "description": "All game sprites - slimes, enemies, buildings, projectiles",
          "order": 2
        },
        {
          "name": "effects",
          "description": "Damage numbers, death particles, ability effects, collectible drops",
          "order": 3
        },
        {
          "name": "hudOverlay",
          "description": "Health bars above entities, selection indicators, range circles, placement preview",
          "order": 4
        }
      ],
      "camera": {
        "type": "Fixed top-down view",
        "description": "Canvas shows full ranch area, no scrolling needed"
      },
      "clickInteractions": [
        {
          "name": "Drag Slime",
          "action": "Click and hold on slime to drag to new position",
          "visualFeedback": "Slime follows cursor with semi-transparent ghost, highlight valid drop zones",
          "gameplayEffect": "Reposition slime tactically (pull warrior to left flank, move breeder to safety)"
        },
        {
          "name": "Click Enemy to Prioritize",
          "action": "Click on enemy to mark as priority target",
          "visualFeedback": "Target reticle appears over enemy, nearby slimes glow to indicate targeting",
          "gameplayEffect": "Nearby slimes focus attacks on marked enemy"
        },
        {
          "name": "Click Baby Slime to Collect",
          "action": "Click wandering baby slime before escape timer expires",
          "visualFeedback": "Baby disappears with burst animation, floating +5 Tokens text",
          "gameplayEffect": "Add tokens to currency, remove baby from Canvas"
        },
        {
          "name": "Click Essence to Collect",
          "action": "Click dropped essence sprite from killed enemy",
          "visualFeedback": "Essence flies to currency counter with particle trail",
          "gameplayEffect": "Add essence to currency for evolution"
        },
        {
          "name": "Click Charged Slime to Activate Ability",
          "action": "Click on slime with glowing aura (charged ability ready)",
          "visualFeedback": "Screen flash, area damage animation, particles burst from slime",
          "gameplayEffect": "Activate special ability (area damage, stun, heal, etc.)"
        },
        {
          "name": "Click Food to Feed Slime",
          "action": "Click on food item in ranch, then click on slime to feed",
          "visualFeedback": "Food flies to slime, evolution flash animation, sprite transforms",
          "gameplayEffect": "Trigger slime evolution, stat boost, or special path unlock"
        },
        {
          "name": "Place Structure from Build Panel",
          "action": "Click structure in build panel, then click on Canvas to place",
          "visualFeedback": "Placement preview shows valid/invalid positions, green/red tint",
          "gameplayEffect": "Place toy or barrier at selected location"
        }
      ]
    },
    "bottomPanel": {
      "height": "30-40% of viewport",
      "collapsedHeight": "40px",
      "backgroundColor": "rgba(26, 46, 26, 0.95)",
      "layout": "+--------------------------------------------------+\n|  [Tab 1] [Tab 2] [Tab 3] [Tab 4] ...  [collapse] |\n+--------------------------------------------------+\n|                                                    |\n|  [Active Tab Content Area]                         |\n|  Upgrade cards, skill tree, prestige panel, etc.   |\n|                                                    |\n+--------------------------------------------------+",
      "collapseButton": {
        "icon": "▲",
        "position": "right edge of tab bar",
        "behavior": "Collapses panel to just tab bar, giving more Canvas space. Icon flips to ▼ when collapsed."
      }
    },
    "navigation": {
      "tabs": [
        {
          "id": "shop",
          "label": "Shop",
          "icon": "🛒",
          "unlockedAt": "waveComplete >= 1",
          "content": "Buy slimes, food, structures"
        },
        {
          "id": "upgrades",
          "label": "Upgrades",
          "icon": "⬆️",
          "unlockedAt": "waveComplete >= 3",
          "content": "Pen upgrades, structure upgrades"
        },
        {
          "id": "skills",
          "label": "Skills",
          "icon": "🌟",
          "unlockedAt": "waveComplete >= 5",
          "content": "Skill tree node purchases"
        },
        {
          "id": "prestige",
          "label": "Prestige",
          "icon": "✨",
          "unlockedAt": "bossesDefeated >= 1",
          "content": "Prestige confirmation and gene shop"
        }
      ],
      "tabAppearanceAnimation": "New tabs fade in from transparent to opaque over 500ms with a subtle scale animation (0.9 to 1.0). A golden glow pulses around the tab icon for 3 seconds when unlocked."
    }
  },
  "entityVisualSpecs": {
    "entityStateMachines": {
      "rancherSlime": {
        "name": "Rancher Slime (Player's Basic Unit)",
        "diagram": "stateDiagram-v2\n    [*] --> Spawning: created\n    Spawning --> Idle: spawn animation complete (400ms)\n    Idle --> Wandering: in pen, no enemies\n    Idle --> Combat: enemies detected nearby\n    Wandering --> Combat: enemies enter range\n    Combat --> Attacking: target in range\n    Combat --> Moving: moving toward target\n    Attacking --> Combat: attack cooldown\n    Attacking --> Dying: hp <= 0\n    Moving --> Attacking: in range of target\n    Combat --> Idle: all enemies defeated\n    Dying --> Dead: death animation (500ms)\n    Dead --> [*]: remove from Canvas\n\n    note right of Spawning\n        Animation: Scale 0→1 (400ms)\n        Position: Ranch house spawn point\n        Invulnerable: 200ms\n    end note\n\n    note right of Wandering\n        Random walk within pen bounds\n        Bounce animation: 0.5s period\n        Cute idle behavior\n    end note\n\n    note right of Combat\n        Active targeting mode\n        Moves toward nearest enemy\n        Auto-attacks when in range\n    end note"
      },
      "breederSlime": {
        "name": "Breeder Slime (Economy Unit)",
        "diagram": "stateDiagram-v2\n    [*] --> Spawning: created\n    Spawning --> Wandering: spawn complete\n    Wandering --> Producing: production timer (30s)\n    Producing --> Wandering: baby spawned\n    Wandering --> Dying: hp <= 0\n    Dying --> Dead: death animation (500ms)\n    Dead --> [*]: remove from Canvas\n\n    note right of Producing\n        Timer: 30 seconds (reduced by Breeding Frenzy skill)\n        Spawns: Baby slime at current position\n        Visual: Heart particle effect\n    end note"
      },
      "warriorSlime": {
        "name": "Warrior Slime (Combat Evolution)",
        "diagram": "stateDiagram-v2\n    [*] --> Spawning: created (evolution or purchase)\n    Spawning --> Idle: spawn complete\n    Idle --> Patrolling: in defensive trench\n    Patrolling --> Combat: enemies detected\n    Combat --> Attacking: target in range\n    Attacking --> Patrolling: no targets\n    Attacking --> Charging: ability charged (if unlocked)\n    Charging --> Attacking: ability activated\n    Attacking --> Dying: hp <= 0\n    Dying --> Dead: death animation (500ms)\n    Dead --> [*]: remove from Canvas\n\n    note right of Charging\n        Condition: Ability ready (if unlocked)\n        Visual: Golden glow aura\n        Player can click to activate\n    end note"
      },
      "corruptedSpider": {
        "name": "Corrupted Spider (Basic Enemy)",
        "diagram": "stateDiagram-v2\n    [*] --> PreSpawn: wave spawns\n    PreSpawn --> Spawning: spawn timer\n    Spawning --> Active: spawn animation (300ms)\n    Active --> Moving: spawn complete\n    Moving --> Attacking: slime in range\n    Moving --> Moving: moving toward ranch house\n    Attacking --> Moving: no targets in range\n    Attacking --> Dying: hp <= 0\n    Moving --> Dying: killed by slime\n    Dying --> DropReward: death animation starts\n    DropReward --> Dead: reward spawned\n    Dead --> [*]: remove from Canvas\n\n    note right of DropReward\n        Essence sprite spawns at death position\n        Value: 2 essence (modified by genes/wave)\n        Lifetime: 8 seconds\n        Player must click to collect\n    end note"
      },
      "shadowWolf": {
        "name": "Shadow Wolf (Elite Enemy)",
        "diagram": "stateDiagram-v2\n    [*] --> PreSpawn: wave spawns (wave 5+)\n    PreSpawn --> Dashing: spawn + dash immediately\n    Dashing --> Attacking: slime in range\n    Attacking --> Stunned: attack complete\n    Stunned --> Dashing: recovery complete\n    Attacking --> Dying: hp <= 0\n    Dying --> DropReward: death animation\n    DropReward --> Dead: shadow essence spawned\n    Dead --> [*]: remove from Canvas\n\n    note right of DropReward\n        Shadow Essence sprite (purple-black)\n        Value: 5 essence\n        Lifetime: 8 seconds\n        Higher reward than spider\n    end note"
      },
      "slimeKing": {
        "name": "Slime King (Mini-Boss)",
        "diagram": "stateDiagram-v2\n    [*] --> PreSpawn: Wave 10 starts\n    PreSpawn --> Warning: 5-second warning\n    Warning --> Spawning: countdown complete\n    Spawning --> Entering: spawn animation (2000ms)\n    Entering --> Active: boss fully spawned\n    Active --> MinionSpawn: every 10 seconds\n    Active --> Attacking: slimes in range\n    Active --> Moving: moving toward house\n    Attacking --> Active: attack cooldown\n    MinionSpawn --> Active: minions spawned\n    Attacking --> Dying: hp <= 0\n    Dying --> EpicDeath: death animation (2000ms)\n    EpicDeath --> DropRewards: animation complete\n    DropRewards --> [*]: 3 King Essence spawned\n\n    note right of Warning\n        UI: \"BOSS INCOMING!\"\n        Screen flash red\n        Camera shake\n    end note"
      },
      "projectile": {
        "name": "Slime Projectile",
        "diagram": "stateDiagram-v2\n    [*] --> Spawning: slime attacks\n    Spawning --> Flying: spawn complete\n    Flying --> Impact: hit enemy or edge\n    Flying --> Expired: lifetime exceeded (2s)\n    Impact --> [*]: spawn hit effect\n    Expired --> [*]: fade out\n\n    note right of Spawning\n        Spawns from attacking slime\n        Position: slime position\n        Direction: toward target\n    end note"
      },
      "collectible": {
        "name": "Collectible (Baby/Essence/King Essence)",
        "diagram": "stateDiagram-v2\n    [*] --> Spawning: producer triggers\n    Spawning --> Active: spawn animation\n    Active --> Active: waiting for collection\n    Active --> Collected: player clicks\n    Active --> Expired: lifetime elapses\n    Collected --> [*]: reward added, despawn\n    Expired --> [*]: fade out, lost\n\n    note right of Spawning\n        Baby: Breeder production (30s)\n        Essence: Enemy death\n        King Essence: Boss death (3 sprites)\n        Animation: Pop in (300-500ms)\n    end note\n\n    note right of Active\n        Bob animation (amplitude varies)\n        Glow effect (enabled)\n        Lifetime countdown (visible timer)\n        Click radius varies by type\n    end note\n\n    note right of Collected\n        Immediate reward\n        Floating text at position\n        Particle burst\n        Counter animation\n        Despawn instantly\n    end note"
      }
    },
    "entityInteractionDiagram": {
      "description": "Shows how entities interact with each other on the Canvas",
      "diagram": "flowchart LR\n    subgraph Player_Entities\n        Unit[\"Player Slime\\n(attacks enemies)\"]\n        Structure[\"Structure\\n(produces/defends)\"]\n        Projectile[\"Projectile\\n(deals damage)\"]\n    end\n    subgraph Enemy_Entities\n        Enemy[\"Enemy\\n(attacks player entities)\"]\n        Boss[\"Boss\\n(stronger enemy)\"]\n    end\n    subgraph Collectibles\n        Drop[\"Resource Drop\\n(clickable)\"]\n    end\n\n    Unit -->|\"spawns\"| Projectile\n    Projectile -->|\"hits\"| Enemy\n    Projectile -->|\"hits\"| Boss\n    Enemy -->|\"attacks\"| Structure\n    Enemy -->|\"attacks\"| Unit\n    Boss -->|\"attacks\"| Structure\n    Enemy -->|\"on death → spawns\"| Drop\n    Boss -->|\"on death → spawns\"| Drop\n    Structure -->|\"produces\"| Drop\n    Drop -->|\"player clicks → collect\"| Unit"
    },
    "configEntities": {
      "rancherSlime": {
        "sprite": "slime",
        "colorVariant": "blue",
        "scale": 2,
        "team": "player",
        "hp": 50,
        "damage": 5,
        "attackSpeed": 1,
        "attackRange": 60,
        "moveSpeed": 30,
        "states": {
          "idle": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 500
          },
          "wandering": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 500
          },
          "moving": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 200
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 100,
            "spawnsProjectile": true
          },
          "dying": {
            "type": "fadeOut",
            "duration": 500,
            "particles": "spark",
            "particleCount": 5
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 400
          }
        },
        "healthBar": {
          "show": true,
          "width": 30,
          "height": 3,
          "yOffset": -8,
          "color": "#4A90E2"
        },
        "flipX": true
      },
      "breederSlime": {
        "sprite": "slime",
        "colorVariant": "pink",
        "scale": 1.8,
        "team": "player",
        "hp": 30,
        "damage": 0,
        "moveSpeed": 20,
        "states": {
          "idle": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 600
          },
          "wandering": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 600
          },
          "producing": {
            "type": "glow",
            "color": "#FF69B4",
            "duration": 1000
          },
          "dying": {
            "type": "fadeOut",
            "duration": 500,
            "particles": "spark",
            "particleCount": 5
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 400
          }
        },
        "healthBar": {
          "show": true,
          "width": 25,
          "height": 3,
          "yOffset": -6,
          "color": "#FF69B4"
        },
        "productionInterval": 30
      },
      "warriorSlime": {
        "sprite": "slime",
        "colorVariant": "red",
        "scale": 2.5,
        "team": "player",
        "hp": 100,
        "damage": 15,
        "attackSpeed": 1,
        "attackRange": 50,
        "moveSpeed": 25,
        "states": {
          "idle": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 500
          },
          "patrolling": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 250
          },
          "moving": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 200
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 100,
            "spawnsProjectile": true
          },
          "charging": {
            "type": "glow",
            "color": "#FFD700",
            "duration": 2000
          },
          "dying": {
            "type": "fadeOut",
            "duration": 500,
            "particles": "spark",
            "particleCount": 8
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 400
          }
        },
        "healthBar": {
          "show": true,
          "width": 35,
          "height": 4,
          "yOffset": -10,
          "color": "#E74C3C"
        },
        "flipX": true
      },
      "eliteSlime": {
        "sprite": "slime",
        "colorVariant": "gold",
        "scale": 3,
        "team": "player",
        "hp": 250,
        "damage": 40,
        "attackSpeed": 1.2,
        "attackRange": 60,
        "moveSpeed": 25,
        "states": {
          "idle": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 400
          },
          "moving": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 150
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 80,
            "spawnsProjectile": true
          },
          "charging": {
            "type": "glow",
            "color": "#FFD700",
            "duration": 1500
          },
          "dying": {
            "type": "fadeOut",
            "duration": 800,
            "particles": "spark",
            "particleCount": 15
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 600
          }
        },
        "healthBar": {
          "show": true,
          "width": 40,
          "height": 5,
          "yOffset": -12,
          "color": "#FFD700"
        },
        "flipX": true,
        "glow": true
      },
      "corruptedSpider": {
        "sprite": "slime",
        "colorVariant": "darkPurple",
        "scale": 1.5,
        "stretchX": 1.3,
        "team": "enemy",
        "hp": 30,
        "damage": 5,
        "moveSpeed": 30,
        "reward": {
          "essence": 2
        },
        "states": {
          "moving": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 200
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 150
          },
          "dying": {
            "type": "fadeOut",
            "duration": 400,
            "particles": "spark",
            "particleCount": 5,
            "spawnCollectible": "essence"
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 300
          }
        },
        "healthBar": {
          "show": true,
          "width": 25,
          "height": 3,
          "yOffset": -6,
          "color": "#F44336"
        }
      },
      "shadowWolf": {
        "sprite": "ghost",
        "colorVariant": "black",
        "scale": 2,
        "team": "enemy",
        "hp": 50,
        "damage": 10,
        "moveSpeed": 60,
        "reward": {
          "essence": 5
        },
        "states": {
          "dashing": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 100
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 100
          },
          "stunned": {
            "type": "glow",
            "color": "#FF0000",
            "duration": 500
          },
          "dying": {
            "type": "fadeOut",
            "duration": 600,
            "particles": "spark",
            "particleCount": 8,
            "spawnCollectible": "essence"
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 300
          }
        },
        "healthBar": {
          "show": true,
          "width": 30,
          "height": 3,
          "yOffset": -8,
          "color": "#F44336"
        }
      },
      "slimeKing": {
        "sprite": "slime",
        "colorVariant": "gold",
        "scale": 6,
        "team": "enemy",
        "hp": 500,
        "damage": 20,
        "moveSpeed": 15,
        "reward": {
          "kingEssence": 3
        },
        "states": {
          "entering": {
            "type": "scaleIn",
            "duration": 2000
          },
          "moving": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 400
          },
          "attacking": {
            "frames": [
              2,
              3
            ],
            "frameDuration": 200
          },
          "minionSpawn": {
            "type": "glow",
            "color": "#FFD700",
            "duration": 1000
          },
          "dying": {
            "type": "fadeOut",
            "duration": 2000,
            "particles": "spark",
            "particleCount": 30,
            "spawnCollectible": "kingEssence"
          },
          "spawning": {
            "type": "scaleIn",
            "duration": 2000
          }
        },
        "healthBar": {
          "show": true,
          "width": 80,
          "height": 8,
          "yOffset": -20,
          "color": "#FFD700"
        },
        "glow": true
      },
      "projectile": {
        "sprite": "fireball",
        "scale": 1.5,
        "speed": 200,
        "pierceCount": 1,
        "lifetime": 2,
        "states": {
          "flying": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 50
          },
          "impact": {
            "type": "burst",
            "duration": 200,
            "particles": "spark",
            "particleCount": 3
          }
        }
      },
      "babySlime": {
        "sprite": "slime",
        "colorVariant": "pink",
        "scale": 0.8,
        "lifetime": 10,
        "collectRadius": 18,
        "value": 5,
        "currency": "tokens",
        "states": {
          "spawning": {
            "type": "scaleIn",
            "duration": 400
          },
          "wandering": {
            "frames": [
              0,
              1
            ],
            "frameDuration": 500
          },
          "collected": {
            "type": "burst",
            "duration": 200,
            "particles": "spark",
            "particleCount": 5
          },
          "expired": {
            "type": "fadeOut",
            "duration": 500
          }
        }
      },
      "essence": {
        "sprite": "crystal",
        "colorVariant": "purple",
        "scale": 1,
        "lifetime": 8,
        "collectRadius": 20,
        "value": "variable",
        "currency": "essence",
        "states": {
          "spawning": {
            "type": "scaleIn",
            "duration": 300
          },
          "idle": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 100
          },
          "collected": {
            "type": "burst",
            "duration": 200,
            "particles": "spark",
            "particleCount": 5
          },
          "expired": {
            "type": "fadeOut",
            "duration": 500
          }
        },
        "glow": true
      },
      "kingEssence": {
        "sprite": "slime",
        "colorVariant": "gold",
        "scale": 2,
        "lifetime": 15,
        "collectRadius": 25,
        "value": 1,
        "currency": "kingEssence",
        "states": {
          "spawning": {
            "type": "scaleIn",
            "duration": 500
          },
          "idle": {
            "frames": [
              0,
              1,
              2,
              3
            ],
            "frameDuration": 150
          },
          "collected": {
            "type": "burst",
            "duration": 300,
            "particles": "spark",
            "particleCount": 10
          },
          "expired": {
            "type": "fadeOut",
            "duration": 1000
          }
        },
        "glow": true,
        "screenFlash": true
      }
    }
  },
  "hudOverlay": {
    "elements": [
      {
        "name": "Entity Health Bars",
        "position": "Above each entity",
        "content": "Small colored bar",
        "behavior": "Updates with damage, fades on death, color-coded by team (blue/red)"
      },
      {
        "name": "Floating Damage Numbers",
        "position": "At hit location",
        "content": "\"-15\" in red/white",
        "behavior": "Float upward, fade over 800ms, different colors for damage types"
      },
      {
        "name": "Wave Indicator",
        "position": "Top center of canvas",
        "content": "\"Wave 5 incoming!\"",
        "behavior": "Appears 2s before wave, fades after wave starts"
      },
      {
        "name": "Spawn Indicators",
        "position": "At spawn points (forest edge)",
        "content": "Pulsing circle",
        "behavior": "Shows where enemies will appear, increases intensity as wave countdown progresses"
      },
      {
        "name": "Selection Indicators",
        "position": "Around selected entity",
        "content": "Gold ring/circle",
        "behavior": "Appears when slime is clicked/dragged, shows range circle for warriors"
      },
      {
        "name": "Priority Target Marker",
        "position": "Around marked enemy",
        "content": "Red target reticle",
        "behavior": "Player clicked enemy to prioritize, nearby slimes glow indicating they're targeting"
      },
      {
        "name": "Escape Timer (Baby Slime)",
        "position": "Above baby slime",
        "content": "Countdown bar or number",
        "behavior": "Shows remaining lifetime (10s), changes color from green to red as time runs out"
      },
      {
        "name": "Charged Ability Indicator",
        "position": "Around charged slime",
        "content": "Glowing aura",
        "behavior": "Pulses when ability ready, player can click to activate"
      },
      {
        "name": "Placement Preview",
        "position": "Under cursor during structure placement",
        "content": "Semi-transparent structure sprite",
        "behavior": "Green tint for valid placement, red tint for invalid (blocked/out of bounds)"
      }
    ]
  },
  "bottomPanelTabs": {
    "shopTab": {
      "name": "Shop Tab",
      "layout": "+---------------------------------------+\n|  [Slimes]  [Food]  [Structures]            |\n+---------------------------------------+\n|  +--------+  +--------+  +--------+      |\n|  |Rancher |  |Breeder |  |Warrior |      |\n|  |  20🪙  |  |  50🪙  |  | 100🪙  |      |\n|  +--------+  +--------+  +--------+      |\n+---------------------------------------+",
      "sections": [
        {
          "name": "Slimes",
          "items": [
            {
              "id": "rancherSlime",
              "name": "Rancher Slime",
              "icon": "💧",
              "cost": {
                "tokens": 20
              },
              "description": "Basic combat unit, bouncy attacks",
              "states": {
                "locked": {
                  "visible": true,
                  "name": "Rancher Slime",
                  "icon": "💧",
                  "cost": "20 🪙",
                  "description": "???",
                  "action": "disabled"
                },
                "available": {
                  "icon": "💧",
                  "cost": "20 🪙",
                  "action": "enabled"
                },
                "affordable": {
                  "border": "#4CAF50",
                  "buttonColor": "#4CAF50",
                  "buttonText": "BUY"
                },
                "cannotAfford": {
                  "border": "#606060",
                  "buttonColor": "#606060",
                  "costColor": "#F44336",
                  "buttonText": "NEED 20 🪙"
                }
              }
            },
            {
              "id": "breederSlime",
              "name": "Breeder Slime",
              "icon": "💗",
              "cost": {
                "tokens": 50
              },
              "unlockedAt": "tokens >= 50",
              "description": "Economy unit, produces baby slimes"
            },
            {
              "id": "warriorSlime",
              "name": "Warrior Slime",
              "icon": "⚔️",
              "cost": {
                "tokens": 100
              },
              "unlockedAt": "tokens >= 100",
              "description": "Combat evolution, high damage"
            }
          ]
        },
        {
          "name": "Food",
          "items": [
            {
              "id": "basicFood",
              "name": "Essence Food",
              "icon": "💎",
              "cost": {
                "tokens": 10
              },
              "output": {
                "essence": 5
              },
              "description": "Convert tokens to essence"
            }
          ]
        },
        {
          "name": "Structures",
          "items": [
            {
              "id": "toyStructure",
              "name": "Slime Toy",
              "icon": "🧸",
              "cost": {
                "tokens": 50
              },
              "description": "Boosts breeding speed"
            },
            {
              "id": "barrierStructure",
              "name": "Barrier",
              "icon": "🧱",
              "cost": {
                "tokens": 150
              },
              "description": "Blocks enemy movement"
            }
          ]
        }
      ]
    },
    "upgradesTab": {
      "name": "Upgrades Tab",
      "layout": "+---------------------------------------+\n|  [Pen Upgrades]  [Ability Unlocks]       |\n+---------------------------------------+\n|  +----------------------------------+   |\n|  | Pen Level 1        [UPGRADE]      |   |\n|  | Cost: 100 🪙                      |   |\n|  | Effect: Capacity 5→10, +1🪙/s     |   |\n|  +----------------------------------+   |\n+---------------------------------------+",
      "sections": [
        {
          "name": "Pen Upgrades",
          "items": [
            {
              "id": "penLevel1",
              "name": "Pen Expansion Level 1",
              "cost": {
                "tokens": 100
              },
              "unlockedAt": "waveComplete >= 3",
              "effect": "Capacity 5→10 slimes, +1 Token/sec",
              "visualChange": "Pen visibly grows on Canvas"
            },
            {
              "id": "penLevel2",
              "name": "Pen Expansion Level 2",
              "cost": {
                "tokens": 500
              },
              "requires": "penLevel1",
              "effect": "Capacity 10→20 slimes, +3 Tokens/sec",
              "visualChange": "Pen doubles in size on Canvas"
            },
            {
              "id": "penLevel3",
              "name": "Nursery Zone",
              "cost": {
                "tokens": 2000
              },
              "requires": "penLevel2",
              "effect": "Capacity 20→40 slimes, +10 Tokens/sec, unlocks nursery zone",
              "visualChange": "New area appears on Canvas for baby slimes"
            }
          ]
        }
      ]
    },
    "skillsTab": {
      "name": "Skills Tab (Skill Tree)",
      "layout": "+---------------------------------------+\n|         [SKILL TREE]                  |\n|  +----+     +----+     +----+        |\n|  | B1 | --> | B2 | --> | B3 | ...     |\n|  +----+     +----+     +----+        |\n|                                      |\n|  Current SP: 25    SP/s: +1.2        |\n+---------------------------------------+",
      "description": "Interactive skill tree visualization with nodes and connections",
      "rendering": {
        "layout": "CSS Grid or absolute positioning",
        "nodeSize": "60x60px",
        "connections": "SVG lines or CSS borders",
        "nodeStates": {
          "locked": {
            "background": "#2a2a2a",
            "border": "#606060",
            "icon": "🔒"
          },
          "available": {
            "background": "#3a3a3a",
            "border": "#FFD700",
            "icon": "skill icon",
            "pulse": true
          },
          "purchased": {
            "background": "#1a4a1a",
            "border": "#4CAF50",
            "icon": "skill icon",
            "glow": true
          },
          "affordable": {
            "border": "#4CAF50",
            "button": "BUY"
          },
          "cannotAfford": {
            "border": "#F44336",
            "cost": "red"
          }
        }
      }
    },
    "prestigeTab": {
      "name": "Prestige Tab",
      "layout": "+---------------------------------------+\n|           ⟳ PRESTIGE                   |\n|                                      |\n|  You will earn: 60 🧬                |\n|  Current total: 5 👑                 |\n|  New total: 60 🧬                    |\n|                                      |\n|  RESETS:                             |\n|  - All slimes                        |\n|  - Tokens, Essence, King Essence     |\n|  - Pen upgrades                      |\n|                                      |\n|  KEEPS:                              |\n|  - Genes (permanent currency)        |\n|  - Gene upgrades                     |\n|  - Achievements                      |\n|                                      |\n|  VISUAL CHANGE:                      |\n|  - World transforms to Corrupted     |\n|    Forest (red-shifted background)   |\n|  - Enemies get new color palette     |\n|  - Ranch house upgrades visually     |\n|                                      |\n|  [CANCEL]        [PRESTIGE NOW]      |\n+---------------------------------------+",
      "unlockedAt": "bossesDefeated >= 1",
      "minKingEssence": 5
    }
  },
  "componentSpecifications": {
    "upgradeCard": {
      "layout": "+----------------------------------+\n|  [Icon]  [Upgrade Name]    [Lvl]  |\n|  [Description text]               |\n|  [Effect: +X damage / +Y speed]    |\n|  [Cost: 150 Gold]  [BUY button]   |\n+----------------------------------+",
      "states": {
        "affordable": {
          "borderColor": "#4CAF50",
          "buttonColor": "#4CAF50",
          "buttonText": "BUY",
          "textColor": "#e0e0e0"
        },
        "cannotAfford": {
          "borderColor": "#606060",
          "buttonColor": "#606060",
          "buttonText": "NEED 150 🪙",
          "costColor": "#F44336",
          "textColor": "#a0a0a0"
        },
        "maxed": {
          "borderColor": "#FFD700",
          "badge": "MAX",
          "button": "hidden",
          "glow": true
        },
        "locked": {
          "entireCard": "dimmed, opacity 0.5",
          "name": "???",
          "icon": "🔒",
          "description": "hidden",
          "noDetails": true
        },
        "hoverAffordable": {
          "highlight": "subtle scale 1.05",
          "showTooltip": true
        },
        "clickAffordable": {
          "purchaseAnimation": "flash white 200ms",
          "numberTickUp": "currency count animates",
          "satisfaction": "haptic feedback (if available), sound effect"
        },
        "clickCannotAfford": {
          "shakeAnimation": "horizontal shake 20ms x3",
          "costFlash": "cost flashes red briefly"
        }
      }
    },
    "currencyDisplay": {
      "layout": "[Icon] 1,234.5 (+12.3/s)",
      "numberAnimation": "Count-up animation 300ms when value changes",
      "rateDisplay": "Per-second rate in smaller text, updates every second",
      "largeNumbers": "Switch to K/M/B/T suffixes at 1,000 / 1,000,000 / 1,000,000,000 / 1,000,000,000,000",
      "color": "Match accent color for currency type",
      "earnedByGameplayFlash": "Brief glow/pulse when currency earned from defeating enemies or completing waves, distinct from passive income ticks"
    },
    "milestoneToast": {
      "layout": "+----------------------------------+\n|  ★ [Achievement Name]!            |\n|  [Description]  [+Reward]         |\n+----------------------------------+",
      "appearance": "Slide in from right",
      "duration": "3-5 seconds",
      "stackBehavior": "Multiple toasts stack vertically, max 3 visible"
    },
    "skillTreeRenderer": {
      "layout": "CSS Grid with node positioning",
      "nodeSize": "60x60px",
      "connectionLines": "SVG paths drawn behind nodes",
      "nodeStates": "Reference skill-tree.md node states"
    },
    "tooltip": {
      "layout": "+----------------------------------+\n|  [Upgrade Name] (Level X)        |\n|  [Full description]               |\n|  Current: +Y damage                |\n|  Next level: +Z damage            |\n|  Cost: [amount]                   |\n+----------------------------------+",
      "trigger": "Hover (desktop)",
      "position": "Above element, clamped to viewport",
      "delay": "200ms hover before showing"
    }
  },
  "uiEventFlowDiagrams": {
    "slimePlacement": {
      "description": "Player places/buys a new slime from shop",
      "diagram": "sequenceDiagram\n    actor Player\n    participant Canvas as Canvas\n    participant UI as Bottom Panel\n    participant Currency as CurrencyManager\n    participant Entities as EntitySystem\n\n    Player->>UI: clicks Shop tab, selects Rancher Slime\n    UI->>Canvas: placement mode active\n    Canvas->>Canvas: cursor shows placement preview\n    Player->>Canvas: clicks canvas at position (x, y)\n    Canvas->>Canvas: check: valid position? (in pen, not blocked)\n    Canvas->>Currency: canAfford(tokens, 20)?\n    alt Can afford and valid position\n        Currency->>UI: deduct 20 tokens\n        UI->>UI: currency counter animates 20→lower\n        Canvas->>Entities: createEntity('rancherSlime', x, y)\n        Entities->>Canvas: spawn animation (scale 0→1, 400ms)\n        Canvas->>Canvas: placement flash effect (200ms)\n        UI->>Canvas: exit placement mode\n    else Cannot afford or invalid position\n        Canvas->>Canvas: shake animation, red flash on cost\n        UI->>Canvas: placement mode stays active\n    end"
    },
    "enemyDeathCollection": {
      "description": "Enemy dies → drops essence → player collects",
      "diagram": "sequenceDiagram\n    participant Slime as Player Slime\n    participant Enemy as Enemy Entity\n    participant Canvas as Canvas\n    participant Currency as CurrencyManager\n    participant UI as HUD\n\n    Slime->>Enemy: attack(damage)\n    Enemy->>Enemy: hp -= damage\n    Enemy->>Canvas: play hit animation (white flash)\n    Canvas->>Canvas: floating damage number \"-15\" at position\n    \n    alt hp <= 0 (Enemy dies)\n        Enemy->>Enemy: play death animation\n        Enemy->>Canvas: emit('enemy-killed', {type, position, reward})\n        Canvas->>Canvas: spawnEssence({value: 2, position})\n        Canvas->>Canvas: essence sprite appears with pop-in (300ms)\n        Enemy->>Enemy: despawn\n        \n        Note over Canvas: Essence waits for collection (8s lifetime)\n        Canvas->>Canvas: player clicks essence sprite\n        Canvas->>Currency: add('essence', 2)\n        Canvas->>Canvas: essence flies to HUD counter\n        Canvas->>UI: floatingText(\"+2 💜\", essence position)\n        Canvas->>Canvas: particle burst (5 purple particles)\n        UI->>UI: essence counter count-up animation (300ms)\n        UI->>UI: gameplay-earned flash/pulse on essence display\n    end"
    },
    "upgradePurchaseEffect": {
      "description": "Player buys upgrade → visible effect on Canvas",
      "diagram": "sequenceDiagram\n    participant Player\n    participant UI as Upgrade Panel\n    participant Canvas as Game World\n    participant Currency as CurrencyManager\n    participant Slimes as SlimeEntities\n\n    Player->>UI: clicks upgrade card (affordable)\n    UI->>UI: card flashes green (200ms)\n    UI->>Currency: deduct(cost)\n    Currency->>UI: currency counter animates down\n    UI->>Canvas: emit('upgrade-purchased', {type, effect})\n    \n    alt Upgrade affects slimes (e.g., +damage)\n        Canvas->>Slimes: applyUpgradeToAllSlimes({type: 'damage', value: +5})\n        Slimes->>Canvas: each slime flashes briefly\n        Canvas->>Canvas: all slimes have subtle glow for 500ms\n    else Upgrade unlocks new zone (pen expansion)\n        Canvas->>Canvas: pen area visibly grows (scale animation 500ms)\n        Canvas->>Canvas: new boundary lines appear\n        Canvas->>Canvas: capacity counter updates\n    end\n    \n    Canvas->>UI: showNotification(\"Upgrade Complete!\")"
    },
    "waveStartComplete": {
      "description": "Wave starts → wave complete → rewards",
      "diagram": "sequenceDiagram\n    participant Wave as WaveSystem\n    participant Canvas as Game Canvas\n    participant UI as HUD\n    participant Currency as CurrencyManager\n    Player as Player\n\n    Wave->>UI: show \"Wave 5 incoming!\" (2s before)\n    UI->>Canvas: spawn indicators pulse at forest edge\n    Wave->>Canvas: spawn enemies (staggered)\n    Canvas->>Canvas: enemies emerge and attack\n    \n    Note over Canvas,Player: Combat phase - player micromanages slimes\n    Player->>Canvas: drags slimes, clicks enemies, collects babies\n    \n    Note over Canvas: All enemies defeated\n    Canvas->>Wave: last enemy dies\n    Wave->>Canvas: emit('wave-complete', {waveNumber: 5})\n    Canvas->>Canvas: brief screen flash (white, 200ms)\n    Wave->>Currency: calculateWaveReward(5)\n    Currency->>Currency: reward = 50 * 5 = 250 tokens\n    Currency->>UI: add('tokens', 250)\n    UI->>UI: tokens count-up animation (500ms, larger)\n    UI->>Player: showNotification(\"Wave 5 Complete! +250 🪙\")\n    Wave->>Wave: start intermission (10s)"
    }
  },
  "uiStateMachine": {
    "diagram": "stateDiagram-v2\n    [*] --> Loading: page load\n    Loading --> Playing: assets loaded\n\n    state Playing {\n        [*] --> PreWave: between waves\n        PreWave --> WaveActive: countdown complete (3s)\n        WaveActive --> PreWave: wave cleared\n        WaveActive --> GameOver: core destroyed / all slimes dead\n\n        state PreWave {\n            [*] --> BuildPhase\n            BuildPhase: Player can place slimes\n            BuildPhase: Shop/upgrades fully accessible\n            BuildPhase: Canvas interactive (drag slimes)\n        }\n\n        state WaveActive {\n            [*] --> Combat\n            Combat: Enemies spawning/moving\n            Combat: Player can drag slimes\n            Combat: Player can click collectibles\n            Combat: Player can click enemies to prioritize\n            Combat: Player can activate charged abilities\n            Combat: Bottom panel can be collapsed for more canvas space\n        }\n    }\n\n    Playing --> PrestigeScreen: player prestiges\n    PrestigeScreen --> Playing: new run starts\n    Playing --> SettingsModal: gear icon clicked\n    SettingsModal --> Playing: modal closed\n    GameOver --> Playing: restart"
  },
  "feedbackSystems": {
    "visualFeedbackCatalog": [
      {
        "action": "Enemy defeated",
        "canvasFeedback": "Death animation (fade out + spark sprite particles), floating purple essence sprite",
        "uiFeedback": "Essence counter pulses, count-up animation (300ms)",
        "duration": "500ms"
      },
      {
        "action": "Wave completed",
        "canvasFeedback": "Brief screen flash (white, 200ms), all enemies gone",
        "uiFeedback": "Toast 'Wave X Complete! +Y Tokens', wave counter increments, tokens count-up (500ms)",
        "duration": "1000ms"
      },
      {
        "action": "Purchase upgrade/shop item",
        "canvasFeedback": "If affects slimes: all slimes glow briefly. If pen upgrade: pen visibly grows on Canvas",
        "uiFeedback": "Card flashes green, cost deducted animation, counter animates",
        "duration": "300ms"
      },
      {
        "action": "Cannot afford (click)",
        "canvasFeedback": "None",
        "uiFeedback": "Card shakes horizontally, cost flashes red",
        "duration": "200ms"
      },
      {
        "action": "New unlock (tab/upgrade)",
        "canvasFeedback": "None",
        "uiFeedback": "Tab glow/pulse animation, notification dot, toast message",
        "duration": "Until clicked"
      },
      {
        "action": "Prestige",
        "canvasFeedback": "Canvas fades to white (500ms), new world fades in (500ms) with transformed background",
        "uiFeedback": "Screen flash, transition animation, gene shop appears",
        "duration": "1000-2000ms"
      },
      {
        "action": "Skill node purchased",
        "canvasFeedback": "If has visual effect: entities change on Canvas (e.g., faster bounce, glow)",
        "uiFeedback": "Node fills with color, connection lines light up, SP counter animates",
        "duration": "500ms"
      },
      {
        "action": "Slime spawned/purchased",
        "canvasFeedback": "Sprite appears on Canvas with spawn animation (fade in + scale up, 400ms)",
        "uiFeedback": "Resource deducted from currency counter",
        "duration": "400ms"
      },
      {
        "action": "Entity takes damage",
        "canvasFeedback": "Sprite flashes white briefly (100ms), floating damage number rises up",
        "uiFeedback": "None",
        "duration": "200ms"
      },
      {
        "action": "Baby slime collected",
        "canvasFeedback": "Baby disappears with burst animation (5 pink particles), floating '+5 🪙' text",
        "uiFeedback": "Tokens counter pulses, count-up animation (200ms), gameplay-earned flash",
        "duration": "300ms"
      },
      {
        "action": "King Essence collected",
        "canvasFeedback": "Massive particle explosion (10 gold particles), screen golden flash",
        "uiFeedback": "Dramatic counter animation (1000ms per count), achievement toast",
        "duration": "1500ms"
      },
      {
        "action": "Slime ability activated",
        "canvasFeedback": "Screen flash, area damage animation (particles burst from slime), enemies hit",
        "uiFeedback": "Ability cooldown indicator appears on slime",
        "duration": "500ms"
      },
      {
        "action": "Evolution complete",
        "canvasFeedback": "Slime transforms with flash animation, sprite changes (blue→red), size increases",
        "uiFeedback": "Toast 'Evolution Complete!', essence counter animates",
        "duration": "1000ms"
      }
    ]
  },
  "numberFormattingRules": {
    "ranges": [
      {
        "range": "0 - 999",
        "format": "Whole number",
        "example": "742"
      },
      {
        "range": "1,000 - 999,999",
        "format": "With commas",
        "example": "12,345"
      },
      {
        "range": "1M - 999.9M",
        "format": "Suffix",
        "example": "1.5M"
      },
      {
        "range": "1B - 999.9B",
        "format": "Suffix",
        "example": "42.3B"
      },
      {
        "range": "1T+",
        "format": "Suffix",
        "example": "1.2T"
      },
      {
        "range": "Rates (/sec)",
        "format": "1 decimal",
        "example": "+12.3/s"
      },
      {
        "range": "Damage numbers (Canvas)",
        "format": "Whole number",
        "example": "-15"
      }
    ]
  },
  "progressBars": {
    "style": "Rounded corners, striped animated fill",
    "color": "Gradient from left to right based on completion %",
    "label": "Percentage on right, current/max on left",
    "animation": "Fill animates smoothly over 300ms"
  },
  "responsiveConsiderations": {
    "minWidth": "1280px",
    "maxWidth": "Full viewport",
    "scaling": "Canvas scales to fit available width, bottom panel uses percentage-based heights",
    "collapseBehavior": "Bottom panel can be collapsed to give Canvas more space. On narrow viewports, default to collapsed."
  },
  "accessibility": {
    "contrastRatios": "All text meets WCAG AA minimum 4.5:1",
    "focusIndicators": "Visible focus outlines for keyboard navigation (2px gold outline)",
    "screenReader": "Currency amounts have aria-live regions for updates",
    "reducedMotion": "Respect prefers-reduced-motion media query — disable Canvas animations, use static sprites, remove particle effects"
  },
  "settingsPanel": {
    "settings": [
      {
        "name": "Notation Format",
        "type": "Toggle",
        "options": [
          "Standard",
          "Scientific"
        ],
        "default": "Standard",
        "effect": "Changes number display format"
      },
      {
        "name": "Animation Speed",
        "type": "Slider",
        "range": "0.5x - 2x",
        "default": "1x",
        "effect": "Scales all animation durations and Canvas game speed"
      },
      {
        "name": "Auto-Save Interval",
        "type": "Dropdown",
        "options": [
          "10s",
          "30s",
          "60s",
          "Never"
        ],
        "default": "30s",
        "effect": "How often game state saves"
      },
      {
        "name": "Canvas Quality",
        "type": "Toggle",
        "options": [
          "High",
          "Low"
        ],
        "default": "High",
        "effect": "Low disables glow effects and particles for performance"
      },
      {
        "name": "Hard Reset",
        "type": "Button (with confirmation)",
        "effect": "Wipe all data, require confirmation"
      },
      {
        "name": "Export Save",
        "type": "Button",
        "effect": "Copy save string to clipboard"
      },
      {
        "name": "Import Save",
        "type": "Button",
        "effect": "Paste save string from clipboard"
      }
    ]
  },
  "config": {
    "canvas": {
      "width": 800,
      "height": 450,
      "backgroundColor": "#1a2e1a",
      "gridCellSize": 16,
      "layers": [
        "background",
        "entities",
        "effects",
        "hudOverlay"
      ]
    },
    "ui": {
      "tickRate": 20,
      "autoSaveInterval": 30000,
      "theme": "dark",
      "hudHeight": 50,
      "bottomPanelHeight": 250,
      "bottomPanelCollapsedHeight": 40,
      "canvasMinHeight": 400,
      "tabs": [
        {
          "id": "shop",
          "label": "Shop",
          "icon": "🛒",
          "unlockedAt": "waveComplete >= 1"
        },
        {
          "id": "upgrades",
          "label": "Upgrades",
          "icon": "⬆️",
          "unlockedAt": "waveComplete >= 3"
        },
        {
          "id": "skills",
          "label": "Skills",
          "icon": "🌟",
          "unlockedAt": "waveComplete >= 5"
        },
        {
          "id": "prestige",
          "label": "Prestige",
          "icon": "✨",
          "unlockedAt": "bossesDefeated >= 1"
        }
      ],
      "notifications": {
        "toastDuration": 3000,
        "toastPosition": "top-right",
        "milestoneDisplayDuration": 5000,
        "stackLimit": 3
      }
    },
    "effects": {
      "particles": {
        "babyCollection": {
          "count": 5,
          "sprite": "spark",
          "lifetime": 500,
          "spread": 20,
          "color": "#FF69B4"
        },
        "essenceCollection": {
          "count": 5,
          "sprite": "spark",
          "lifetime": 500,
          "spread": 20,
          "color": "#9B59B6"
        },
        "kingEssenceCollection": {
          "count": 10,
          "sprite": "spark",
          "lifetime": 800,
          "spread": 40,
          "color": "#FFD700"
        },
        "enemyDeath": {
          "count": 5,
          "sprite": "spark",
          "lifetime": 400,
          "spread": 15
        },
        "bossDeath": {
          "count": 30,
          "sprite": "spark",
          "lifetime": 800,
          "spread": 40
        },
        "structureDestroyed": {
          "count": 10,
          "sprite": "spark",
          "lifetime": 600,
          "spread": 25
        }
      },
      "floatingText": {
        "duration": 800,
        "riseSpeed": 30,
        "fontSize": 14,
        "fontWeight": "bold",
        "colors": {
          "gold": "#FFD700",
          "tokens": "#FFD700",
          "damage": "#FF4444",
          "heal": "#44FF44",
          "essence": "#9B59B6",
          "kingEssence": "#FFA500"
        }
      },
      "screenFlash": {
        "waveComplete": {
          "color": "#FFFFFF",
          "opacity": 0.3,
          "duration": 200
        },
        "prestige": {
          "color": "#FFFFFF",
          "opacity": 1,
          "duration": 500
        },
        "bossSpawn": {
          "color": "#FF0000",
          "opacity": 0.2,
          "duration": 300
        },
        "kingEssenceCollected": {
          "color": "#FFD700",
          "opacity": 0.5,
          "duration": 400
        }
      },
      "placementFlash": {
        "duration": 200,
        "color": "#FFFFFF",
        "opacity": 0.5
      }
    },
    "colorPalette": {
      "background": {
        "primary": "#0f1a0f",
        "secondary": "#1a2e1a",
        "tertiary": "#2a4e2a"
      },
      "canvas": "#1a2e1a",
      "text": {
        "primary": "#e0e0e0",
        "secondary": "#a0a0a0",
        "muted": "#606060"
      },
      "accent1": "#FFD700",
      "accent2": "#4FC3F7",
      "accent3": "#E040FB",
      "success": "#4CAF50",
      "warning": "#FF9800",
      "danger": "#F44336",
      "prestige": "#E040FB"
    }
  },
  "qualityChecklist": {
    "checkedItems": [
      "The Canvas game world is the PRIMARY element, occupying 60-70% of screen height",
      "Upgrade panels are SECONDARY, in a collapsible bottom panel (not the whole screen)",
      "Currency displays are ALWAYS visible in the HUD (never hidden behind tabs)",
      "Every entity type from idea.md has visual specs (sprite, scale, animation states)",
      "Canvas layers are specified (background, entities, effects, HUD overlay)",
      "Every UI element has specified states (locked, available, affordable, maxed, etc.)",
      "Feedback is specified for BOTH Canvas effects AND UI effects",
      "Floating damage/reward numbers are specified for the Canvas",
      "The color palette has enough contrast for readability (dark theme)",
      "Tab unlock conditions match progression.md's unlock sequence",
      "Number formatting rules cover the full range from 0 to 1T+",
      "The prestige UI shows visual transformation info",
      "The skill tree rendering approach is implementable in vanilla CSS/JS",
      "Accessibility basics are covered (contrast, keyboard, reduced motion)",
      "The design works at 1280x720 minimum resolution",
      "There is NO language about 'the UI IS the game' — the Canvas is the game",
      "Every entity type has a state machine diagram with all visual states",
      "Entity interaction diagram shows how all entity types relate",
      "UI event flow diagrams cover all major interaction paths (place, kill, collect, upgrade, wave)",
      "UI state machine shows game phases (loading, pre-wave, wave-active, prestige, game over)",
      "CONFIG.entities spec has every entity with sprite, scale, team, hp, states, healthBar",
      "CONFIG.canvas spec has width, height, backgroundColor, gridCellSize, layers",
      "CONFIG.ui spec has tab definitions with unlock conditions",
      "CONFIG.effects spec has particle, floatingText, and screenFlash definitions",
      "CONFIG.colorPalette has hex values for every UI color role",
      "Entity state definitions in CONFIG match the state machine diagrams exactly",
      "Seven click/interaction behaviors are specified for the Canvas (drag slime, click enemy, click baby, click essence, click charged slime, click food, place structure)",
      "The bottom panel is 30-40% of viewport and COLLAPSIBLE to give more Canvas space",
      "Gameplay-earned currency collection has distinct visual feedback (glow/pulse) separate from passive income"
    ]
  },
  "designPhilosophy": {
    "summary": "This UI/UX design is built around **Canvas-first gameplay** where the player's hands spend most of their time interacting with the game world, not clicking buttons. The upgrade panel is a strategic planning area that sits BETWEEN gameplay moments, not the main interaction loop.",
    "keyPrinciples": [
      "**Canvas is the game**: 60-70% of the screen is the game world. Player hands spend most of their time dragging slimes, clicking enemies, collecting babies, activating abilities on the Canvas. The bottom panel is for decisions BETWEEN combat moments.",
      "**Always-visible essentials**: Currency counts, wave info, and key stats are in the HUD overlay, never hidden behind tabs.",
      "**Progressive disclosure**: Tabs and features unlock as the player progresses. Empty tabs don't exist—when something unlocks, it appears with animation and notification.",
      "**Feedback everywhere**: Every action has BOTH Canvas feedback (particles, animations, floating text) AND UI feedback (counter animations, notifications). The player SEES the results of their actions.",
      "**One primary action**: At any moment, the player knows what the main thing is. During waves: fight. Between waves: upgrade. The UI supports this, not obscures it.",
      "**Information on demand**: Summary info is always visible. Detailed info is on hover/click. Don't dump formulas unless asked.",
      "**Dark theme for extended play**: Dark backgrounds reduce eye strain during long sessions. Colored accents celebrate rewards and signal threats."
    ]
  }
}