> ## Documentation Index
> Fetch the complete documentation index at: https://hyperscape-ai.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Game Systems Overview

> How Hyperscape game systems work

## Systems Architecture

Hyperscape game logic is implemented through **Systems** — classes that process entities and components each game tick. Systems are organized by domain and split between client, server, and shared execution contexts.

```
packages/shared/src/systems/
├── client/           # Client-only systems (rendering, input)
├── server/           # Server-only systems (auth, database)
└── shared/           # Shared systems (combat, economy, skills)
    ├── character/    # Character management
    ├── combat/       # Combat mechanics (20+ files)
    ├── death/        # Death and respawn
    ├── economy/      # Banks, shops, inventory
    ├── entities/     # Entity lifecycle
    ├── infrastructure/
    ├── interaction/  # Player interactions
    ├── movement/     # Movement, collision, pathfinding
    ├── presentation/ # Visual effects
    ├── progression/  # Quest system
    ├── tick/         # Game tick processing
    └── world/        # World management
```

***

## System Base Class

All systems extend `SystemBase` which provides:

* Dependency management (required/optional systems)
* Lifecycle hooks (init, update, cleanup)
* World reference for entity queries
* Auto-cleanup on destroy

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// From packages/shared/src/systems/shared/SystemBase.ts
export class CombatSystem extends SystemBase {
  constructor(world: World) {
    super(world, {
      name: "combat",
      dependencies: {
        required: ["entity-manager"],
        optional: ["mob-npc"],
      },
      autoCleanup: true,
    });
  }
}
```

***

## Core Game Systems

### Combat System

**Location:** `systems/shared/combat/`

The combat system implements OSRS-style tick-based combat with 20+ supporting files:

| File                        | Purpose                                  |
| --------------------------- | ---------------------------------------- |
| `CombatSystem.ts`           | Main combat orchestration (\~2100 lines) |
| `DamageCalculator.ts`       | OSRS damage formulas                     |
| `AggroSystem.ts`            | Mob aggression behavior                  |
| `CombatStateService.ts`     | Combat state management                  |
| `CombatAnimationManager.ts` | Attack animations                        |
| `CombatRotationManager.ts`  | Entity facing                            |
| `CombatAntiCheat.ts`        | Cheat detection                          |
| `CombatRateLimiter.ts`      | Attack rate limiting                     |
| `PlayerDeathSystem.ts`      | Player death handling                    |
| `MobDeathSystem.ts`         | Mob death and drops                      |
| `RangeSystem.ts`            | Ranged combat                            |
| `PidManager.ts`             | Player ID priority (OSRS PID)            |

<Tip>
  Combat runs on a 600ms tick cycle, matching Old School RuneScape exactly.
</Tip>

### Duel Arena System

**Location:** `packages/server/src/systems/DuelSystem/`

Player-vs-player dueling with stakes and customizable rules:

| Component            | Purpose                                        |
| -------------------- | ---------------------------------------------- |
| `DuelSystem`         | Main orchestrator, state machine (1600+ lines) |
| `DuelSessionManager` | Session CRUD, player mapping (290 lines)       |
| `PendingDuelManager` | Challenge lifecycle, timeouts (310 lines)      |
| `ArenaPoolManager`   | Arena reservation, spawn points (260 lines)    |
| `DuelCombatResolver` | Combat resolution, stake transfers (280 lines) |

**Features:**

* 10 toggleable combat rules (no ranged, no food, no forfeit, etc.)
* 11 equipment slot restrictions
* Item staking with anti-scam protection
* 6 dedicated arenas with wall collision
* Disconnect handling (30s grace period)
* Comprehensive unit tests (1700+ lines)

<Info>
  See [Duel Arena System](/wiki/game-systems/duel-arena) for complete documentation.
</Info>

### Economy Systems

**Location:** `systems/shared/economy/`

Handles all economic interactions:

* **Banking** — Deposit, withdraw, note conversion (480-slot bank with tabs)
* **Shops** — Buy/sell with general stores
* **Trading** — Player-to-player item exchange (see `TradingSystem`)
* **Inventory** — 28-slot management with stacking
* **Loot** — Item drops and ground items

### Movement & Collision System

**Location:** `systems/shared/movement/`

Implements tile-based movement and OSRS-accurate collision:

* **TileSystem.ts** — Grid-based coordinate system
* **CollisionMatrix.ts** — Zone-based collision storage (8×8 tile zones)
* **CollisionFlags.ts** — Bitmask flags (BLOCKED, WATER, OCCUPIED, walls)
* **EntityOccupancyMap.ts** — Entity tracking with collision integration
* **BFSPathfinder.ts** — Breadth-first search pathfinding around obstacles
* **ChasePathfinding.ts** — Combat chase behavior
* **WanderBehavior.ts** — NPC wandering AI

**Collision Features:**

* Static object blocking (trees, rocks, stations)
* Multi-tile footprints (2×2 furnaces, large resources)
* Directional walls (for future dungeons)
* Network synchronization (zone serialization)
* Safespotting mechanics (OSRS-accurate)

### World Systems

**Location:** `systems/shared/world/`

Manages world generation and environment:

* **TerrainSystem.ts** — Procedural terrain with flat zones for stations (see [Terrain System](/wiki/game-systems/terrain))
* **WaterSystem.ts** — Water rendering and physics
* **VegetationSystem.ts** — Procedural tree/rock placement
* **RoadNetworkSystem.ts** — Road generation between towns
* **SkySystem.ts** — Day/night cycle
* **Environment.ts** — Lighting and atmosphere

**Terrain Features:**

* Noise-based procedural generation (50m max height)
* Flat zones under stations with smooth blending
* Spatial indexing for O(1) flat zone lookup
* Biome-based height modulation
* Water threshold detection

### Character Systems

**Location:** `systems/shared/character/`

Player character management:

* **Stats tracking** — Levels, XP, combat level
* **Equipment** — Gear slots and bonuses
* **Skills** — 13 trainable skills (6 combat, 3 gathering, 4 artisan)

### Progression Systems

**Location:** `systems/shared/progression/`

Player progression and achievement tracking:

* **Quest System** — OSRS-style quests with multi-stage objectives, requirements, and rewards
* **Quest Points** — Accumulated from quest completions
* **XP Lamps** — Quest reward items that grant XP to chosen skill

### Quest System

**Location:** `systems/shared/progression/QuestSystem.ts`

OSRS-style quest system with multi-stage quests:

* **Quest definitions** — JSON manifest-driven quest content
* **Progress tracking** — Per-player database persistence
* **Stage types** — Dialogue, kill, gather, interact, craft
* **Quest points** — Accumulated across completions
* **Security** — HMAC kill token validation, audit logging
* **Performance** — O(1) stage lookups, object spread elimination

### Duel Arena System

**Location:** `systems/server/DuelSystem/`

Server-authoritative PvP dueling system with OSRS-accurate mechanics:

* **Challenge Management** — 30-second challenge requests with distance validation
* **Arena Pooling** — 6 dedicated arenas with automatic reservation
* **Rules Negotiation** — 10 combat rules + 11 equipment restrictions
* **Stake System** — Item staking with anti-scam protections
* **Combat Resolution** — Death handling, forfeit mechanics, stake transfers
* **Audit Logging** — Complete economic tracking for all duel outcomes

**Key Components:**

* `DuelSystem.ts` — Main orchestrator (1,609 lines)
* `PendingDuelManager.ts` — Challenge lifecycle management
* `ArenaPoolManager.ts` — Arena reservation and collision
* `DuelSessionManager.ts` — Session CRUD operations
* `DuelCombatResolver.ts` — Outcome resolution and stake transfers

<Tip>
  See the [Duel Arena documentation](/wiki/game-systems/duel-arena) for complete implementation details.
</Tip>

***

## Combat Constants

The combat system uses OSRS-accurate constants:

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// From packages/shared/src/constants/CombatConstants.ts
export const COMBAT_CONSTANTS = {
  // Tick System
  TICK_DURATION_MS: 600,
  
  // Ranges (tiles)
  MELEE_RANGE: 2,
  RANGED_RANGE: 10,
  PICKUP_RANGE: 2.5,
  
  // Combat Timing (ticks)
  DEFAULT_ATTACK_SPEED_TICKS: 4,      // 2.4 seconds
  COMBAT_TIMEOUT_TICKS: 17,           // 10.2 seconds
  HEALTH_REGEN_INTERVAL_TICKS: 100,   // 60 seconds
  
  // Damage Formulas (OSRS)
  BASE_CONSTANT: 64,
  EFFECTIVE_LEVEL_CONSTANT: 8,
  DAMAGE_DIVISOR: 640,
  MIN_DAMAGE: 0,
  MAX_DAMAGE: 200,
  
  // XP Rates
  XP: {
    COMBAT_XP_PER_DAMAGE: 4,
    HITPOINTS_XP_PER_DAMAGE: 1.33,
    CONTROLLED_XP_PER_DAMAGE: 1.33,
  },
  
  // Death
  DEATH: {
    ANIMATION_TICKS: 8,
    COOLDOWN_TICKS: 17,
    DEFAULT_RESPAWN_TOWN: "Central Haven",
  },
} as const;
```

