# Resource Systems Design

**Document Version:** 1.0.0 **Game Mode:** The Veil War (Mode 1) **Design
Date:** December 2024 **Status:** Initial Design

---

## Overview

The Veil War features a multi-layered resource economy with four primary
resource types, each tied to specific planes and strategic functions. The
economy is designed around principles of dynamic scarcity, risk-reward
tradeoffs, and meaningful player interaction.

**Design Principles:**

1. **Scarcity as Strategy:** Every resource should become scarce at meaningful
   moments
2. **Ebb and Flow:** Cycles of abundance and scarcity create strategic depth
3. **Gatekeeper Resources:** Certain resources block execution of plans when
   missing
4. **Risk-Reward Balance:** Powerful resources come with significant costs or
   dangers
5. **Player Interaction:** Trading and denial create emergent economic gameplay

**Resource Summary:**

| Resource          | Type               | Primary Source        | Scarcity Level | Risk Level |
| ----------------- | ------------------ | --------------------- | -------------- | ---------- |
| Veil Points       | Soft Currency      | Territory Control     | Low            | None       |
| Echo Crystals     | Strategic Resource | Material Plane Mining | Medium         | Low        |
| Resonance Essence | Magical Currency   | Resonance Nodes       | Medium         | Low        |
| Void Entropy      | Dangerous Resource | Void Plane Activities | High           | Very High  |

---

## 1. Veil Points

Veil Points are the primary "soft currency" of The Veil War, representing a
faction's connection to and manipulation of the Veil itself. They are relatively
abundant but critical for all major actions.

### 1.1 Generation Mechanics

**Base Generation by Territory Type:**

| Territory Type | Base VP/Turn | Conditions            | Max Bonus          |
| -------------- | ------------ | --------------------- | ------------------ |
| Heartland      | 3            | Controlled, supplied  | +3 (Full Dominion) |
| Borderland     | 2            | Controlled, supplied  | +2 (Full Dominion) |
| Wasteland      | 1            | Controlled            | +1 (Full Dominion) |
| Sacred Site    | 4            | Controlled, activated | +4 (Full Dominion) |
| Nexus          | 5            | Controlled, powered   | +5 (Full Dominion) |

**Generation Modifiers:**

```typescript
interface VeilPointGeneration {
  territoryId: TerritoryId;
  baseGeneration: number;

  // Positive modifiers
  fullDominionBonus: number; // +100% if Full Dominion
  resonanceBonus: number; // +1 per connected powered ley line
  prosperityBonus: number; // +1 if resources upgraded to max
  stabilityBonus: number; // +1 if entropy level 0

  // Negative modifiers
  corruptionPenalty: number; // -1 per entropy level above 2
  contestedPenalty: number; // -50% if territory contested
  supplyPenalty: number; // -25% if not supplied

  // Faction modifiers
  factionBonus: number; // Faction-specific generation bonuses
}

function calculateVeilPointGeneration(
  territory: TerritoryState,
  player: Player
): number {
  const base = getBaseGeneration(territory.type);

  // Positive modifiers
  let bonus = 0;
  if (territory.fullDominion?.controller === player.id) {
    bonus += base; // Double for Full Dominion
  }
  bonus += countPoweredLeyLines(territory) * 1;
  if (areResourcesMaxUpgraded(territory)) bonus += 1;
  if (territory.void_.entropyLevel === 0) bonus += 1;

  // Negative modifiers
  let penalty = 0;
  if (territory.void_.entropyLevel > 2) {
    penalty += territory.void_.entropyLevel - 2;
  }

  let multiplier = 1.0;
  if (isContested(territory)) multiplier *= 0.5;
  if (territory.material.supplyStatus !== 'supplied') multiplier *= 0.75;

  // Faction bonus
  const factionMod = getFactionVeilPointModifier(player.faction, territory);

  return Math.floor((base + bonus - penalty) * multiplier * factionMod);
}
```

**Special Generation Sources:**

| Source                   | VP Generated | Frequency      | Condition                         |
| ------------------------ | ------------ | -------------- | --------------------------------- |
| Battle Victory           | 2-5          | Per victory    | Based on enemy strength defeated  |
| Commander Level Up       | 3            | Per level      | Commander gains experience        |
| Prophecy Progress        | 2            | Per milestone  | Hidden objective progress         |
| Weave Connection Formed  | 1            | Per connection | Positive relationship established |
| Enemy Territory Captured | 3            | Per capture    | Must hold for 1 turn              |

### 1.2 Spending Options

**Unit Recruitment:**

| Unit Category     | VP Cost | Additional Costs | Notes                         |
| ----------------- | ------- | ---------------- | ----------------------------- |
| Militia           | 1       | None             | Available anywhere            |
| Standard Infantry | 2       | None             | Requires controlled territory |
| Elite Infantry    | 4       | 2 Echo Crystals  | Requires fortification        |
| Cavalry           | 3-5     | None             | Requires borderland+          |
| Siege Units       | 5-8     | 3 Echo Crystals  | Requires citadel              |
| Faction Unique    | 6-10    | Varies           | Faction-specific requirements |

**Ability Activation:**

| Ability Type       | VP Cost Range | Examples                      |
| ------------------ | ------------- | ----------------------------- |
| Basic Faction      | 5-8           | Minor movement, scouting      |
| Advanced Faction   | 10-15         | Major combat effects          |
| Ultimate Faction   | 20-30         | Game-changing abilities       |
| Cross-Plane Action | 8-15          | Affecting another plane       |
| Veil-Strike        | 5-15          | Magical attacks (+ Resonance) |

**Plane Manipulation:**

