# Victory Conditions Implementation

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

---

## Overview

The Veil War features five distinct victory conditions, each representing a
different path to ultimate dominion. Players can pursue multiple victory
conditions simultaneously, and faction-specific modifiers can alter thresholds
or provide alternative paths.

**Design Principles:**

1. **Multiple Viable Paths:** No single victory condition should be universally
   optimal
2. **Asymmetric Accessibility:** Different factions should favor different
   victory paths
3. **Interruptibility:** Victory progress should be visible and contestable
4. **Narrative Integration:** Each victory condition tells a story through the
   Weave
5. **Decoupled from Production:** Victory progress requires investment that
   doesn't strengthen the economy

**Research Sources:**

- Root's Dominance Cards and asymmetric victory
- Twilight Imperium's secret objectives system
- COIN series faction-specific victory conditions
- 4X game victory condition theory
- Dead of Winter's main + secret objective design

---

## 1. Dominion Victory

_"When the Material, Resonance, and Void kneel beneath a single will, the Veil
itself becomes the throne."_

Dominion Victory represents total control - mastering all three planes of a
territory simultaneously across a majority of the map.

### 1.1 Victory Condition

**Threshold:** Control 60% of all territories with Full Dominion status.

**Full Dominion Definition:**

- Control the Material Plane (physical structures, armies)
- Control the Resonance Plane (ley lines, power nodes)
- Control the Void Plane (entropy management, void presence)
- All three must be controlled simultaneously

**Victory Declaration:**

- At the start of any player's turn, if they control Full Dominion over ≥60% of
  territories, they may declare Dominion Victory
- The declaration triggers a **Challenge Period** of 2 full rounds
- If they still hold ≥60% Full Dominion at the end of the Challenge Period, they
  win

### 1.2 Real-Time Dominion Percentage Tracking

```typescript
interface DominionTracker {
  totalTerritories: number;
  fullDominionTerritories: Map<PlayerId, TerritoryId[]>;
  dominionPercentages: Map<PlayerId, number>;

  // Configuration
  victoryThreshold: number; // Default 0.60 (60%)
  challengePeriodRounds: number; // Default 2

  // State
  activeChallenges: DominionChallenge[];
}

interface DominionChallenge {
  challengerId: PlayerId;
  declaredTurn: number;
  declaredPercentage: number;
  challengePeriodEnds: number;
  territoriesAtDeclaration: TerritoryId[];
}

function calculateDominionPercentage(
  player: PlayerId,
  gameState: GameState
): DominionPercentageResult {
  const allTerritories = gameState.territories;
  const totalCount = allTerritories.size;

  let fullDominionCount = 0;
  const fullDominionTerritories: TerritoryId[] = [];

  for (const [id, territory] of allTerritories) {
    if (hasFullDominion(territory, player)) {
      fullDominionCount++;
      fullDominionTerritories.push(id);
    }
  }

  const percentage = fullDominionCount / totalCount;

  return {
    player,
    fullDominionCount,
    totalTerritories: totalCount,
    percentage,
    territories: fullDominionTerritories,
    meetsThreshold: percentage >= gameState.victoryConfig.dominionThreshold,
  };
}

function hasFullDominion(territory: TerritoryState, player: PlayerId): boolean {
  return (
    territory.material.controller === player &&
    territory.resonance.controller === player &&
    territory.void_.controller === player
  );
}

function updateDominionTracker(gameState: GameState): void {
  const tracker = gameState.dominionTracker;

  // Clear and recalculate for all players
  tracker.fullDominionTerritories.clear();
  tracker.dominionPercentages.clear();

  for (const player of gameState.players.keys()) {
    const result = calculateDominionPercentage(player, gameState);
    tracker.fullDominionTerritories.set(player, result.territories);
    tracker.dominionPercentages.set(player, result.percentage);
  }

  // Check for victory declarations
  checkDominionVictoryDeclarations(gameState);
}
```

### 1.3 Contested Territory Handling

Territories can become contested in multiple ways, affecting Full Dominion:

**Contest Conditions:** | Plane | Contested When | Resolution |
|-------|----------------|------------| | Material | Enemy army present | Combat
or withdrawal | | Resonance | Ley line under attack | Magical contest | | Void |
Entropy ≥ 3 and enemy void presence | Void confrontation |

```typescript
interface ContestState {
  territory: TerritoryId;
  plane: PlaneType;
  contestants: PlayerId[];
  contestType: ContestType;
  startTurn: number;
}

type ContestType =
  | 'military_presence' // Enemy army in territory
  | 'ley_line_attack' // Resonance disruption
  | 'void_incursion' // Void entity presence
  | 'siege' // Active siege
  | 'ritual_interference'; // Cross-plane ritual

function isPlaneContested(
  territory: TerritoryState,
  plane: PlaneType,
  controller: PlayerId
): boolean {
  switch (plane) {
    case 'material':
      // Contested if enemy army present
      return territory.material.armies.some(
        (army) => army.owner !== controller
      );

    case 'resonance':
      // Contested if ley lines under attack or power node disputed
      return (
        territory.resonance.leyLineStatus === 'disrupted' ||
        territory.resonance.powerNodeContested
      );

    case 'void':
      // Contested if high entropy AND enemy void presence
      return (
        territory.void_.entropyLevel >= 3 &&
        territory.void_.voidPresences.some((p) => p.owner !== controller)
      );

    default:
      return false;
  }
}

function handleContestedDominion(
  territory: TerritoryState,
  player: PlayerId
): ContestResolution {
  const contestedPlanes: PlaneType[] = [];

  if (isPlaneContested(territory, 'material', player)) {
    contestedPlanes.push('material');
  }
  if (isPlaneContested(territory, 'resonance', player)) {
    contestedPlanes.push('resonance');
  }
  if (isPlaneContested(territory, 'void', player)) {
    contestedPlanes.push('void');
  }

  // If ANY plane is contested, Full Dominion is suspended
  if (contestedPlanes.length > 0) {
    return {
      hasFullDominion: false,
      contestedPlanes,
      resolution: 'suspended_until_resolved',
    };
  }

  return {
    hasFullDominion: hasFullDominion(territory, player),
    contestedPlanes: [],
    resolution: 'stable',
  };
}
```

### 1.4 Victory Threshold Configuration

Different game modes can adjust the victory threshold:

```typescript
interface DominionVictoryConfig {
  // Base threshold
  defaultThreshold: number; // 0.60 (60%)

  // Player count adjustments
  thresholdByPlayerCount: Map<number, number>;

  // Map size adjustments
  thresholdByMapSize: Map<MapSize, number>;

  // Challenge period
  challengePeriodRounds: number;

  // Faction modifiers
  factionThresholdModifiers: Map<FactionId, number>;
}

const DEFAULT_DOMINION_CONFIG: DominionVictoryConfig = {
  defaultThreshold: 0.6,

  thresholdByPlayerCount: new Map([
    [2, 0.65], // 2 players: need 65%
    [3, 0.55], // 3 players: need 55%
    [4, 0.5], // 4 players: need 50%
    [5, 0.45], // 5 players: need 45%
    [6, 0.4], // 6 players: need 40%
  ]),

  thresholdByMapSize: new Map([
    ['small', 0.7], // Small maps: need 70%
    ['medium', 0.6], // Medium maps: need 60%
    ['large', 0.5], // Large maps: need 50%
    ['massive', 0.45], // Massive maps: need 45%
  ]),

  challengePeriodRounds: 2,

  factionThresholdModifiers: new Map([
    ['guardian', -0.05], // Guardian needs only 55% (defensive)
    ['champion', -0.05], // Champion needs only 55% (military)
    ['weaver', +0.05], // Weaver needs 65% (chaos focus)
  ]),
};

function getEffectiveThreshold(
  baseConfig: DominionVictoryConfig,
  playerCount: number,
  mapSize: MapSize,
  faction: FactionId
): number {
  let threshold = baseConfig.defaultThreshold;

  // Apply player count adjustment
  if (baseConfig.thresholdByPlayerCount.has(playerCount)) {
    threshold = baseConfig.thresholdByPlayerCount.get(playerCount)!;
  }

  // Apply map size adjustment (use the more restrictive)
  if (baseConfig.thresholdByMapSize.has(mapSize)) {
    const mapThreshold = baseConfig.thresholdByMapSize.get(mapSize)!;
    threshold = Math.max(threshold, mapThreshold);
  }

  // Apply faction modifier
  if (baseConfig.factionThresholdModifiers.has(faction)) {
    threshold += baseConfig.factionThresholdModifiers.get(faction)!;
  }

  return Math.max(0.3, Math.min(0.8, threshold)); // Clamp 30%-80%
}
```