### Level Constants

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// From packages/shared/src/constants/CombatConstants.ts
export const LEVEL_CONSTANTS = {
  DEFAULT_COMBAT_LEVEL: 3,
  MIN_COMBAT_LEVEL: 3,
  MAX_LEVEL: 99,
  
  XP_BASE: 50,
  XP_GROWTH_FACTOR: 8,
  
  COMBAT_LEVEL_WEIGHTS: {
    DEFENSE_WEIGHT: 0.25,
    OFFENSE_WEIGHT: 0.325,
    RANGED_MULTIPLIER: 1.5,
  },
} as const;
```

***

## Skills System

Hyperscape implements 14 skills with OSRS-accurate mechanics:

### Combat Skills

| Skill            | Purpose                                 |
| ---------------- | --------------------------------------- |
| **Attack**       | Melee accuracy and weapon requirements  |
| **Strength**     | Melee damage                            |
| **Defense**      | Damage reduction and armor requirements |
| **Constitution** | Health points (HP)                      |
| **Ranged**       | Ranged combat accuracy and damage       |
| **Prayer**       | Prayer points and combat bonuses        |

### Gathering Skills

| Skill           | Purpose                   |
| --------------- | ------------------------- |
| **Woodcutting** | Chop trees for logs       |
| **Fishing**     | Catch fish at water spots |
| **Mining**      | Mine ore from rocks       |

### Artisan Skills

| Skill            | Purpose                                  |
| ---------------- | ---------------------------------------- |
| **Firemaking**   | Light fires from logs                    |
| **Cooking**      | Cook raw fish for healing                |
| **Smithing**     | Smelt ores into bars and smith equipment |
| **Fletching**    | Create ranged weapons and ammunition     |
| **Runecrafting** | Craft runes for magic combat             |

### Support Skills

| Skill       | Purpose                                            |
| ----------- | -------------------------------------------------- |
| **Agility** | Traverse the world to improve stamina regeneration |

<Info>
  Each skill has independent XP tracking and levels 1-99 following OSRS XP curves. Agility is unique in that it trains passively as you move around the world.
</Info>

***

## Quest System

**Location:** `systems/shared/progression/`

OSRS-style quest system with multi-stage progression:

| Component             | Purpose                                             |
| --------------------- | --------------------------------------------------- |
| `QuestSystem.ts`      | Quest logic and progression tracking (\~1100 lines) |
| `QuestRepository.ts`  | Database persistence for quest progress             |
| `quest-types.ts`      | Quest definitions and validation                    |
| `quest-interfaces.ts` | ISP interfaces (IQuestQuery, IQuestActions)         |

**Features:**

* Multi-stage quests (kill, gather, interact, dialogue)
* Quest requirements (prerequisite quests, skill levels, items)
* Quest points and rewards (items, XP)
* HMAC kill token validation (prevents spoofing)
* Rate limiting (5/sec list, 10/sec detail, 3/sec accept)
* Quest audit logging for security
* O(1) stage lookup caches for performance

**Database Tables:**

* `quest_progress` — Player quest state (status, current stage, progress)
* `quest_audit_log` — Immutable audit trail for all quest actions
* `characters.questPoints` — Total quest points earned

***

## Attack Styles

Players choose how combat XP is distributed:

| Style          | XP Distribution         |
| -------------- | ----------------------- |
| **Accurate**   | Attack + Constitution   |
| **Aggressive** | Strength + Constitution |
| **Defensive**  | Defense + Constitution  |
| **Controlled** | Equal split across all  |

***

## Mob Aggression

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// From packages/shared/src/constants/CombatConstants.ts
export const AGGRO_CONSTANTS = {
  DEFAULT_BEHAVIOR: "passive",
  AGGRO_UPDATE_INTERVAL_MS: 100,
  ALWAYS_AGGRESSIVE_LEVEL: 999,  // Ignores level difference
} as const;
```