| Action              | VP Cost | Effect                        |
| ------------------- | ------- | ----------------------------- |
| Stabilize Territory | 10      | Reduce entropy by 1           |
| Empower Ley Line    | 8       | +2 power flow for 3 turns     |
| Veil Sight          | 5       | Scout all planes in territory |
| Plane Shift Army    | 12      | Move army between planes      |
| Create Ley Bridge   | 15      | Requires Mystic faction       |

### 1.3 Banking and Interest

**Veil Point Storage:**

| Storage Level  | Capacity | Interest Rate | Unlock Condition              |
| -------------- | -------- | ------------- | ----------------------------- |
| Basic Pool     | 50 VP    | 0%            | Default                       |
| Veil Vault     | 100 VP   | 5% per turn   | Control Sacred Site           |
| Nexus Treasury | 200 VP   | 8% per turn   | Control Nexus + Full Dominion |

**Banking Mechanics:**

```typescript
interface VeilPointBank {
  playerId: PlayerId;
  currentBalance: number;
  maxCapacity: number;
  interestRate: number; // Percentage per turn

  // Banking history
  deposits: Transaction[];
  withdrawals: Transaction[];
  interestEarned: number;

  // Special features
  hasVault: boolean;
  hasTreasury: boolean;
  protectedAmount: number; // Cannot be stolen
}

function processEndOfTurnBanking(bank: VeilPointBank): BankingResult {
  // Calculate interest
  const interest = Math.floor(bank.currentBalance * bank.interestRate);

  // Apply interest (capped at capacity)
  const newBalance = Math.min(bank.currentBalance + interest, bank.maxCapacity);

  // Overflow penalty (lose excess)
  const overflow = bank.currentBalance + interest - newBalance;

  return {
    previousBalance: bank.currentBalance,
    interestEarned: interest,
    newBalance,
    overflowLost: overflow,
  };
}
```

**Overflow Mechanics:**

- VP exceeding capacity at end of turn is lost
- Encourages spending and strategic timing
- Upgrades increase capacity

### 1.4 Inter-Player Trading

**Trade Rules:**

```typescript
interface VeilPointTrade {
  offerer: PlayerId;
  recipient: PlayerId;
  vpAmount: number;

  // Trade conditions
  exchangeType: 'gift' | 'trade' | 'tribute';
  exchangeFor?: TradeItem; // What's being received in return

  // Diplomatic effects
  weaveConnectionStrength: number; // Created/strengthened connection
  reputationChange: number; // Public perception

  // Restrictions
  minimumAmount: 5; // Can't trade less than 5 VP
  taxRate: 0.1; // 10% lost in transfer (to sink)
  cooldownTurns: 2; // Can't trade same player again for 2 turns
}

type TradeItem =
  | { type: 'veil_points'; amount: number }
  | { type: 'echo_crystals'; amount: number }
  | { type: 'resonance_essence'; amount: number }
  | { type: 'territory_rights'; territories: TerritoryId[] }
  | { type: 'military_access'; duration: number }
  | { type: 'non_aggression'; duration: number }
  | { type: 'alliance_commitment'; terms: string };
```

**Trade Restrictions:**

- 10% tax on all VP transfers (economy sink)
- 2-turn cooldown between trades with same player
- Minimum 5 VP per transaction
- Cannot trade if at war (armistice required)
- Some factions have trade bonuses (Herald: no tax, Sage: information trades)

---

## 2. Echo Crystals

Echo Crystals are strategic resources harvested from the Material Plane. They
represent crystallized echoes of reality, used for powerful one-time effects and
elite unit construction.

### 2.1 Mining Mechanics

**Crystal Deposits:**

| Deposit Type      | Base Yield   | Rarity    | Mining Time      | Special              |
| ----------------- | ------------ | --------- | ---------------- | -------------------- |
| Surface Vein      | 1/turn       | Common    | Immediate        | Depletes in 10 turns |
| Deep Mine         | 2/turn       | Uncommon  | 2 turns setup    | Requires engineers   |
| Ancient Cache     | 5 (one-time) | Rare      | Excavation event | Random discovery     |
| Nexus Crystalline | 3/turn       | Very Rare | Nexus control    | Never depletes       |

**Mining Implementation:**

```typescript
interface EchoCrystalDeposit {
  id: string;
  territoryId: TerritoryId;
  type: 'surface_vein' | 'deep_mine' | 'ancient_cache' | 'nexus_crystalline';

  // Production
  baseYield: number;
  currentYield: number;
  remainingReserves: number | null; // null = infinite

  // State
  isDiscovered: boolean;
  isMining: boolean;
  miningProgress: number; // For setup time
  assignedWorkers: number;

  // Modifiers
  improvementLevel: number; // 0-3, each +25% yield
  corruptionDamage: number; // Entropy reduces yield
}

function calculateCrystalYield(
  deposit: EchoCrystalDeposit,
  territory: TerritoryState
): number {
  if (!deposit.isMining || deposit.remainingReserves === 0) return 0;

  let yield_ = deposit.baseYield;

  // Improvement bonus
  yield_ *= 1 + deposit.improvementLevel * 0.25;

  // Worker efficiency (diminishing returns)
  const workerBonus = Math.log2(deposit.assignedWorkers + 1) * 0.2;
  yield_ *= 1 + workerBonus;

  // Corruption penalty
  if (territory.void_.entropyLevel > 0) {
    yield_ *= 1 - territory.void_.entropyLevel * 0.15;
  }

  // Faction bonuses
  if (territory.material.controller) {
    const faction = getFaction(territory.material.controller);
    if (faction === 'champion' || faction === 'guardian') {
      yield_ *= 1.2; // Material-focused factions
    }
  }

  return Math.floor(yield_);
}

function processDepletion(
  deposit: EchoCrystalDeposit,
  harvested: number
): void {
  if (deposit.remainingReserves === null) return; // Infinite

  deposit.remainingReserves -= harvested;

  if (deposit.remainingReserves <= 0) {
    deposit.remainingReserves = 0;
    deposit.isMining = false;
    // Trigger depletion event for Weave
    emitResourceEvent('deposit_depleted', deposit);
  }
}
```