---

## 2. Resonance Supremacy

_"The ley lines converge. The nexuses pulse as one. All magic flows through
me."_

Resonance Supremacy represents magical dominance - controlling all major ley
nexuses and establishing uncontested magical authority.

### 2.1 Victory Condition

**Threshold:** Control all Major Ley Nexuses on the map simultaneously.

**Major Ley Nexus Definition:**

- Territories designated as nexuses during map generation
- Typically 5-8 nexuses depending on map size
- Each nexus connects 4+ ley lines

**Victory Declaration:**

- Instant victory when player controls all nexuses (no challenge period)
- Control means: Resonance Plane controller AND power node active

### 2.2 Nexus Identification and Tracking

```typescript
interface LeyNexus {
  id: NexusId;
  territoryId: TerritoryId;

  // Nexus properties
  nexusRank: 'minor' | 'major' | 'grand'; // Only 'major' and 'grand' count
  connectedLeyLines: LeyLineId[];
  powerCapacity: number;

  // State
  controller: PlayerId | null;
  powerNodeActive: boolean;
  contested: boolean;

  // Strategic value
  resonanceMultiplier: number; // Power generation multiplier
}

interface NexusTracker {
  majorNexuses: Map<NexusId, LeyNexus>;
  totalMajorNexuses: number;

  controlByPlayer: Map<PlayerId, NexusId[]>;

  supremacyCandidate: PlayerId | null; // Player closest to supremacy
  turnsUntilSupremacy: number | null; // If ritually claiming
}

function updateNexusTracker(gameState: GameState): void {
  const tracker = gameState.nexusTracker;
  tracker.controlByPlayer.clear();

  for (const [nexusId, nexus] of tracker.majorNexuses) {
    const territory = gameState.territories.get(nexus.territoryId)!;

    // Update nexus state from territory
    nexus.controller = territory.resonance.controller;
    nexus.powerNodeActive = territory.resonance.powerNodeActive;
    nexus.contested = isPlaneContested(
      territory,
      'resonance',
      nexus.controller!
    );

    // Track control
    if (nexus.controller && nexus.powerNodeActive && !nexus.contested) {
      const controlled = tracker.controlByPlayer.get(nexus.controller) ?? [];
      controlled.push(nexusId);
      tracker.controlByPlayer.set(nexus.controller, controlled);
    }
  }

  // Check for supremacy
  checkResonanceSupremacy(gameState);
}

function checkResonanceSupremacy(gameState: GameState): PlayerId | null {
  const tracker = gameState.nexusTracker;

  for (const [player, nexuses] of tracker.controlByPlayer) {
    if (nexuses.length === tracker.totalMajorNexuses) {
      // Player controls all major nexuses!
      return player;
    }
  }

  return null;
}
```

### 2.3 Contested Nexus Handling

```typescript
interface NexusContest {
  nexusId: NexusId;
  currentController: PlayerId;
  challengers: PlayerId[];
  contestType: NexusContestType;

  // Contest mechanics
  resonanceBattle: boolean; // Magical battle in progress
  ritualInterference: boolean; // Someone disrupting rituals
  leyLineSeverance: boolean; // Ley lines being cut
}

type NexusContestType =
  | 'resonance_battle' // Direct magical combat
  | 'ley_line_severance' // Cutting connections
  | 'power_node_sabotage' // Destroying the node
  | 'void_corruption'; // Entropy overwhelming

function resolveNexusContest(
  contest: NexusContest,
  gameState: GameState
): NexusContestResult {
  const nexus = gameState.nexusTracker.majorNexuses.get(contest.nexusId)!;
  const territory = gameState.territories.get(nexus.territoryId)!;

  switch (contest.contestType) {
    case 'resonance_battle':
      // Opposed roll using Resonance strength
      return resolveResonanceBattle(
        contest.currentController,
        contest.challengers[0],
        territory,
        gameState
      );

    case 'ley_line_severance':
      // Check if enough ley lines remain for nexus status
      const activeLines = nexus.connectedLeyLines.filter(
        (lineId) => !gameState.leyLines.get(lineId)!.severed
      );
      if (activeLines.length < 4) {
        // Nexus loses major status temporarily
        return { nexusDowngraded: true, controller: null };
      }
      break;

    case 'void_corruption':
      // High entropy disables power nodes
      if (territory.void_.entropyLevel >= 4) {
        return {
          powerNodeDisabled: true,
          controller: contest.currentController,
          countForSupremacy: false,
        };
      }
      break;
  }

  return { controller: contest.currentController, contested: true };
}
```

### 2.4 Supremacy Declaration Mechanics

```typescript
interface SupremacyDeclaration {
  player: PlayerId;
  declarationTurn: number;
  nexusesControlled: NexusId[];

  // Ritual aspect (optional alternative)
  usingRitualPath: boolean;
  ritualProgress: number; // 0-100
  ritualTurnsRemaining: number;
}

// Standard path: control all nexuses simultaneously
function declareResonanceSupremacy(
  player: PlayerId,
  gameState: GameState
): SupremacyDeclarationResult {
  const controlled = gameState.nexusTracker.controlByPlayer.get(player) ?? [];
  const required = gameState.nexusTracker.totalMajorNexuses;

  if (controlled.length < required) {
    return {
      success: false,
      reason: `Control ${controlled.length}/${required} nexuses`,
    };
  }

  // Check that all are uncontested with active power nodes
  for (const nexusId of controlled) {
    const nexus = gameState.nexusTracker.majorNexuses.get(nexusId)!;
    if (nexus.contested || !nexus.powerNodeActive) {
      return {
        success: false,
        reason: `Nexus ${nexusId} is contested or inactive`,
      };
    }
  }

  // Instant victory!
  return {
    success: true,
    victoryType: 'resonance_supremacy',
    narrativeEntry: generateSupremacyNarrative(player, controlled, gameState),
  };
}

// Alternative: Resonance Ritual (takes 3 turns but only needs 4/5 nexuses)
function progressResonanceRitual(
  player: PlayerId,
  gameState: GameState
): RitualProgressResult {
  const controlled = gameState.nexusTracker.controlByPlayer.get(player) ?? [];
  const required = Math.ceil(gameState.nexusTracker.totalMajorNexuses * 0.8);

  if (controlled.length < required) {
    return { progress: 0, reason: 'Not enough nexuses for ritual' };
  }

  // Progress the ritual
  const ritual = gameState.activeRituals.get(player);
  if (!ritual) {
    // Start new ritual
    return startResonanceRitual(player, controlled, gameState);
  }

  // Continue existing ritual
  ritual.progress += 33; // ~3 turns to complete
  ritual.ritualTurnsRemaining--;

  if (ritual.progress >= 100) {
    return {
      progress: 100,
      complete: true,
      victoryType: 'resonance_supremacy_ritual',
    };
  }

  return {
    progress: ritual.progress,
    turnsRemaining: ritual.ritualTurnsRemaining,
  };
}
```

---

## 3. Void Ascension

_"The Entropy Spiral awakens. Reality unravels, and from its threads, I weave my
apotheosis."_

Void Ascension represents transcendence through chaos - completing a dangerous
multi-turn ritual that requires massive entropy accumulation and specific
components.

### 3.1 Victory Condition

**Threshold:** Complete the Entropy Spiral Ritual.

**Ritual Requirements:**

