# Feature Documentation

## Core Systems

### 1. Network Manager (Autoload)
**File**: `scripts/network_manager.gd`

**Purpose**: Centralized multiplayer networking system

**Key Features**:
- Host/Join game functionality
- Player registration and tracking
- Automatic peer synchronization
- Connection state management

**Public Methods**:
```gdscript
host_game(port: int = 7777) -> bool
join_game(address: String, port: int = 7777) -> bool
disconnect_from_game()
set_local_player_count(count: int)
get_all_player_ids() -> Array
get_player_info(peer_id: int) -> Dictionary
```

**Signals**:
- `player_connected(peer_id, player_info)`
- `player_disconnected(peer_id)`
- `connection_failed()`
- `connection_succeeded()`

**Implementation Details**:
- Uses ENet for reliable UDP networking
- Server-authoritative architecture
- RPC calls for state synchronization
- Supports up to 8 concurrent connections

---

### 2. Player Manager
**File**: `scripts/player_manager.gd`

**Purpose**: Manages player spawning and lifecycle

**Key Features**:
- Spawns players for each peer
- Handles local vs remote players
- Manages player despawning on disconnect
- Provides player queries

**Public Methods**:
```gdscript
spawn_players_for_peer(peer_id: int, local_count: int)
spawn_player(peer_id: int, local_index: int)
despawn_players_for_peer(peer_id: int)
get_local_players() -> Array
get_all_players() -> Array
```

**Implementation Details**:
- Circular spawn point distribution
- Unique player IDs: "{peer_id}_{local_index}"
- Automatic authority assignment
- Scene instancing for player creation

---

### 3. Player Controller
**File**: `scripts/player.gd`

**Purpose**: Character movement and interaction

**Key Features**:
- Top-down movement
- Multi-input support (keyboard + multiple gamepads)
- Grab/throw mechanics
- Network synchronization
- Physics-based interactions

**Exported Properties**:
```gdscript
@export var move_speed: float = 300.0
@export var grab_range: float = 80.0
@export var throw_force: float = 600.0
```

**Network Properties**:
```gdscript
var peer_id: int
var local_player_index: int
var is_local_player: bool
var input_device: int  # -1 = keyboard, 0+ = gamepad index
```

**Interaction System**:
- Area2D-based grab detection
- Hold offset for smooth carrying
- Direction-based throwing
- Can grab both objects and players

**Input Mapping**:
- Player 0: Keyboard (device -1)
- Player 1+: Gamepad (device 0, 1, 2...)

---

### 4. Interactable Objects
**File**: `scripts/interactable_object.gd`

**Purpose**: Physics-based grabbable objects

**Key Features**:
- RigidBody2D physics
- Grab/throw support
- Weight-based mechanics
- Collision-based pushing

**Exported Properties**:
```gdscript
@export var can_be_grabbed: bool = true
@export var can_be_pushed: bool = true
@export var weight: float = 1.0
```

**Interaction Callbacks**:
```gdscript
on_grabbed(by_player)
on_released(by_player)
on_thrown(by_player, force: Vector2)
```

**Physics Behavior**:
- Freezes when held
- Applies force when thrown (adjusted by weight)
- Natural collision-based pushing
- Bounces and slides realistically

---

### 5. Game World
**File**: `scripts/game_world.gd`

**Purpose**: Main game scene controller

**Key Features**:
- Player spawning coordination
- Camera management
- Network event handling
- Dynamic camera zoom

**Camera System**:
- Follows center of all local players
- Smooth lerp movement (0.1 factor)
- Dynamic zoom based on player spread
- Zoom range: 0.5x to 1.5x

**Network Coordination**:
- Server spawns all players
- Clients spawn only their own
- RPC synchronization for new players
- Automatic cleanup on disconnect

---

### 6. Game UI
**File**: `scripts/game_ui.gd`

**Purpose**: Main menu and lobby interface

**Key Features**:
- Host/Join interface
- Local player count selection
- IP address input
- Connection feedback

**UI Elements**:
- Title label
- Local players spinbox (1-4)
- Server address input
- Host/Join buttons
- Control instructions