### 2.2 Usage - Powerful One-Time Effects

**Echo Crystal Abilities:**

| Effect              | Crystal Cost | Description                                     | Restrictions                |
| ------------------- | ------------ | ----------------------------------------------- | --------------------------- |
| Reality Anchor      | 5            | Territory immune to plane effects for 3 turns   | Once per game per territory |
| Echo Duplicate      | 8            | Create copy of any owned unit for 2 turns       | Once per battle             |
| Temporal Cache      | 3            | Store current game state for potential rewind   | Echoes of Fate integration  |
| Crystallized Memory | 4            | Reveal all enemy actions from last turn         | Intel ability               |
| Shatter Charge      | 6            | Double damage on next attack, crystal destroyed | Single use                  |
| Resonance Catalyst  | 4            | Convert crystals to 15 Resonance Essence        | Economy conversion          |
| Void Seal           | 10           | Reduce territory entropy to 0 permanently       | Very powerful               |

**Usage Implementation:**

```typescript
interface EchoCrystalAbility {
  id: string;
  name: string;
  crystalCost: number;
  additionalCosts?: { veilPoints?: number; resonanceEssence?: number };

  // Effect details
  effectType: 'instant' | 'duration' | 'permanent';
  duration?: number;
  target: 'territory' | 'unit' | 'player' | 'global';

  // Restrictions
  usesPerGame: number | null; // null = unlimited
  factionRestrictions?: FactionId[];
  requiredConditions?: Condition[];
}

function useEchoCrystalAbility(
  player: Player,
  ability: EchoCrystalAbility,
  target: AbilityTarget
): AbilityResult {
  // Check costs
  if (player.resources.echoCrystals < ability.crystalCost) {
    return { success: false, reason: 'insufficient_crystals' };
  }

  // Check restrictions
  if (ability.usesPerGame !== null) {
    const uses = getAbilityUses(player, ability.id);
    if (uses >= ability.usesPerGame) {
      return { success: false, reason: 'usage_limit_reached' };
    }
  }

  // Deduct cost
  player.resources.echoCrystals -= ability.crystalCost;
  if (ability.additionalCosts) {
    deductAdditionalCosts(player, ability.additionalCosts);
  }

  // Apply effect
  const effect = applyAbilityEffect(ability, target);

  // Record for Weave
  recordCrystalUsage(player, ability, target);

  return { success: true, effect };
}
```

### 2.3 Rarity Tiers and Distribution

**Crystal Quality Tiers:**

| Tier      | Name           | Effect Multiplier | Discovery Chance | Source         |
| --------- | -------------- | ----------------- | ---------------- | -------------- |
| Common    | Fractured Echo | 0.75x             | 80%              | Surface veins  |
| Uncommon  | Clear Echo     | 1.0x              | 15%              | Deep mines     |
| Rare      | Resonant Echo  | 1.5x              | 4%               | Ancient caches |
| Legendary | Perfect Echo   | 2.0x              | 1%               | Nexus only     |

**Distribution Rules:**

- Each map has 2-3 Nexus territories with Legendary potential
- 15-20% of territories have Crystal deposits
- Deep mines require 2 turns and Engineer units to establish
- Ancient caches discovered through exploration events
- Legendary crystals cannot be traded (bound to discovering faction)

---

## 3. Resonance Essence

Resonance Essence is the magical currency harvested from the Resonance Plane. It
powers ley line manipulation, Veil-strikes, and magical construction.

### 3.1 Harvesting Mechanics

**Node Harvesting:**

| Node Type | Base Essence/Turn | Storage Capacity | Harvest Efficiency |
| --------- | ----------------- | ---------------- | ------------------ |
| Font      | 3                 | 10               | 90%                |
| Well      | 1                 | 30               | 95%                |
| Forge     | 0 (converter)     | 5                | N/A                |
| Sanctum   | 2                 | 15               | 85%                |
| Nexus     | 5                 | 50               | 80%                |

**Harvesting Implementation:**

```typescript
interface ResonanceHarvest {
  nodeId: NodeId;
  playerId: PlayerId;

  // Base calculation
  baseGeneration: number;
  efficiency: number;

  // Modifiers
  leyLineBonus: number; // +1 per connected active line
  constructionBonus: number; // From Resonance buildings
  factionBonus: number; // Mystic: +100%

  // Penalties
  voidCorruptionPenalty: number; // From entropy seepage
  contestedPenalty: number; // If node contested
  overharvestPenalty: number; // From aggressive extraction
}

function calculateResonanceHarvest(
  node: ResonancePlaneState,
  player: Player,
  leyLines: Map<LeyLineId, LeyLine>
): number {
  const baseEfficiency = getNodeEfficiency(node.type);
  let harvest = node.currentPowerGeneration * baseEfficiency;

  // Ley line bonus
  const activeLeyLines = node.connectedLeyLines.filter(
    (id) => !leyLines.get(id)!.isDisrupted
  ).length;
  harvest += activeLeyLines * 1;

  // Construction bonus
  for (const construction of node.constructions) {
    if (construction.type === 'essence_extractor') {
      harvest *= 1.25;
    }
  }

  // Faction bonus
  const faction = player.faction;
  if (faction === 'mystic') harvest *= 2.0;
  if (faction === 'oracle') harvest *= 1.25;
  if (faction === 'harbinger') harvest *= 0.5; // Penalty

  // Void corruption penalty
  harvest *= 1 - node.voidCorruption * 0.2;

  // Contested penalty
  if (node.contestingPlayers.length > 0) {
    harvest *= 0.6;
  }

  return Math.floor(harvest);
}
```