1. Accumulate 50+ Void Entropy across controlled territories
2. Gather 5 Ritual Components (scattered across the map)
3. Control a Paradox Well territory
4. Maintain ritual for 5 consecutive turns
5. No Void Ascension can be interrupted by another player completing theirs
   first

### 3.2 Ritual Component Gathering

```typescript
interface RitualComponent {
  id: ComponentId;
  name: string;
  location: TerritoryId;

  // Acquisition
  gatherer: PlayerId | null;
  gatheringProgress: number; // 0-100
  turnsToGather: number;

  // Requirements
  controlRequirement: PlaneType[]; // Which planes must be controlled
  minimumEntropy: number; // Minimum entropy in territory
  specialRequirement: string | null;
}

const SPIRAL_COMPONENTS: RitualComponent[] = [
  {
    id: 'void_heart',
    name: 'Heart of the Void',
    location: null as any, // Assigned during map gen
    gatherer: null,
    gatheringProgress: 0,
    turnsToGather: 2,
    controlRequirement: ['void'],
    minimumEntropy: 4,
    specialRequirement: 'Must defeat Void Guardian',
  },
  {
    id: 'entropy_shard',
    name: 'Entropy Shard',
    location: null as any,
    gatherer: null,
    gatheringProgress: 0,
    turnsToGather: 1,
    controlRequirement: ['void', 'resonance'],
    minimumEntropy: 3,
    specialRequirement: null,
  },
  {
    id: 'reality_anchor_broken',
    name: 'Shattered Reality Anchor',
    location: null as any,
    gatherer: null,
    gatheringProgress: 0,
    turnsToGather: 2,
    controlRequirement: ['material', 'void'],
    minimumEntropy: 2,
    specialRequirement: 'Destroy an enemy Veil Fortress',
  },
  {
    id: 'paradox_essence',
    name: 'Essence of Paradox',
    location: null as any,
    gatherer: null,
    gatheringProgress: 0,
    turnsToGather: 3,
    controlRequirement: ['void'],
    minimumEntropy: 5,
    specialRequirement: 'Territory must be Paradox Zone',
  },
  {
    id: 'forgotten_name',
    name: 'The Forgotten Name',
    location: null as any,
    gatherer: null,
    gatheringProgress: 0,
    turnsToGather: 2,
    controlRequirement: ['resonance', 'void'],
    minimumEntropy: 3,
    specialRequirement: 'Sacrifice a Legendary unit',
  },
];

function attemptComponentGathering(
  player: PlayerId,
  componentId: ComponentId,
  gameState: GameState
): GatheringResult {
  const component = gameState.spiralComponents.find(
    (c) => c.id === componentId
  );
  if (!component) {
    return { success: false, reason: 'Component not found' };
  }

  if (component.gatherer && component.gatherer !== player) {
    return {
      success: false,
      reason: 'Another player is gathering this component',
    };
  }

  const territory = gameState.territories.get(component.location)!;

  // Check control requirements
  for (const plane of component.controlRequirement) {
    const controller = getPlaneController(territory, plane);
    if (controller !== player) {
      return {
        success: false,
        reason: `Must control ${plane} plane at ${component.location}`,
      };
    }
  }

  // Check entropy requirement
  if (territory.void_.entropyLevel < component.minimumEntropy) {
    return {
      success: false,
      reason: `Territory entropy (${territory.void_.entropyLevel}) below requirement (${component.minimumEntropy})`,
    };
  }

  // Check special requirement
  if (component.specialRequirement) {
    const specialMet = checkSpecialRequirement(
      component.specialRequirement,
      player,
      territory,
      gameState
    );
    if (!specialMet.met) {
      return { success: false, reason: specialMet.reason };
    }
  }

  // Begin or continue gathering
  if (!component.gatherer) {
    component.gatherer = player;
    component.gatheringProgress = 0;
  }

  component.gatheringProgress += 100 / component.turnsToGather;

  if (component.gatheringProgress >= 100) {
    // Component gathered!
    const playerComponents = gameState.playerComponents.get(player) ?? [];
    playerComponents.push(componentId);
    gameState.playerComponents.set(player, playerComponents);

    // Reset component for potential respawn (optional rule)
    component.gatherer = null;
    component.gatheringProgress = 0;

    return {
      success: true,
      gathered: true,
      component: component.name,
      weaveEntry: generateComponentGatheredEntry(player, component),
    };
  }

  return {
    success: true,
    gathered: false,
    progress: component.gatheringProgress,
    turnsRemaining: Math.ceil(
      (100 - component.gatheringProgress) / (100 / component.turnsToGather)
    ),
  };
}
```

### 3.3 Multi-Turn Ritual Execution

```typescript
interface EntropySpiralRitual {
  ritualist: PlayerId;
  startTurn: number;
  currentProgress: number; // 0-5 phases

  // Requirements maintained
  paradoxWellLocation: TerritoryId;
  entropyAccumulated: number;
  componentsUsed: ComponentId[];

  // Interruption tracking
  interruptionAttempts: InterruptionAttempt[];
  stabilityModifier: number; // -20 to +20

  // Phase tracking
  currentPhase: RitualPhase;
  phaseEffects: RitualPhaseEffect[];
}

type RitualPhase =
  | 'initiation' // Turn 1: Begin the spiral
  | 'accumulation' // Turn 2: Gather entropy
  | 'binding' // Turn 3: Bind components
  | 'unraveling' // Turn 4: Reality weakens
  | 'ascension'; // Turn 5: Complete transformation

interface RitualPhaseEffect {
  phase: RitualPhase;
  effect: string;
  mechanicalImpact: GameEffect[];
}

const RITUAL_PHASES: RitualPhaseEffect[] = [
  {
    phase: 'initiation',
    effect: 'The Void stirs. Entropy flows toward the ritual site.',
    mechanicalImpact: [{ type: 'entropy_attraction', radius: 3, strength: 1 }],
  },
  {
    phase: 'accumulation',
    effect: 'Darkness deepens. Reality groans under the strain.',
    mechanicalImpact: [
      { type: 'entropy_generation', value: 2 },
      { type: 'combat_penalty_others', radius: 2, value: -1 },
    ],
  },
  {
    phase: 'binding',
    effect: 'Components fuse. The Spiral takes form.',
    mechanicalImpact: [
      { type: 'void_creature_spawn', count: 2 },
      { type: 'ley_line_disruption', radius: 2 },
    ],
  },
  {
    phase: 'unraveling',
    effect: 'Reality tears. The boundary dissolves.',
    mechanicalImpact: [
      { type: 'terrain_transformation', radius: 1, toType: 'void_scar' },
      { type: 'mass_corruption', radius: 3, value: 2 },
    ],
  },
  {
    phase: 'ascension',
    effect: 'The ritualist becomes one with the Void. Ascension is complete.',
    mechanicalImpact: [{ type: 'victory', victoryType: 'void_ascension' }],
  },
];

function progressEntropySpiralRitual(
  player: PlayerId,
  gameState: GameState
): RitualProgressResult {
  const ritual = gameState.activeRituals.get(player) as EntropySpiralRitual;

  if (!ritual) {
    return { success: false, reason: 'No active ritual' };
  }

  // Verify requirements still met
  const verification = verifyRitualRequirements(ritual, gameState);
  if (!verification.valid) {
    return {
      success: false,
      reason: verification.reason,
      ritualBroken: true,
    };
  }

  // Check for interruption attempts
  const interruptions = resolveInterruptionAttempts(ritual, gameState);
  if (interruptions.ritualBroken) {
    return {
      success: false,
      reason: 'Ritual interrupted!',
      ritualBroken: true,
      interruptedBy: interruptions.interruptor,
    };
  }

  // Progress to next phase
  ritual.currentProgress++;
  ritual.currentPhase = RITUAL_PHASES[ritual.currentProgress - 1].phase;

  // Apply phase effects
  const phaseEffect = RITUAL_PHASES[ritual.currentProgress - 1];
  applyRitualPhaseEffects(phaseEffect, ritual, gameState);

  // Check for completion
  if (ritual.currentProgress >= 5) {
    return {
      success: true,
      complete: true,
      victoryType: 'void_ascension',
      narrativeEntry: generateAscensionNarrative(player, ritual, gameState),
    };
  }

  return {
    success: true,
    complete: false,
    currentPhase: ritual.currentPhase,
    turnsRemaining: 5 - ritual.currentProgress,
    nextPhaseEffect: RITUAL_PHASES[ritual.currentProgress].effect,
  };
}

function verifyRitualRequirements(
  ritual: EntropySpiralRitual,
  gameState: GameState
): VerificationResult {
  // Check paradox well control
  const paradoxTerritory = gameState.territories.get(
    ritual.paradoxWellLocation
  )!;
  if (paradoxTerritory.void_.controller !== ritual.ritualist) {
    return { valid: false, reason: 'Lost control of Paradox Well' };
  }

  // Check entropy level
  const totalEntropy = calculatePlayerEntropy(ritual.ritualist, gameState);
  if (totalEntropy < 50) {
    return { valid: false, reason: `Insufficient entropy: ${totalEntropy}/50` };
  }

  // Components stay gathered once used
  // But check the ritualist still has them
  const playerComponents =
    gameState.playerComponents.get(ritual.ritualist) ?? [];
  for (const required of ritual.componentsUsed) {
    if (!playerComponents.includes(required)) {
      return { valid: false, reason: `Lost ritual component: ${required}` };
    }
  }

  return { valid: true };
}
```