---

### 7. Debug Overlay
**File**: `scripts/debug_overlay.gd`

**Purpose**: Runtime debugging information

**Key Features**:
- Network status display
- Player count and IDs
- FPS counter
- Toggle with ESC key

**Displayed Information**:
- Connection state
- Peer ID
- Server status
- Connected peer count
- Local player counts
- Frame rate

---

## Interaction System Details

### Grab Mechanics

**Detection**:
1. Player presses grab button
2. GrabArea (80 unit radius) checks for overlapping bodies
3. Finds closest grabbable object/player
4. Stores grab offset for smooth following

**Holding**:
1. Object position lerps to player position + offset
2. Lerp factor: 0.3 for smooth movement
3. Object stays ~60 units from player center
4. Object can be RigidBody2D or CharacterBody2D

**Release**:
1. Player presses grab button again
2. Object physics re-enabled
3. Object stays at current position
4. Grab offset cleared

### Throw Mechanics

**Direction**:
- Uses player's current velocity direction
- Falls back to Vector2.RIGHT if stationary
- Normalized for consistent force

**Force Application**:
- Base throw_force: 600 units/sec
- Adjusted by object weight
- Applied as linear_velocity (RigidBody2D)
- Applied as velocity (CharacterBody2D)

**Physics**:
- Natural trajectory from physics engine
- Bounces off walls and objects
- Gradually slows due to friction
- Can chain-react with other objects

### Push Mechanics

**Implementation**:
- Automatic via physics collisions
- No special code required
- CharacterBody2D naturally pushes RigidBody2D
- Force depends on movement speed

**Weight Effects**:
- Heavier objects (higher mass) move slower
- Lighter objects move faster
- Multiple players can push together
- Cumulative force from multiple pushers

### Player-Player Interaction

**Grabbing Players**:
- Same mechanics as objects
- Grabbed player loses control
- Grabbed player follows grabber
- Physics_process disabled while held

**Throwing Players**:
- Same force calculation
- Player regains control mid-air
- Can be thrown into objects
- Creates fun chaos!

---

## Network Architecture

### Connection Flow

**Host**:
1. Create ENetMultiplayerPeer server
2. Set as multiplayer_peer
3. Register self in players_info
4. Wait for clients

**Client**:
1. Create ENetMultiplayerPeer client
2. Connect to host IP:port
3. Wait for connection_succeeded
4. Send registration RPC to server

**Registration**:
1. Client sends peer_id + local_count
2. Server stores in players_info
3. Server syncs all player info to client
4. Server broadcasts new player to all clients

### Synchronization

**Player Position**:
- Local players: Authoritative
- Remote players: Synced via unreliable RPC
- Update frequency: Every physics frame
- Interpolation: Direct position assignment

**Player Spawning**:
- Server spawns all players
- Server sends spawn RPC to clients
- Clients spawn remote players
- Authority assigned to owning peer

**Object Interaction**:
- Grab/throw: Local prediction
- Object physics: RigidBody2D auto-sync
- State changes: Reliable RPCs
- Conflict resolution: Server authority

### Data Structures

**players_info Dictionary**:
```gdscript
{
  peer_id: {
    "local_player_count": int,
    "player_names": Array[String]
  }
}
```

**Player Identification**:
- Unique ID: "{peer_id}_{local_index}"
- Node name: "Player_{unique_id}"
- Authority: peer_id

---

## Input System

### Device Assignment

**Automatic Assignment**:
```gdscript
if local_player_index == 0:
    input_device = -1  # Keyboard
else:
    input_device = local_player_index - 1  # Gamepad
```

**Mapping**:
- Local Player 0 → Keyboard (-1)
- Local Player 1 → Gamepad 0
- Local Player 2 → Gamepad 1
- Local Player 3 → Gamepad 2

### Input Reading

**Keyboard**:
```gdscript
Input.get_action_strength("move_right")
Input.is_action_just_pressed("grab")
```

**Gamepad**:
```gdscript
Input.get_joy_axis(device, JOY_AXIS_LEFT_X)
Input.is_joy_button_pressed(device, JOY_BUTTON_A)
```