### 3.2 Usage - Magical Abilities and Ley Line Manipulation

**Resonance Essence Costs:**

| Action              | Essence Cost | VP Cost | Effect                                     |
| ------------------- | ------------ | ------- | ------------------------------------------ |
| Minor Veil-Strike   | 5            | 5       | 3 damage to target unit                    |
| Major Veil-Strike   | 15           | 10      | 6 damage + area effect                     |
| Ley Line Empower    | 8            | 5       | +50% power flow for 3 turns                |
| Ley Bridge Creation | 25           | 15      | Create new ley line                        |
| Node Activation     | 10           | 8       | Activate dormant node                      |
| Resonance Ward      | 12           | 6       | Protect territory from magical attacks     |
| Power Surge         | 20           | 12      | Double all node generation for 1 turn      |
| Reality Anchor      | 30           | 20      | Prevent all plane manipulation for 3 turns |

**Ley Line Manipulation:**

```typescript
interface LeyLineManipulation {
  type: 'empower' | 'disrupt' | 'redirect' | 'create' | 'destroy';
  leyLineId: LeyLineId;
  caster: PlayerId;

  // Costs
  essenceCost: number;
  veilPointCost: number;
  castingTime: number; // Turns to complete

  // Effects
  duration: number | 'permanent';
  powerModifier: number;
  stabilityChange: number;
  flowDirectionChange?: 'a_to_b' | 'b_to_a' | 'bidirectional';
}

const LEY_LINE_MANIPULATIONS: Record<string, LeyLineManipulation> = {
  empower: {
    type: 'empower',
    essenceCost: 8,
    veilPointCost: 5,
    castingTime: 0,
    duration: 3,
    powerModifier: 1.5,
    stabilityChange: -10,
  },
  disrupt: {
    type: 'disrupt',
    essenceCost: 12,
    veilPointCost: 8,
    castingTime: 1,
    duration: 2,
    powerModifier: 0,
    stabilityChange: -30,
  },
  redirect: {
    type: 'redirect',
    essenceCost: 15,
    veilPointCost: 10,
    castingTime: 1,
    duration: 'permanent',
    powerModifier: 1.0,
    stabilityChange: -15,
    flowDirectionChange: 'bidirectional',
  },
  create: {
    type: 'create',
    essenceCost: 25,
    veilPointCost: 15,
    castingTime: 2,
    duration: 'permanent',
    powerModifier: 1.0,
    stabilityChange: 50, // New lines start unstable
  },
  destroy: {
    type: 'destroy',
    essenceCost: 20,
    veilPointCost: 12,
    castingTime: 1,
    duration: 'permanent',
    powerModifier: 0,
    stabilityChange: -100,
  },
};
```

### 3.3 Essence Corruption Mechanics

Resonance Essence can become corrupted by Void influence, changing its
properties.

**Corruption Levels:**

| Corruption % | Effect                      | Risk         |
| ------------ | --------------------------- | ------------ |
| 0-25%        | Normal essence              | None         |
| 26-50%       | -25% efficiency, +10% power | 10% backfire |
| 51-75%       | -50% efficiency, +25% power | 25% backfire |
| 76-100%      | Converts to Void Entropy    | 50% backfire |

**Corruption Implementation:**

```typescript
interface CorruptedEssence {
  baseAmount: number;
  corruptionPercentage: number;

  // Effects
  efficiencyMultiplier: number;
  powerMultiplier: number;
  backfireChance: number;

  // Outcomes on use
  possibleBackfires: BackfireEffect[];
}

type BackfireEffect =
  | { type: 'damage_caster'; amount: number }
  | { type: 'corrupt_node'; targetNode: NodeId; amount: number }
  | { type: 'spawn_void_creature'; location: NodeId }
  | { type: 'essence_loss'; percentage: number }
  | { type: 'ley_line_disruption'; leyLineId: LeyLineId };

function useCorruptedEssence(
  essence: CorruptedEssence,
  ability: ResonanceAbility,
  caster: Player
): EssenceUsageResult {
  // Roll for backfire
  const backfireRoll = Math.random() * 100;

  if (backfireRoll < essence.backfireChance) {
    // Backfire occurred
    const backfire = selectRandomBackfire(essence.possibleBackfires);
    applyBackfire(backfire, caster);

    return {
      success: false,
      backfired: true,
      backfireEffect: backfire,
      essenceConsumed: Math.floor(essence.baseAmount * 0.5), // Half consumed on backfire
    };
  }

  // Calculate effective power
  const effectivePower = ability.basePower * essence.powerMultiplier;

  return {
    success: true,
    backfired: false,
    effectivePower,
    essenceConsumed: Math.floor(
      essence.baseAmount * essence.efficiencyMultiplier
    ),
  };
}
```

**Purification:**

- Essence can be purified at Font nodes (costs 50% essence)
- Some factions immune to corruption (Warden, Guardian)
- Corrupted essence is more powerful but dangerous
- Harbinger faction deliberately corrupts essence for power

---

## 4. Void Entropy

Void Entropy is a dangerous resource generated through destructive and chaotic
activities. It offers immense power but accumulates with devastating
consequences.

### 4.1 Generation from Paradox and Destruction

**Entropy Generation Sources:**

| Activity                    | Entropy Generated | Conditions                     |
| --------------------------- | ----------------- | ------------------------------ |
| Paradox Well Harvest        | 3-5               | Per harvest action             |
| Territory Reaches Entropy 5 | 8                 | Catastrophic event             |
| Void Creature Kill          | 2                 | Per creature defeated          |
| Ley Line Destruction        | 4                 | Per line destroyed             |
| Army Annihilation           | 3                 | When army completely destroyed |
| Veil-Strike Backfire        | 2                 | When magical attack fails      |
| Hidden Passage Use          | 1                 | Per passage traversal          |
| Corrupted Essence Use       | 2                 | When corruption > 50%          |