| Behavior              | Description                        |
| --------------------- | ---------------------------------- |
| **Passive**           | Never attacks first                |
| **Aggressive**        | Attacks players in detection range |
| **Level-gated**       | Ignores high-level players         |
| **Always Aggressive** | Attacks regardless of level        |

***

## Event System

Systems communicate through typed events:

```typescript theme={"theme":{"light":"github-light","dark":"css-variables"}}
// Event types from packages/shared/src/types/events/events.ts
export enum EventType {
  // Combat
  COMBAT_START = "combat:start",
  COMBAT_END = "combat:end",
  DAMAGE_DEALT = "damage:dealt",
  
  // Inventory
  INVENTORY_ADD = "inventory:add",
  INVENTORY_REMOVE = "inventory:remove",
  
  // Skills
  XP_GAINED = "xp:gained",
  LEVEL_UP = "level:up",
  
  // ... many more
}
```

***

***

## Detailed Documentation

<CardGroup cols={2}>
  <Card title="Combat System" icon="swords" href="/wiki/game-systems/combat">
    OSRS-accurate damage formulas, attack styles, aggro system, and death mechanics.
  </Card>

  <Card title="Duel Arena" icon="shield-halved" href="/wiki/game-systems/duel-arena">
    Player-vs-player dueling with rules, stakes, arenas, and anti-scam protections.
  </Card>

  <Card title="Skills & Progression" icon="chart-line" href="/wiki/game-systems/skills">
    RuneScape XP curves, leveling, combat level formula, and skill requirements.
  </Card>

  <Card title="Trading System" icon="handshake" href="/wiki/game-systems/trading">
    Player-to-player trading with two-screen confirmation and security features.
  </Card>

  <Card title="Social System" icon="users" href="/wiki/game-systems/social">
    Friend management, private messaging, and player interactions.
  </Card>

  <Card title="Tile Movement" icon="route" href="/wiki/game-systems/movement">
    Discrete tile-based movement, pathfinding, and OSRS melee range rules.
  </Card>
</CardGroup>