### 3.4 Ritual Interruption Mechanics

```typescript
interface InterruptionAttempt {
  attempter: PlayerId;
  method: InterruptionMethod;
  turn: number;
  strength: number;
}

type InterruptionMethod =
  | 'military_assault' // Attack the paradox well territory
  | 'resonance_disruption' // Magical interference
  | 'component_theft' // Steal a ritual component
  | 'entropy_drain' // Reduce total entropy below 50
  | 'reality_anchoring'; // Deploy reality anchors

function attemptRitualInterruption(
  interruptor: PlayerId,
  ritualist: PlayerId,
  method: InterruptionMethod,
  gameState: GameState
): InterruptionResult {
  const ritual = gameState.activeRituals.get(ritualist) as EntropySpiralRitual;

  if (!ritual) {
    return { success: false, reason: 'No active ritual to interrupt' };
  }

  let interruptionStrength: number;
  let defenseStrength: number = 3 + ritual.currentProgress; // Harder to stop later

  switch (method) {
    case 'military_assault':
      // Must attack and take the paradox well
      const assaultResult = checkMilitaryInterruption(
        interruptor,
        ritual.paradoxWellLocation,
        gameState
      );
      interruptionStrength = assaultResult.strength;
      break;

    case 'resonance_disruption':
      // Roll opposed Resonance check
      const resonanceResult = performOpposedResonanceCheck(
        interruptor,
        ritualist,
        gameState
      );
      interruptionStrength = resonanceResult.margin;
      break;

    case 'component_theft':
      // Must have unit adjacent to ritual site
      const theftResult = attemptComponentTheft(interruptor, ritual, gameState);
      if (theftResult.success) {
        // Theft automatically breaks ritual
        return {
          success: true,
          ritualBroken: true,
          method: 'component_theft',
          stolenComponent: theftResult.component,
        };
      }
      return { success: false, reason: 'Theft failed' };

    case 'entropy_drain':
      // Deploy entropy drain effects
      const drainResult = applyEntropyDrain(interruptor, ritualist, gameState);
      // Check if entropy dropped below 50
      const newEntropy = calculatePlayerEntropy(ritualist, gameState);
      if (newEntropy < 50) {
        return {
          success: true,
          ritualBroken: true,
          method: 'entropy_drain',
          newEntropyLevel: newEntropy,
        };
      }
      return { success: false, reason: 'Entropy still above threshold' };

    case 'reality_anchoring':
      // Deploy reality anchors around ritual site
      interruptionStrength = deployRealityAnchors(
        interruptor,
        ritual.paradoxWellLocation,
        gameState
      );
      defenseStrength -= 2; // Anchors weaken void defense
      break;

    default:
      return { success: false, reason: 'Unknown interruption method' };
  }

  // Roll interruption check
  const interruptRoll = performRoll(interruptionStrength);
  const defenseRoll = performRoll(defenseStrength);

  if (interruptRoll.netSuccesses > defenseRoll.netSuccesses) {
    return {
      success: true,
      ritualBroken: true,
      method,
      margin: interruptRoll.netSuccesses - defenseRoll.netSuccesses,
    };
  }

  // Interruption failed
  ritual.interruptionAttempts.push({
    attempter: interruptor,
    method,
    turn: gameState.currentTurn,
    strength: interruptionStrength,
  });

  return {
    success: false,
    reason: 'Ritual defenses held',
    margin: defenseRoll.netSuccesses - interruptRoll.netSuccesses,
  };
}
```

### 3.5 Ascension Resolution Effects

When Void Ascension completes, major effects occur:

```typescript
interface AscensionResolution {
  ascendant: PlayerId;
  ascensionTurn: number;

  // Immediate effects
  immediateEffects: AscensionEffect[];

  // World state changes
  worldChanges: WorldChange[];

  // Weave impact
  weaveEntries: WeaveEntry[];
}

function resolveVoidAscension(
  ritualist: PlayerId,
  ritual: EntropySpiralRitual,
  gameState: GameState
): AscensionResolution {
  const resolution: AscensionResolution = {
    ascendant: ritualist,
    ascensionTurn: gameState.currentTurn,
    immediateEffects: [],
    worldChanges: [],
    weaveEntries: []
  };

  // Transform the ritual territory
  const paradoxTerritory = gameState.territories.get(ritual.paradoxWellLocation)!;
  resolution.worldChanges.push({
    type: 'territory_transformation',
    territory: ritual.paradoxWellLocation,
    newType: 'void_nexus',
    permanentEffect: true
  });

  // Spread void corruption
  const nearbyTerritories = getTerritories withinRange(
    ritual.paradoxWellLocation,
    3,
    gameState
  );
  for (const territory of nearbyTerritories) {
    resolution.worldChanges.push({
      type: 'entropy_increase',
      territory: territory.id,
      value: 3,
      permanentEffect: false
    });
  }

  // Generate massive Weave impact
  resolution.weaveEntries.push({
    type: 'major_event',
    title: 'The Void Ascension',
    description: generateAscensionDescription(ritualist, ritual, gameState),
    weaveWeight: 20,  // Maximum impact
    affectedNodes: getAllNodesInRadius(ritual.paradoxWellLocation, 5),
    permanentThreads: [
      createAscensionThread(ritualist, gameState)
    ]
  });

  // Victory!
  resolution.immediateEffects.push({
    type: 'victory',
    victor: ritualist,
    victoryType: 'void_ascension'
  });

  return resolution;
}
```

---

## 4. Prophetic Fulfillment

_"The prophecy was written before time began. I am merely its instrument."_

Prophetic Fulfillment represents destiny - completing a set of hidden objectives
assigned at game start that, when fulfilled, prove the player was always meant
to win.

### 4.1 Victory Condition

**Threshold:** Complete all three prophecy objectives (main + 2 secondary).

**Prophecy Structure:**

- 1 Main Prophecy (worth 2 fulfillment points)
- 2 Secondary Prophecies (worth 1 fulfillment point each)
- Victory at 4 fulfillment points

**Key Feature:** Prophecies are hidden from other players until fulfilled or
partially revealed.

### 4.2 Prophecy Assignment at Game Start