**Passive Generation:**

```typescript
interface VoidEntropyGeneration {
  playerId: PlayerId;

  // Active sources
  paradoxWellHarvests: number;
  voidCreatureKills: number;
  destructionEvents: number;

  // Passive sources
  controlledHighEntropyTerritories: number; // Entropy 3+
  corruptedEssencePool: number;
  voidUnitCount: number;

  // Decay (negative generation)
  stabilizationEfforts: number;
  voidAnchorCount: number;
}

function calculateEntropyGeneration(
  gen: VoidEntropyGeneration,
  faction: FactionId
): number {
  let entropy = 0;

  // Active sources
  entropy += gen.paradoxWellHarvests * 4;
  entropy += gen.voidCreatureKills * 2;
  entropy += gen.destructionEvents * 3;

  // Passive sources
  entropy += gen.controlledHighEntropyTerritories * 1;
  entropy += Math.floor(gen.corruptedEssencePool / 20);
  entropy += gen.voidUnitCount * 0.5;

  // Faction modifiers
  if (faction === 'harbinger') {
    entropy *= 1.5; // Harbingers generate more
  } else if (faction === 'shadow') {
    entropy *= 1.2; // Shadow affinity
  } else if (faction === 'guardian' || faction === 'warden') {
    entropy *= 0.5; // Resist entropy generation
  }

  // Decay/stabilization
  entropy -= gen.stabilizationEfforts * 2;
  entropy -= gen.voidAnchorCount * 1;

  return Math.max(0, Math.floor(entropy));
}
```

### 4.2 Usage - Void Abilities and Creature Summoning

**Void Entropy Costs:**

| Action               | Entropy Cost | VP Cost | Effect                                   | Risk |
| -------------------- | ------------ | ------- | ---------------------------------------- | ---- |
| Summon Shadow Wisp   | 5            | 3       | Spawn weak void creature                 | 10%  |
| Summon Entropy Hound | 10           | 5       | Spawn pack hunter                        | 20%  |
| Summon Void Stalker  | 20           | 10      | Spawn assassin creature                  | 35%  |
| Entropy Cascade      | 15           | 8       | +1 entropy to adjacent territories       | 25%  |
| Void Passage         | 8            | 6       | Create temporary hidden passage          | 15%  |
| Reality Corruption   | 25           | 15      | Permanently increase territory entropy   | 40%  |
| Void Shroud          | 12           | 6       | Hide army from all detection for 2 turns | 20%  |
| Entropy Absorption   | Variable     | 5       | Convert stored entropy to VP (dangerous) | 50%  |

**Void Ability Implementation:**

```typescript
interface VoidAbility {
  id: string;
  name: string;
  entropyCost: number;
  veilPointCost: number;
  riskPercentage: number; // Chance of negative consequence

  // Effect
  effectType:
    | 'summon'
    | 'area'
    | 'passage'
    | 'corruption'
    | 'stealth'
    | 'conversion';
  targetType: 'territory' | 'unit' | 'player' | 'self';
  duration: number | 'instant' | 'permanent';

  // Risk consequences
  possibleConsequences: VoidConsequence[];
}

type VoidConsequence =
  | {
      type: 'entropy_spike';
      amount: number;
      target: 'self' | 'controlled_territories';
    }
  | { type: 'creature_turns_hostile'; creatureId: VoidCreatureId }
  | { type: 'void_rift'; location: TerritoryId; duration: number }
  | { type: 'corruption_spread'; radius: number }
  | { type: 'commander_corruption'; commander: CommanderId; amount: number }
  | { type: 'reality_fracture'; effects: string[] };

function useVoidAbility(
  player: Player,
  ability: VoidAbility,
  target: AbilityTarget
): VoidAbilityResult {
  // Check entropy available
  if (player.resources.voidEntropy < ability.entropyCost) {
    return { success: false, reason: 'insufficient_entropy' };
  }

  // Check faction restrictions
  if (!canFactionUseVoidAbility(player.faction, ability)) {
    return { success: false, reason: 'faction_restricted' };
  }

  // Deduct costs
  player.resources.voidEntropy -= ability.entropyCost;
  player.resources.veilPoints -= ability.veilPointCost;

  // Roll for risk
  const riskRoll = Math.random() * 100;
  const hasConsequence = riskRoll < ability.riskPercentage;

  // Apply effect
  const effect = applyVoidEffect(ability, target);

  // Apply consequence if rolled
  let consequence: VoidConsequence | null = null;
  if (hasConsequence) {
    consequence = selectConsequence(ability.possibleConsequences, player);
    applyVoidConsequence(consequence, player);
  }

  return {
    success: true,
    effect,
    hadConsequence: hasConsequence,
    consequence,
  };
}
```

### 4.3 Dangerous Accumulation Effects

Void Entropy accumulates on players, creating escalating dangers.

**Accumulation Thresholds:**

| Entropy Level | Threshold | Effects                                                 | Mitigation                 |
| ------------- | --------- | ------------------------------------------------------- | -------------------------- |
| Touched       | 10-24     | Visual indicator only                                   | None needed                |
| Corrupted     | 25-49     | -10% all resource generation                            | Stabilize territories      |
| Consumed      | 50-74     | -25% generation, units take 5% attrition                | Major stabilization        |
| Void-Bound    | 75-99     | -50% generation, 10% attrition, hostile creatures spawn | Emergency measures         |
| Annihilation  | 100+      | GAME OVER - Faction consumed by Void                    | Cannot be reached normally |

**Accumulation Implementation:**