### Input Actions

Defined in project.godot:
- `move_left`: A, Left Arrow
- `move_right`: D, Right Arrow
- `move_up`: W, Up Arrow
- `move_down`: S, Down Arrow
- `grab`: E
- `throw`: Q

---

## Camera System

### Follow Logic

**Center Calculation**:
```gdscript
var center = Vector2.ZERO
for player in local_players:
    center += player.position
center /= local_players.size()
```

**Smooth Movement**:
```gdscript
camera.position = camera.position.lerp(center, 0.1)
```

### Dynamic Zoom

**Distance Calculation**:
```gdscript
var max_distance = 0.0
for player in local_players:
    var distance = center.distance_to(player.position)
    max_distance = max(max_distance, distance)
```

**Zoom Adjustment**:
```gdscript
var target_zoom = clamp(800.0 / (max_distance + 400.0), 0.5, 1.5)
camera.zoom = camera.zoom.lerp(Vector2.ONE * target_zoom, 0.05)
```

**Behavior**:
- Zooms out when players spread apart
- Zooms in when players group together
- Smooth transitions
- Keeps all local players visible

---

## Extension Points

### Adding New Interactables

1. Inherit from `interactable_object.tscn`
2. Override interaction methods:
   - `can_be_grabbed() -> bool`
   - `on_grabbed(by_player)`
   - `on_released(by_player)`
   - `on_thrown(by_player, force: Vector2)`
3. Adjust mass and collision layers
4. Add custom behavior in `_physics_process()`

### Adding Player Abilities

1. Add input action in project.godot
2. Add ability logic in `player.gd`:
   ```gdscript
   func _handle_abilities():
       if Input.is_action_just_pressed("special_ability"):
           _use_special_ability()
   ```
3. Add network sync if needed:
   ```gdscript
   @rpc("any_peer", "call_local")
   func _sync_ability_use():
       # Ability effects
   ```

### Creating Game Modes

1. Create new scene inheriting from `game_world.tscn`
2. Add game mode script:
   ```gdscript
   extends Node2D
   
   var game_mode = "capture_flag"
   var score = {}
   
   func _ready():
       _setup_game_mode()
   ```
3. Add mode selection in main menu
4. Implement mode-specific logic

---

## Performance Considerations

### Network Optimization

**Unreliable RPCs**:
- Used for position updates
- Reduces bandwidth
- Acceptable packet loss

**Reliable RPCs**:
- Used for state changes
- Guaranteed delivery
- Higher latency

**Update Frequency**:
- Position: Every frame (60Hz)
- State: On change only
- Spawn/Despawn: Immediate

### Physics Optimization

**Collision Layers**:
- Layer 1: Players
- Layer 2: Objects
- Layer 4: Walls

**Sleep Threshold**:
- Objects sleep when stationary
- Reduces physics calculations
- Wakes on interaction

### Rendering Optimization

**Simple Sprites**:
- Procedural circle/rectangle
- No texture loading
- Minimal draw calls

**Camera Culling**:
- Only visible objects rendered
- Automatic by Godot
- No manual optimization needed

---

## Known Limitations

1. **Max Players**: 8 concurrent connections
2. **Max Local**: 4 players per machine
3. **No Reconnect**: Disconnected players can't rejoin
4. **No Persistence**: Game state not saved
5. **LAN Focus**: Best for local network play
6. **No Voice Chat**: Text only (via external tools)
7. **Single Map**: Only one game world
8. **No AI**: No enemy or NPC support yet

---

## Future Enhancements

### Short Term
- [ ] Player name customization
- [ ] Color selection
- [ ] More object types
- [ ] Sound effects
- [ ] Particle effects

### Medium Term
- [ ] Multiple maps
- [ ] Game modes (CTF, King of Hill)
- [ ] Character stats (health, stamina)
- [ ] Inventory system
- [ ] Cooperative puzzles

### Long Term
- [ ] Enemy AI
- [ ] Combat system
- [ ] Progression/leveling
- [ ] Dedicated server
- [ ] Matchmaking
- [ ] Steam integration