```typescript
interface Prophecy {
  id: ProphecyId;
  type: 'main' | 'secondary';
  fulfillmentValue: number; // 2 for main, 1 for secondary

  // Content
  title: string;
  crypticDescription: string; // Shown to all
  clearDescription: string; // Only owner sees this

  // Requirements
  requirements: ProphecyRequirement[];

  // State
  owner: PlayerId;
  progress: ProphecyProgress;
  fulfilled: boolean;
  revealed: boolean;
}

type ProphecyRequirement =
  | { type: 'control_territory'; territory: TerritoryId }
  | { type: 'control_territories_count'; count: number; plane?: PlaneType }
  | { type: 'defeat_player'; target: PlayerId }
  | { type: 'legendary_deed'; deedType: DeedType }
  | { type: 'accumulate_resource'; resource: ResourceType; amount: number }
  | { type: 'weave_connection'; strength: number; nodeType: WeaveNodeType }
  | { type: 'alliance_with'; target: PlayerId; duration: number }
  | { type: 'betray'; target: PlayerId }
  | { type: 'ritual_completion'; ritualType: string }
  | { type: 'combat_victory'; count: number; conditions?: string }
  | { type: 'specific_unit_action'; unit: UnitId; action: string };

interface ProphecyPool {
  mainProphecies: Prophecy[];
  secondaryProphecies: Prophecy[];
}

const MAIN_PROPHECY_TEMPLATES: ProphecyTemplate[] = [
  {
    title: 'The Unifier',
    crypticDescription:
      'From many, one. Where division reigned, harmony shall flow.',
    clearDescription:
      'Control 5 territories that were each controlled by a different player at some point.',
    requirements: [{ type: 'control_territories_changed_hands', count: 5 }],
  },
  {
    title: 'The Breaker of Chains',
    crypticDescription: 'The oppressor falls. Those who lorded shall kneel.',
    clearDescription:
      'Defeat the player who controlled the most territories at turn 5.',
    requirements: [{ type: 'defeat_leader_at_turn', turn: 5 }],
  },
  {
    title: 'The Weave-Walker',
    crypticDescription: 'Threads bind all. Follow them to the truth.',
    clearDescription: 'Create 10 Weave connections with strength 5 or higher.',
    requirements: [{ type: 'weave_connections', count: 10, minStrength: 5 }],
  },
  {
    title: 'The Void Touched',
    crypticDescription: 'Embrace the dark. Let it flow through you.',
    clearDescription:
      'Accumulate 100 total Void Entropy over the course of the game.',
    requirements: [
      { type: 'accumulate_resource', resource: 'void_entropy', amount: 100 },
    ],
  },
  {
    title: 'The Ley-Shaper',
    crypticDescription: 'Rivers of power await those who can see them.',
    clearDescription:
      'Control ley lines connecting 8 different territories simultaneously.',
    requirements: [{ type: 'ley_line_network', size: 8 }],
  },
];

function assignProphecies(
  player: PlayerId,
  gameState: GameState
): AssignedProphecies {
  const pool = gameState.prophecyPool;

  // Select 1 main prophecy
  const mainIndex = Math.floor(Math.random() * pool.mainProphecies.length);
  const mainProphecy = instantiateProphecy(
    pool.mainProphecies[mainIndex],
    player,
    gameState
  );
  pool.mainProphecies.splice(mainIndex, 1);

  // Select 2 secondary prophecies
  const secondaryProphecies: Prophecy[] = [];
  for (let i = 0; i < 2; i++) {
    const index = Math.floor(Math.random() * pool.secondaryProphecies.length);
    const secondary = instantiateProphecy(
      pool.secondaryProphecies[index],
      player,
      gameState
    );
    secondaryProphecies.push(secondary);
    pool.secondaryProphecies.splice(index, 1);
  }

  return {
    main: mainProphecy,
    secondary: secondaryProphecies,
    totalFulfillmentRequired: 4,
  };
}

function instantiateProphecy(
  template: ProphecyTemplate,
  player: PlayerId,
  gameState: GameState
): Prophecy {
  // Fill in specific details based on game state
  const instantiated = {
    ...template,
    id: generateProphecyId(),
    owner: player,
    progress: initializeProphecyProgress(template.requirements),
    fulfilled: false,
    revealed: false,
  };

  // Some prophecies need specific targets
  instantiated.requirements = template.requirements.map((req) => {
    if (req.type === 'defeat_player' && !req.target) {
      // Assign a random opponent
      const opponents = Array.from(gameState.players.keys()).filter(
        (p) => p !== player
      );
      return {
        ...req,
        target: opponents[Math.floor(Math.random() * opponents.length)],
      };
    }
    return req;
  });

  return instantiated;
}
```

### 4.3 Progress Tracking (Hidden from Opponents)

```typescript
interface ProphecyProgress {
  requirements: RequirementProgress[];
  percentComplete: number;
  turnsAtCurrentProgress: number;

  // Revelation tracking
  revelationEvents: RevelationEvent[];
}

interface RequirementProgress {
  requirementIndex: number;
  current: number;
  target: number;
  complete: boolean;
}

function updateProphecyProgress(
  player: PlayerId,
  gameState: GameState
): ProphecyUpdateResult {
  const prophecies = gameState.playerProphecies.get(player)!;
  const updates: ProphecyUpdate[] = [];

  // Check main prophecy
  const mainUpdate = checkProphecyProgress(prophecies.main, gameState);
  if (mainUpdate.changed) {
    updates.push(mainUpdate);
  }

  // Check secondary prophecies
  for (const secondary of prophecies.secondary) {
    const secondaryUpdate = checkProphecyProgress(secondary, gameState);
    if (secondaryUpdate.changed) {
      updates.push(secondaryUpdate);
    }
  }

  // Calculate total fulfillment
  let totalFulfillment = 0;
  if (prophecies.main.fulfilled) totalFulfillment += 2;
  for (const secondary of prophecies.secondary) {
    if (secondary.fulfilled) totalFulfillment += 1;
  }

  // Check for victory
  if (totalFulfillment >= 4) {
    return {
      updates,
      victoryAchieved: true,
      victoryType: 'prophetic_fulfillment',
    };
  }

  return { updates, victoryAchieved: false };
}

function checkProphecyProgress(
  prophecy: Prophecy,
  gameState: GameState
): ProphecyUpdate {
  const previousPercent = prophecy.progress.percentComplete;
  let allComplete = true;

  for (let i = 0; i < prophecy.requirements.length; i++) {
    const req = prophecy.requirements[i];
    const progress = prophecy.progress.requirements[i];

    // Check current status
    const current = evaluateRequirement(req, prophecy.owner, gameState);
    progress.current = current;
    progress.complete = current >= progress.target;

    if (!progress.complete) {
      allComplete = false;
    }
  }

  // Calculate new percentage
  const totalProgress = prophecy.progress.requirements.reduce(
    (sum, p) => sum + p.current / p.target,
    0
  );
  prophecy.progress.percentComplete =
    (totalProgress / prophecy.requirements.length) * 100;

  // Check for fulfillment
  if (allComplete && !prophecy.fulfilled) {
    prophecy.fulfilled = true;
    return {
      prophecy,
      changed: true,
      fulfilled: true,
      previousPercent,
      newPercent: 100,
    };
  }

  return {
    prophecy,
    changed: prophecy.progress.percentComplete !== previousPercent,
    fulfilled: false,
    previousPercent,
    newPercent: prophecy.progress.percentComplete,
  };
}
```

### 4.4 Partial Prophecy Revelation Mechanics

Prophecies become partially visible to other players through various mechanisms:

```typescript
interface RevelationEvent {
  prophecyId: ProphecyId;
  turn: number;
  revelationType: RevelationType;
  revealedTo: PlayerId[];
  revealedContent: string;
}

type RevelationType =
  | 'progress_milestone' // 50%, 75% progress
  | 'requirement_complete' // One requirement done
  | 'seer_vision' // Seer faction ability
  | 'weave_reading' // Weave analysis
  | 'fulfillment'; // Prophecy complete

function triggerRevelation(
  prophecy: Prophecy,
  type: RevelationType,
  gameState: GameState
): RevelationEvent {
  let revealedContent: string;
  let revealedTo: PlayerId[];

  switch (type) {
    case 'progress_milestone':
      // Reveal cryptic description and progress percentage
      revealedContent = `${prophecy.crypticDescription} (${Math.floor(prophecy.progress.percentComplete)}% complete)`;
      revealedTo = getAllOpponents(prophecy.owner, gameState);
      break;

    case 'requirement_complete':
      // Reveal one completed requirement (cryptically)
      const completedReq = prophecy.requirements.find(
        (_, i) => prophecy.progress.requirements[i].complete
      );
      revealedContent = generateCrypticRequirementHint(completedReq!);
      revealedTo = getAllOpponents(prophecy.owner, gameState);
      break;

    case 'seer_vision':
      // Seer player sees more detail
      revealedContent = prophecy.clearDescription;
      revealedTo = [gameState.seerPlayer]; // Only the Seer
      break;

    case 'weave_reading':
      // Players who invest in Weave analysis can learn more
      revealedContent = `Prophecy type: ${prophecy.type}, ${prophecy.requirements.length} requirements`;
      revealedTo = getPlayersWithWeaveReading(gameState);
      break;

    case 'fulfillment':
      // Full revelation when fulfilled
      revealedContent = prophecy.clearDescription;
      revealedTo = getAllPlayers(gameState);
      break;
  }

  const event: RevelationEvent = {
    prophecyId: prophecy.id,
    turn: gameState.currentTurn,
    revelationType: type,
    revealedTo,
    revealedContent,
  };

  prophecy.progress.revelationEvents.push(event);

  // Add to Weave
  addProphecyRevelationToWeave(event, prophecy, gameState);

  return event;
}

function generateCrypticRequirementHint(req: ProphecyRequirement): string {
  const hints: Record<string, string> = {
    control_territory: 'A specific place calls to them...',
    defeat_player: 'A rival must fall...',
    legendary_deed: 'A great deed awaits...',
    accumulate_resource: 'They gather power...',
    weave_connection: 'The threads tighten around them...',
    alliance_with: 'A pact must be sealed...',
    betray: 'Trust will be broken...',
    ritual_completion: 'Dark rites are prepared...',
    combat_victory: 'Blood must be spilled...',
  };

  return hints[req.type] || 'Fate moves in mysterious ways...';
}
```

### 4.5 Prophecy Completion Verification

```typescript
function verifyProphecyCompletion(
  player: PlayerId,
  gameState: GameState
): ProphecyVerificationResult {
  const prophecies = gameState.playerProphecies.get(player)!;

  // Verify each prophecy
  const verifications: ProphecyVerification[] = [];

  // Main prophecy
  verifications.push(verifyIndividualProphecy(prophecies.main, gameState));

  // Secondary prophecies
  for (const secondary of prophecies.secondary) {
    verifications.push(verifyIndividualProphecy(secondary, gameState));
  }

  // Calculate fulfillment
  let fulfillmentPoints = 0;
  for (const v of verifications) {
    if (v.valid && v.prophecy.fulfilled) {
      fulfillmentPoints += v.prophecy.fulfillmentValue;
    }
  }

  const victoryAchieved = fulfillmentPoints >= 4;

  if (victoryAchieved) {
    // Generate victory narrative
    return {
      verifications,
      fulfillmentPoints,
      victoryAchieved,
      victoryNarrative: generatePropheticVictoryNarrative(
        player,
        prophecies,
        gameState
      ),
    };
  }

  return {
    verifications,
    fulfillmentPoints,
    victoryAchieved,
  };
}
```

---

## 5. Weave Mastery

_"History remembers. The Weave knows who shaped the age."_

Weave Mastery represents narrative dominance - accumulating the most positive
Weave connections and becoming the central figure of the campaign's story.

### 5.1 Victory Condition

**Threshold:** Achieve Weave Mastery score ≥ 100 while having the highest score.

**Weave Mastery Score Calculation:**

- Positive Weave connections (protagonist role): +value
- Heroic deeds recorded: +5 to +15 each
- Alliance threads (kept): +10 each
- Negative connections (antagonist role): +1 per 2 points
- Fulfilled prophecy threads: +20
- Betrayal threads (committed): -5 each

### 5.2 Connection Value Calculation Algorithm

```typescript
interface WeaveMasteryScore {
  player: PlayerId;

  // Positive contributions
  positiveConnections: ConnectionScore[];
  heroicDeeds: DeedScore[];
  alliances: AllianceScore[];
  prophecyBonus: number;

  // Negative contributions
  negativeConnections: ConnectionScore[];
  betrayals: BetrayalScore[];

  // Totals
  grossPositive: number;
  grossNegative: number;
  netScore: number;
}

interface ConnectionScore {
  connectionId: string;
  sourceNode: WeaveNodeId;
  targetNode: WeaveNodeId;
  baseStrength: number;
  roleModifier: number; // +1 protagonist, -1 antagonist
  ageModifier: number; // Older connections worth more
  totalValue: number;
}

function calculateWeaveMasteryScore(
  player: PlayerId,
  weave: WeaveSystem
): WeaveMasteryScore {
  const score: WeaveMasteryScore = {
    player,
    positiveConnections: [],
    heroicDeeds: [],
    alliances: [],
    prophecyBonus: 0,
    negativeConnections: [],
    betrayals: [],
    grossPositive: 0,
    grossNegative: 0,
    netScore: 0,
  };

  // Get all connections involving this player
  const playerNode = weave.getPlayerNode(player);
  const connections = weave.getConnectionsForNode(playerNode.id);

  for (const connection of connections) {
    const roleModifier =
      connection.playerRole === 'protagonist'
        ? 1.5
        : connection.playerRole === 'antagonist'
          ? 0.5
          : 1.0;

    const ageBonus = Math.min(20, Math.floor(connection.ageInTurns / 5));

    const connectionScore: ConnectionScore = {
      connectionId: connection.id,
      sourceNode: connection.source,
      targetNode: connection.target,
      baseStrength: connection.strength,
      roleModifier,
      ageModifier: ageBonus,
      totalValue: Math.floor(connection.strength * roleModifier) + ageBonus,
    };

    if (connectionScore.totalValue > 0) {
      score.positiveConnections.push(connectionScore);
      score.grossPositive += connectionScore.totalValue;
    } else {
      score.negativeConnections.push(connectionScore);
      score.grossNegative += Math.abs(connectionScore.totalValue);
    }
  }

  // Add heroic deeds
  const deeds = weave.getHeroicDeeds(player);
  for (const deed of deeds) {
    const deedScore: DeedScore = {
      deedId: deed.id,
      deedType: deed.deedType,
      baseValue: deed.weaveImpact,
      fameMultiplier: 1 + deed.fameGenerated / 100,
      totalValue: Math.floor(deed.weaveImpact * (1 + deed.fameGenerated / 100)),
    };
    score.heroicDeeds.push(deedScore);
    score.grossPositive += deedScore.totalValue;
  }

  // Add alliance bonuses
  const alliances = weave.getAllianceThreads(player);
  for (const alliance of alliances) {
    if (alliance.status === 'honored') {
      score.alliances.push({
        allianceId: alliance.id,
        partner: alliance.partner,
        duration: alliance.duration,
        value: 10 + Math.floor(alliance.duration / 3),
      });
      score.grossPositive += 10 + Math.floor(alliance.duration / 3);
    }
  }

  // Add prophecy bonus
  const fulfilledProphecies = weave.getFulfilledProphecies(player);
  score.prophecyBonus = fulfilledProphecies.length * 20;
  score.grossPositive += score.prophecyBonus;

  // Subtract betrayals
  const betrayals = weave.getBetrayalThreads(player);
  for (const betrayal of betrayals) {
    if (betrayal.betrayer === player) {
      score.betrayals.push({
        betrayalId: betrayal.id,
        victim: betrayal.victim,
        severity: betrayal.severity,
        penalty: 5 * betrayal.severity,
      });
      score.grossNegative += 5 * betrayal.severity;
    }
  }

  score.netScore = score.grossPositive - score.grossNegative;

  return score;
}
```

### 5.3 Real-Time Weave State Tracking