```typescript
interface PlayerEntropyState {
  playerId: PlayerId;
  currentEntropy: number;
  accumulationRate: number; // Per turn passive increase
  decayRate: number; // Per turn decrease (from mitigation)

  // Threshold tracking
  currentThreshold:
    | 'safe'
    | 'touched'
    | 'corrupted'
    | 'consumed'
    | 'void_bound';
  turnsSinceThresholdReached: number;

  // Effects active
  resourcePenalty: number;
  attritionRate: number;
  creatureSpawnChance: number;

  // Mitigation efforts
  activeStabilizations: StabilizationEffect[];
  voidAnchorsControlled: number;
  purificationProgress: number;
}

function processEntropyAccumulation(state: PlayerEntropyState): EntropyResult {
  // Calculate net change
  const netChange = state.accumulationRate - state.decayRate;
  state.currentEntropy = Math.max(0, state.currentEntropy + netChange);

  // Check threshold changes
  const newThreshold = getEntropyThreshold(state.currentEntropy);
  const thresholdChanged = newThreshold !== state.currentThreshold;

  if (thresholdChanged) {
    state.currentThreshold = newThreshold;
    state.turnsSinceThresholdReached = 0;
    applyThresholdEffects(state);
  } else {
    state.turnsSinceThresholdReached++;
  }

  // Process effects
  const results: EntropyResult = {
    newEntropy: state.currentEntropy,
    threshold: state.currentThreshold,
    thresholdChanged,
    effects: [],
  };

  // Attrition
  if (state.attritionRate > 0) {
    const attritionResult = processAttrition(state);
    results.effects.push({ type: 'attrition', ...attritionResult });
  }

  // Creature spawning
  if (state.creatureSpawnChance > 0) {
    if (Math.random() * 100 < state.creatureSpawnChance) {
      const spawnResult = spawnHostileCreature(state);
      results.effects.push({ type: 'creature_spawn', ...spawnResult });
    }
  }

  // Check for annihilation
  if (state.currentEntropy >= 100) {
    results.gameOver = true;
    results.gameOverReason = 'void_annihilation';
  }

  return results;
}
```

**Mitigation Strategies:**

| Strategy                 | Entropy Reduction | Cost               | Requirements        |
| ------------------------ | ----------------- | ------------------ | ------------------- |
| Territory Stabilization  | -5 per territory  | 10 VP + 5 Essence  | Control territory   |
| Void Anchor Construction | -2 per turn       | 15 VP + 8 Crystals | Fortification slot  |
| Purification Ritual      | -20 (one-time)    | 25 VP + 15 Essence | Sacred Site control |
| Entropy Transfer         | Variable          | Trade negotiation  | Willing recipient   |
| Void Creature Binding    | -3 per creature   | 10 Entropy         | Dangerous           |

---

## 5. Resource Denial Strategies

Resource denial is a critical strategic element, allowing players to weaken
opponents economically.

### 5.1 Ley Line Severance

Cutting off ley lines isolates territories from Resonance power.

**Severance Mechanics:**

```typescript
interface LeyLineSeverance {
  targetLeyLine: LeyLineId;
  attacker: PlayerId;
  method: 'magical_disruption' | 'void_corruption' | 'physical_destruction';

  // Costs
  essenceCost: number;
  entropyCost: number;
  veilPointCost: number;

  // Effects
  severanceDuration: number | 'permanent';
  powerFlowReduction: number; // 0 = complete severance

  // Consequences
  affectedTerritories: TerritoryId[];
  cascadeEffects: CascadeEffect[];
}

function severLeyLine(
  severance: LeyLineSeverance,
  gameState: GameState
): SeveranceResult {
  const leyLine = gameState.leyLines.get(severance.targetLeyLine)!;

  // Apply severance
  leyLine.isDisrupted = true;
  leyLine.currentPowerFlow *= 1 - severance.powerFlowReduction;

  // Calculate affected territories
  const affected: TerritoryId[] = [];
  const nodeA = gameState.resonanceNodes.get(leyLine.nodeA)!;
  const nodeB = gameState.resonanceNodes.get(leyLine.nodeB)!;

  // Propagate isolation
  for (const nodeId of [nodeA.id, nodeB.id]) {
    const node = gameState.resonanceNodes.get(nodeId)!;
    if (isNowIsolated(node, gameState)) {
      affected.push(node.id);
      applyIsolationEffects(node, gameState);
    }
  }

  // Trigger cascade if permanent
  const cascades: CascadeEffect[] = [];
  if (severance.severanceDuration === 'permanent') {
    cascades.push(...triggerSeveranceCascade(leyLine, gameState));
  }

  return {
    success: true,
    affectedTerritories: affected,
    cascadeEffects: cascades,
    powerLost: calculatePowerLost(affected, gameState),
  };
}
```

**Isolation Effects:**

- Isolated nodes lose 50% power generation
- Isolated territories cannot receive Resonance-based buffs
- Veil-strikes from isolated territories cost +50%
- Mystic faction severely weakened when isolated

### 5.2 Paradox Well Creation

Creating paradox wells destabilizes enemy territories.

**Creation Mechanics:**

```typescript
interface ParadoxWellCreation {
  targetTerritory: TerritoryId;
  creator: PlayerId;

  // Costs
  voidEntropyCost: number; // 20 base
  veilPointCost: number; // 15 base

  // Properties of created well
  initialInstability: number;
  initialDepth: number;
  initialYield: number;

  // Targeting
  canTargetOwn: boolean;
  canTargetEnemy: boolean;
  canTargetNeutral: boolean;
}

function createParadoxWell(
  creation: ParadoxWellCreation,
  gameState: GameState
): ParadoxWellResult {
  const territory = gameState.territories.get(creation.targetTerritory)!;

  // Check if territory already has maximum wells
  if (territory.void_.paradoxWells.length >= 3) {
    return { success: false, reason: 'max_wells_reached' };
  }

  // Create the well
  const well: ParadoxWell = {
    id: generateId(),
    instability: creation.initialInstability + Math.random() * 20,
    depth: creation.initialDepth as 1 | 2 | 3 | 4 | 5,
    resonanceInteraction: -20 - Math.random() * 30, // Negative (disrupts ley)
    temporalFlux: Math.floor(Math.random() * 5),
    voidEssenceYield: creation.initialYield,
    harvestRisk: 25 + creation.initialInstability * 0.5,
    harvestedThisTurn: false,
    totalHarvested: 0,
    isCollapsing: false,
    collapseProgress: 0,
  };

  territory.void_.paradoxWells.push(well);

  // Increase territory entropy
  territory.void_.entropyLevel = Math.min(
    5,
    territory.void_.entropyLevel + 1
  ) as EntropyLevel;

  // Disrupt nearby ley lines
  const resonanceNode = gameState.resonanceNodes.get(
    territory.resonance.nodeId
  )!;
  for (const leyLineId of resonanceNode.connectedLeyLines) {
    const leyLine = gameState.leyLines.get(leyLineId)!;
    leyLine.stability -= 15;
    if (leyLine.stability < 30) {
      leyLine.isDisrupted = true;
    }
  }

  return {
    success: true,
    wellCreated: well,
    entropyIncrease: 1,
    leyLinesAffected: resonanceNode.connectedLeyLines.length,
  };
}
```

### 5.3 Supply Line Interdiction

Cutting supply lines starves enemy armies.

**Interdiction Mechanics:**

```typescript
interface SupplyInterdiction {
  targetRoute: SupplyRouteId;
  attacker: PlayerId;
  method:
    | 'cavalry_raid'
    | 'fortification_siege'
    | 'void_corruption'
    | 'ley_disruption';

  // Unit requirements
  requiredUnits: { cavalry?: number; infantry?: number; void_units?: number };

  // Effects
  interdictionStrength: number; // 0-100
  duration: number; // Turns
  maintenanceCost: number; // VP per turn to maintain
}

function interdictSupplyLine(
  interdiction: SupplyInterdiction,
  gameState: GameState
): InterdictionResult {
  const route = gameState.supplyRoutes.get(interdiction.targetRoute)!;

  // Calculate effectiveness based on method and units
  let effectiveness = interdiction.interdictionStrength;

  // Method modifiers
  switch (interdiction.method) {
    case 'cavalry_raid':
      effectiveness *= 1.2; // Cavalry excels at raiding
      break;
    case 'fortification_siege':
      effectiveness *= 0.8; // Slower but permanent
      break;
    case 'void_corruption':
      effectiveness *= 1.5; // Very effective but risky
      break;
    case 'ley_disruption':
      effectiveness *= 0.9; // Requires magical control
      break;
  }

  // Apply interdiction
  route.isInterdicted = true;
  route.efficiency *= 1 - effectiveness / 100;

  // Calculate affected armies
  const affectedArmies = findArmiesDependentOnRoute(route, gameState);
  for (const army of affectedArmies) {
    updateArmySupplyStatus(army, gameState);
  }

  return {
    success: true,
    routeEfficiency: route.efficiency,
    affectedArmies: affectedArmies.map((a) => a.id),
    estimatedStarvationTurns: calculateStarvationTime(affectedArmies),
  };
}
```

**Starvation Effects:**

| Status   | Turn Limit          | Effects                                |
| -------- | ------------------- | -------------------------------------- |
| Supplied | Unlimited           | Full effectiveness                     |
| Foraging | 3 turns             | -25% strength, damages local resources |
| Starving | Until supplied/dead | -50% strength, 10% attrition per turn  |

### 5.4 Economic Warfare Options

**Economic Attack Types:**

| Attack              | Target                | Cost              | Effect                   | Duration     |
| ------------------- | --------------------- | ----------------- | ------------------------ | ------------ |
| Market Manipulation | Enemy VP generation   | 15 VP             | -20% VP generation       | 3 turns      |
| Resource Sabotage   | Echo Crystal deposits | 10 VP, 5 Crystals | -50% yield               | 5 turns      |
| Essence Drain       | Resonance nodes       | 12 Essence        | Steal 5 Essence/turn     | 3 turns      |
| Entropy Seeding     | Any territory         | 15 Entropy        | +2 entropy level         | Permanent    |
| Trade Blockade      | Trade routes          | 8 VP              | No trading with target   | Until broken |
| Information Warfare | Seer/Sage abilities   | 10 VP             | Reveal false information | 2 turns      |

**Economic Warfare Implementation:**

```typescript
interface EconomicAttack {
  type:
    | 'market_manipulation'
    | 'resource_sabotage'
    | 'essence_drain'
    | 'entropy_seeding'
    | 'trade_blockade'
    | 'information_warfare';
  attacker: PlayerId;
  target: PlayerId | TerritoryId;

  // Costs
  veilPointCost: number;
  additionalCosts: Partial<ResourceCosts>;

  // Effects
  effectMagnitude: number;
  duration: number;
  canBeCountered: boolean;
  counterCost: Partial<ResourceCosts>;
}

function executeEconomicAttack(
  attack: EconomicAttack,
  gameState: GameState
): EconomicAttackResult {
  // Deduct costs
  const attacker = gameState.players.get(attack.attacker)!;
  deductCosts(attacker, attack.veilPointCost, attack.additionalCosts);

  // Apply effect based on type
  switch (attack.type) {
    case 'market_manipulation':
      return applyMarketManipulation(attack, gameState);

    case 'resource_sabotage':
      return applyResourceSabotage(attack, gameState);

    case 'essence_drain':
      return applyEssenceDrain(attack, gameState);

    case 'entropy_seeding':
      return applyEntropySeeding(attack, gameState);

    case 'trade_blockade':
      return applyTradeBlockade(attack, gameState);

    case 'information_warfare':
      return applyInformationWarfare(attack, gameState);
  }
}

// Counter mechanics
function attemptCounter(
  attack: EconomicAttack,
  defender: Player,
  gameState: GameState
): CounterResult {
  if (!attack.canBeCountered) {
    return { success: false, reason: 'attack_cannot_be_countered' };
  }

  if (!hasResources(defender, attack.counterCost)) {
    return { success: false, reason: 'insufficient_counter_resources' };
  }

  // Deduct counter cost
  deductCosts(defender, 0, attack.counterCost);

  // Roll for success (base 50%, modified by faction)
  let successChance = 50;
  if (defender.faction === 'sage') successChance += 20; // Information expertise
  if (defender.faction === 'mystic') successChance += 15; // Magical resistance

  const roll = Math.random() * 100;
  if (roll < successChance) {
    // Counter successful
    removeAttackEffect(attack, gameState);
    return { success: true, attackNegated: true };
  }

  return { success: false, reason: 'counter_failed' };
}
```