```typescript
interface WeaveStateTracker {
  currentScores: Map<PlayerId, WeaveMasteryScore>;
  leaderboard: PlayerId[];

  // Threshold tracking
  masteryThreshold: number; // 100
  playersAboveThreshold: PlayerId[];

  // Change tracking
  lastUpdateTurn: number;
  recentChanges: WeaveScoreChange[];
}

interface WeaveScoreChange {
  player: PlayerId;
  turn: number;
  previousScore: number;
  newScore: number;
  reason: string;
}

function updateWeaveStateTracker(gameState: GameState): void {
  const tracker = gameState.weaveTracker;
  const weave = gameState.weave;

  // Recalculate all scores
  for (const player of gameState.players.keys()) {
    const previousScore = tracker.currentScores.get(player)?.netScore ?? 0;
    const newScore = calculateWeaveMasteryScore(player, weave);

    // Track changes
    if (newScore.netScore !== previousScore) {
      tracker.recentChanges.push({
        player,
        turn: gameState.currentTurn,
        previousScore,
        newScore: newScore.netScore,
        reason: determineChangeReason(previousScore, newScore),
      });
    }

    tracker.currentScores.set(player, newScore);
  }

  // Update leaderboard
  tracker.leaderboard = Array.from(tracker.currentScores.entries())
    .sort((a, b) => b[1].netScore - a[1].netScore)
    .map(([player]) => player);

  // Update threshold tracking
  tracker.playersAboveThreshold = tracker.leaderboard.filter(
    (player) =>
      tracker.currentScores.get(player)!.netScore >= tracker.masteryThreshold
  );

  tracker.lastUpdateTurn = gameState.currentTurn;

  // Check for victory
  checkWeaveMasteryVictory(tracker, gameState);
}

function checkWeaveMasteryVictory(
  tracker: WeaveStateTracker,
  gameState: GameState
): PlayerId | null {
  if (tracker.playersAboveThreshold.length === 0) {
    return null;
  }

  // Must be sole leader above threshold
  if (tracker.playersAboveThreshold.length === 1) {
    const winner = tracker.playersAboveThreshold[0];
    const winnerScore = tracker.currentScores.get(winner)!.netScore;
    const secondPlace =
      tracker.currentScores.get(tracker.leaderboard[1])?.netScore ?? 0;

    // Must have at least 10 point lead
    if (winnerScore - secondPlace >= 10) {
      return winner;
    }
  }

  return null;
}
```

### 5.4 Mastery Threshold Determination

```typescript
interface MasteryThresholdConfig {
  baseThreshold: number; // 100

  // Dynamic adjustments
  perPlayerAdjustment: number; // +10 per player beyond 2
  perTurnReduction: number; // -0.5 per turn after turn 20
  minimumThreshold: number; // Never below 60

  // Tie-breaking configuration
  tieBreakMethod: 'heroic_deeds' | 'oldest_connection' | 'alliance_count';
}

const DEFAULT_MASTERY_CONFIG: MasteryThresholdConfig = {
  baseThreshold: 100,
  perPlayerAdjustment: 10,
  perTurnReduction: 0.5,
  minimumThreshold: 60,
  tieBreakMethod: 'heroic_deeds',
};

function getEffectiveMasteryThreshold(
  config: MasteryThresholdConfig,
  playerCount: number,
  currentTurn: number
): number {
  let threshold = config.baseThreshold;

  // Adjust for player count
  threshold += (playerCount - 2) * config.perPlayerAdjustment;

  // Reduce over time (game shouldn't drag on forever)
  if (currentTurn > 20) {
    threshold -= (currentTurn - 20) * config.perTurnReduction;
  }

  return Math.max(config.minimumThreshold, threshold);
}
```

### 5.5 Tie-Breaking Rules

```typescript
function resolveWeaveMasteryTie(
  tiedPlayers: PlayerId[],
  gameState: GameState
): PlayerId {
  const config = gameState.victoryConfig.weaveMastery;
  const weave = gameState.weave;

  switch (config.tieBreakMethod) {
    case 'heroic_deeds':
      // Player with most heroic deeds wins
      let mostDeeds = 0;
      let deedWinner: PlayerId | null = null;

      for (const player of tiedPlayers) {
        const deeds = weave.getHeroicDeeds(player).length;
        if (deeds > mostDeeds) {
          mostDeeds = deeds;
          deedWinner = player;
        }
      }

      if (deedWinner) return deedWinner;
    // Fall through if still tied

    case 'oldest_connection':
      // Player with oldest positive connection wins
      let oldestAge = 0;
      let ageWinner: PlayerId | null = null;

      for (const player of tiedPlayers) {
        const connections = weave.getConnectionsForNode(
          weave.getPlayerNode(player).id
        );
        const oldest = Math.max(...connections.map((c) => c.ageInTurns));
        if (oldest > oldestAge) {
          oldestAge = oldest;
          ageWinner = player;
        }
      }

      if (ageWinner) return ageWinner;
    // Fall through if still tied

    case 'alliance_count':
      // Player with most honored alliances wins
      let mostAlliances = 0;
      let allianceWinner: PlayerId | null = null;

      for (const player of tiedPlayers) {
        const alliances = weave
          .getAllianceThreads(player)
          .filter((a) => a.status === 'honored').length;
        if (alliances > mostAlliances) {
          mostAlliances = alliances;
          allianceWinner = player;
        }
      }

      if (allianceWinner) return allianceWinner;
      break;
  }

  // Ultimate tiebreaker: random
  return tiedPlayers[Math.floor(Math.random() * tiedPlayers.length)];
}
```

---

## 6. Faction-Specific Victory Modifiers

Each faction has unique modifiers to victory conditions based on their
playstyle.

### 6.1 Victory Modifier Summary

| Faction   | Dominion      | Resonance         | Void           | Prophecy            | Weave               |
| --------- | ------------- | ----------------- | -------------- | ------------------- | ------------------- |
| Guardian  | -5% threshold | -                 | Cannot pursue  | -                   | Alliance bonus +5   |
| Shadow    | +5% threshold | -                 | -1 turn ritual | Betrayal +10 VP     | -                   |
| Seer      | -             | -                 | -              | See 1 opponent's    | +20% base           |
| Weaver    | +5% threshold | Ritual path       | -1 component   | Can swap prophecy   | Can manipulate      |
| Mystic    | -             | -1 nexus needed   | -              | -                   | -                   |
| Champion  | -5% threshold | -                 | Cannot pursue  | Combat prophecies   | -                   |
| Harbinger | Cannot pursue | -                 | -2 turn ritual | -                   | -20% base           |
| Oracle    | -             | -                 | -              | See all prophecies  | Revelation bonus    |
| Herald    | -             | Diplomatic nexus  | -              | Alliance prophecies | +30% from alliances |
| Sage      | -             | Ritual path bonus | -              | Research prophecies | Knowledge bonus     |
| Warden    | Balance bonus | Balance bonus     | -              | Balance prophecies  | Balance bonus       |
| Exemplar  | -             | -                 | -              | Virtue prophecies   | +50% from deeds     |