---

## 6. Resource Flow Diagram

```
                         ┌─────────────────────────────────────┐
                         │         PLAYER ECONOMY              │
                         └─────────────────────────────────────┘
                                         │
         ┌───────────────┬───────────────┼───────────────┬───────────────┐
         ▼               ▼               ▼               ▼               ▼
   ┌───────────┐   ┌───────────┐   ┌───────────┐   ┌───────────┐   ┌───────────┐
   │   VEIL    │   │   ECHO    │   │ RESONANCE │   │   VOID    │   │  SPECIAL  │
   │  POINTS   │   │ CRYSTALS  │   │  ESSENCE  │   │  ENTROPY  │   │  TOKENS   │
   └───────────┘   └───────────┘   └───────────┘   └───────────┘   └───────────┘
         │               │               │               │               │
         │               │               │               │               │
   SOURCES:        SOURCES:        SOURCES:        SOURCES:        SOURCES:
   - Territories   - Mining         - Nodes         - Destruction   - Achievements
   - Battle wins   - Discoveries    - Ley lines     - Harvesting    - Prophecies
   - Events        - Conversion     - Conversion    - Void acts     - Weave events
         │               │               │               │               │
         ▼               ▼               ▼               ▼               ▼
   ┌───────────────────────────────────────────────────────────────────────────┐
   │                            CONVERSION MATRIX                              │
   │                                                                           │
   │   VP ──────> Crystals (10:1)    Crystals ──────> VP (1:5)                │
   │   VP ──────> Essence (5:1)      Essence ──────> VP (1:3)                 │
   │   Crystals ─> Essence (1:4)     Essence ──────> Crystals (4:1)           │
   │   Essence ──> Entropy (2:1)     Entropy ──────> VP (1:2) [DANGEROUS]     │
   │                                                                           │
   └───────────────────────────────────────────────────────────────────────────┘
         │               │               │               │
         ▼               ▼               ▼               ▼
   SINKS:          SINKS:          SINKS:          SINKS:
   - Unit recruit  - Elite units   - Veil-strikes  - Void abilities
   - Abilities     - Abilities     - Ley manip     - Creature summon
   - Trading tax   - Void Seal     - Construction  - Corruption
   - Fortification - Temporal      - Purification  - (Accumulates!)
```

---

## 7. Faction Resource Modifiers

| Faction   | VP Mod | Crystal Mod | Essence Mod | Entropy Mod | Special                         |
| --------- | ------ | ----------- | ----------- | ----------- | ------------------------------- |
| Guardian  | +10%   | +20%        | -10%        | -50%        | Cannot use Entropy              |
| Shadow    | +0%    | +0%         | -25%        | +50%        | Bonus from Entropy use          |
| Seer      | +10%   | +0%         | +10%        | +0%         | Trade information for resources |
| Weaver    | -10%   | +0%         | +20%        | +20%        | Random bonuses/penalties        |
| Mystic    | +0%    | -10%        | +100%       | -25%        | Essence is primary currency     |
| Champion  | +20%   | +25%        | -25%        | +0%         | VP from combat victories        |
| Harbinger | -25%   | -25%        | -50%        | +100%       | Entropy is primary currency     |
| Oracle    | +10%   | +10%        | +25%        | +0%         | Predict resource events         |
| Herald    | +15%   | +0%         | +0%         | -10%        | Trade bonuses, no tax           |
| Sage      | +10%   | +0%         | +25%        | +0%         | Discover hidden deposits        |
| Warden    | +0%    | +0%         | +0%         | -50%        | Balance bonuses                 |
| Exemplar  | +15%   | +10%        | +10%        | -25%        | Virtue generates resources      |

---

## References

Research sources used in this design:

- [Unity Gaming Services - Building Game Economies](https://unity.com/how-to/building-game-economy-guide-part-2)
- [Peachpit - Game Mechanics: Internal Economy Design](https://www.peachpit.com/articles/article.aspx?p=1925649)
- [Game Rant - Grand Strategy Economic Systems](https://gamerant.com/grand-strategy-games-best-economy-systems/)
- [Wayward Strategy - Multiple Resource Generation in RTS](https://waywardstrategy.com/2022/01/23/food-gold-and-beyond/)
- [BGG Forum - Scarcity in Board Game Economics](https://boardgamegeek.com/thread/1599377/scarcity-board-game-economics-and-how-use-when-des)
- [BGDF - Corruption Mechanics](https://www.bgdf.com/forum/game-creation/mechanics/corruption-mechanic)
- [Medium - Trade-Offs, Dilemmas, Risk & Reward](https://medium.com/understanding-games/trade-offs-dilemmas-sacrifices-risk-reward-46acd014e435)

---

**Document End**

_Related Documents: Tri-Planar System Design, Asymmetric Factions, Territory
Control Matrix_