```typescript
interface FactionVictoryModifiers {
  factionId: FactionId;

  dominionModifiers: {
    thresholdAdjustment: number; // % change
    canPursue: boolean;
    specialCondition?: string;
  };

  resonanceModifiers: {
    nexusRequirementAdjustment: number;
    ritualPathBonus: number;
    canPursue: boolean;
    specialCondition?: string;
  };

  voidModifiers: {
    ritualTurnAdjustment: number;
    componentAdjustment: number;
    canPursue: boolean;
    specialCondition?: string;
  };

  prophecyModifiers: {
    canSeeOpponentProphecies: number; // How many
    prophecyTypeBonus: ProphecyType[];
    canSwapProphecy: boolean;
    specialCondition?: string;
  };

  weaveModifiers: {
    baseScoreMultiplier: number;
    allianceBonus: number;
    deedBonus: number;
    canManipulateWeave: boolean;
    specialCondition?: string;
  };
}

const FACTION_VICTORY_MODIFIERS: Map<FactionId, FactionVictoryModifiers> =
  new Map([
    [
      'guardian',
      {
        factionId: 'guardian',
        dominionModifiers: {
          thresholdAdjustment: -0.05,
          canPursue: true,
          specialCondition: 'Defensive territories count double',
        },
        resonanceModifiers: {
          nexusRequirementAdjustment: 0,
          ritualPathBonus: 0,
          canPursue: true,
        },
        voidModifiers: {
          ritualTurnAdjustment: 0,
          componentAdjustment: 0,
          canPursue: false,
          specialCondition: 'Cannot pursue Void Ascension',
        },
        prophecyModifiers: {
          canSeeOpponentProphecies: 0,
          prophecyTypeBonus: ['defensive'],
          canSwapProphecy: false,
        },
        weaveModifiers: {
          baseScoreMultiplier: 1.0,
          allianceBonus: 5,
          deedBonus: 0,
          canManipulateWeave: false,
        },
      },
    ],
    [
      'shadow',
      {
        factionId: 'shadow',
        dominionModifiers: {
          thresholdAdjustment: 0.05,
          canPursue: true,
        },
        resonanceModifiers: {
          nexusRequirementAdjustment: 0,
          ritualPathBonus: 0,
          canPursue: true,
        },
        voidModifiers: {
          ritualTurnAdjustment: -1,
          componentAdjustment: 0,
          canPursue: true,
          specialCondition: 'Ritual completes 1 turn faster',
        },
        prophecyModifiers: {
          canSeeOpponentProphecies: 0,
          prophecyTypeBonus: ['betrayal', 'assassination'],
          canSwapProphecy: false,
          specialCondition: 'Betrayal prophecies worth +10 VP',
        },
        weaveModifiers: {
          baseScoreMultiplier: 1.0,
          allianceBonus: 0,
          deedBonus: 0,
          canManipulateWeave: false,
        },
      },
    ],
    // ... additional factions
  ]);

function applyFactionVictoryModifiers(
  player: PlayerId,
  victoryCondition: VictoryConditionType,
  baseConfig: VictoryConfig,
  gameState: GameState
): VictoryConfig {
  const faction = gameState.players.get(player)!.faction;
  const modifiers = FACTION_VICTORY_MODIFIERS.get(faction);

  if (!modifiers) return baseConfig;

  const modifiedConfig = { ...baseConfig };

  switch (victoryCondition) {
    case 'dominion':
      if (!modifiers.dominionModifiers.canPursue) {
        modifiedConfig.enabled = false;
      } else {
        modifiedConfig.threshold +=
          modifiers.dominionModifiers.thresholdAdjustment;
      }
      break;

    case 'resonance_supremacy':
      if (!modifiers.resonanceModifiers.canPursue) {
        modifiedConfig.enabled = false;
      } else {
        modifiedConfig.nexusRequirement +=
          modifiers.resonanceModifiers.nexusRequirementAdjustment;
      }
      break;

    case 'void_ascension':
      if (!modifiers.voidModifiers.canPursue) {
        modifiedConfig.enabled = false;
      } else {
        modifiedConfig.ritualTurns +=
          modifiers.voidModifiers.ritualTurnAdjustment;
        modifiedConfig.componentsRequired +=
          modifiers.voidModifiers.componentAdjustment;
      }
      break;

    case 'prophetic_fulfillment':
      // Apply prophecy type bonuses during prophecy assignment
      break;

    case 'weave_mastery':
      modifiedConfig.scoreMultiplier =
        modifiers.weaveModifiers.baseScoreMultiplier;
      modifiedConfig.allianceBonus = modifiers.weaveModifiers.allianceBonus;
      modifiedConfig.deedBonus = modifiers.weaveModifiers.deedBonus;
      break;
  }

  return modifiedConfig;
}
```

---

## 7. Victory UI/UX

### 7.1 Victory Progress Display

```typescript
interface VictoryProgressDisplay {
  player: PlayerId;

  conditions: VictoryConditionProgress[];

  nearestVictory: VictoryConditionType;
  turnsToVictory: number | null; // Estimate

  threats: VictoryThreat[]; // Other players close to winning
}

interface VictoryConditionProgress {
  type: VictoryConditionType;
  enabled: boolean;
  currentProgress: number; // 0-100%
  requirement: string;
  details: string[];

  // Visual indicators
  color: 'red' | 'yellow' | 'green'; // Red < 33%, Yellow 33-66%, Green > 66%
  trending: 'up' | 'down' | 'stable';
}

interface VictoryThreat {
  player: PlayerId;
  condition: VictoryConditionType;
  progress: number;
  turnsToVictory: number | null;
  counterOptions: string[];
}
```

### 7.2 Victory Announcement

```typescript
interface VictoryAnnouncement {
  victor: PlayerId;
  faction: FactionId;
  victoryType: VictoryConditionType;

  // Narrative
  title: string;
  description: string;
  epilogue: string;

  // Statistics
  turnsPlayed: number;
  territoriesControlled: number;
  battlesWon: number;
  heroicDeeds: number;
  alliances: number;
  betrayals: number;

  // Weave summary
  majorWeaveThreads: WeaveThread[];
  finalWeaveScore: number;
}

function generateVictoryAnnouncement(
  victor: PlayerId,
  victoryType: VictoryConditionType,
  gameState: GameState
): VictoryAnnouncement {
  const player = gameState.players.get(victor)!;

  const titles: Record<VictoryConditionType, string> = {
    dominion: `${player.name} Achieves Total Dominion`,
    resonance_supremacy: `${player.name} Claims Resonance Supremacy`,
    void_ascension: `${player.name} Ascends Through the Void`,
    prophetic_fulfillment: `${player.name} Fulfills the Prophecy`,
    weave_mastery: `${player.name} Masters the Weave`,
  };

  return {
    victor,
    faction: player.faction,
    victoryType,

    title: titles[victoryType],
    description: generateVictoryDescription(victor, victoryType, gameState),
    epilogue: generateVictoryEpilogue(victor, victoryType, gameState),

    turnsPlayed: gameState.currentTurn,
    territoriesControlled: countPlayerTerritories(victor, gameState),
    battlesWon: getBattleStats(victor, gameState).won,
    heroicDeeds: gameState.weave.getHeroicDeeds(victor).length,
    alliances: gameState.weave
      .getAllianceThreads(victor)
      .filter((a) => a.status === 'honored').length,
    betrayals: gameState.weave
      .getBetrayalThreads(victor)
      .filter((b) => b.betrayer === victor).length,

    majorWeaveThreads: getMajorWeaveThreads(victor, gameState),
    finalWeaveScore: calculateWeaveMasteryScore(victor, gameState.weave)
      .netScore,
  };
}
```

---

## Appendix A: Victory Condition Quick Reference

| Condition | Threshold               | Declaration   | Challenge Period     |
| --------- | ----------------------- | ------------- | -------------------- |
| Dominion  | 60% Full Dominion       | Start of turn | 2 rounds             |
| Resonance | All major nexuses       | Instant       | None                 |
| Void      | Complete Entropy Spiral | After 5 turns | None (can interrupt) |
| Prophecy  | 4 fulfillment points    | On completion | None                 |
| Weave     | 100+ score, highest     | End of turn   | 1 round              |

---

## Appendix B: Implementation Checklist

- [ ] Implement DominionTracker with real-time updates
- [ ] Create NexusTracker for Resonance Supremacy
- [ ] Build Entropy Spiral ritual state machine
- [ ] Implement prophecy assignment and tracking system
- [ ] Create Weave Mastery scoring algorithm
- [ ] Add faction-specific victory modifiers
- [ ] Build victory progress UI components
- [ ] Create victory announcement system
- [ ] Add Weave integration for all victory events
- [ ] Implement multiplayer victory validation
- [ ] Add tests for all victory conditions
- [ ] Create AI victory pursuit logic

---

_Document created as part of The Veil War (Mode 1) game design for Veilborn
Chronicles._
