# Donkey Kong Arcade Game Clone - Architecture Document

## Original User Prompt

Please create a Donkey Kong game, using HTML5 and JavaScript and CSS. Here is the description of the original Donkey Kong, try to make the game close to the original in terms of gameplay.

In the 1981 Donkey Kong arcade game, players control Mario ("Jumpman") to navigate four distinct industrial, platform-based levels to rescue Pauline from a giant gorilla. Gameplay involves climbing ladders, jumping over rolling barrels, fireballs, and hazards to reach the top, often using a hammer for temporary protection. 

Core Gameplay Mechanics:
- Objective: Reach the top of the level to save the "Lady" (Pauline).
- Controls: Players can walk left/right, climb ladders, and jump over obstacles.
- Obstacles: Donkey Kong throws barrels that roll down girders, and "fire" enemies spawn from an oil drum.
- Power-up: A hammer can be picked up to smash barrels and fireballs for points, but it limits movement (no jumping or climbing while holding it).
- Stages: Four levels included: 75m (girder/barrels), 50m (elevators), 75m (conveyor belts), and 100m (removing rivets).
- Failure: Mario loses a life if he hits an enemy, falls from a high distance, or fails to complete the level within the time limit.
- Scoring: Points are awarded for jumping over obstacles, collecting items (purse, umbrella), and completing stages.

## Enhanced Prompt

Create a faithful Donkey Kong arcade game clone using HTML5 Canvas, vanilla JavaScript, and CSS. Implement the complete 1981 arcade experience including:

**CORE FEATURES:**
- Player character (Mario/Jumpman) with walk left/right, climb ladders, and jump mechanics
- 4 authentic arcade stages: (1) 75m girders with rolling barrels, (2) 50m with elevators, (3) 75m with conveyor belts, (4) 100m rivet-removing stage
- Donkey Kong AI that throws barrels down girders with proper physics
- Fire enemies that spawn from oil drums
- Hammer power-up for smashing barrels/fireballs (restricts jumping/climbing)
- Pauline at top of each level as rescue objective
- Collision detection for obstacles, ladders, platforms, and enemies
- Lives system (lose life on enemy collision, high falls, or time-out)
- Scoring system (points for jumping obstacles, collecting items, completing stages)
- Time limit per level with visual countdown
- Retro pixel-art visual style matching arcade aesthetic
- Keyboard controls (arrow keys for movement, spacebar for jump)
- Game states: title screen, gameplay, level transitions, game over, victory

**TECHNICAL REQUIREMENTS:**
- Pure vanilla JavaScript (no game frameworks)
- HTML5 Canvas for rendering
- CSS for UI elements and styling
- Efficient game loop with proper timing
- Clean, modular code structure

---

## Ambiguity Evaluation

### Original Prompt Ambiguities
1. **Visual Style**: Not specified - pixel art vs modern graphics
2. **Sound**: No mention of audio effects or music
3. **Controls**: Only directional mentioned - specific keys not defined
4. **Difficulty Scaling**: No mention of difficulty progression between levels
5. **Mobile Support**: Desktop-only vs responsive design
6. **High Score Persistence**: Local storage vs no persistence
7. **Animation Detail**: Sprite-based vs simple shapes

### Enhanced Prompt Clarifications
1. **Visual Style**: Retro pixel-art style (assumed for authenticity)
2. **Controls**: Arrow keys + spacebar defined
3. **Code Structure**: Vanilla JS with modular architecture specified
4. **Rendering**: HTML5 Canvas explicitly chosen

### Remaining Ambiguities Requiring Decisions
1. Sound implementation (recommended but optional for MVP)
2. Sprite animation complexity (start simple, enhance later)
3. Mobile/touch controls (post-MVP enhancement)
4. High score persistence (recommended for arcade authenticity)

---

## Implied Requirements Analysis

### Unstated Constraints
1. **Performance**: Game must run at 60 FPS for smooth gameplay
2. **Browser Compatibility**: Modern browsers (Chrome, Firefox, Edge, Safari)
3. **File Size**: Reasonable load time for web game
4. **Code Maintainability**: Clean architecture for future enhancements

### Expected Behavior
1. **Authentic Feel**: Movement physics should match original arcade timing
2. **Progressive Difficulty**: Later stages should be harder
3. **Fair Collision Detection**: Forgiving hitboxes like original arcade
4. **Responsive Controls**: Minimal input lag
5. **Visual Feedback**: Clear indication of player state (jumping, climbing, hammer)

### Domain Conventions
1. **Arcade Game Patterns**: Lives system, high score, continue screen
2. **Platformer Physics**: Gravity, platform collision, ladder interaction
3. **Enemy AI Patterns**: Predictable barrel rolling physics, fire enemy behavior
4. **Level Design**: Vertical progression with platform/girder layouts

---

## Further Considerations

### Design Decisions Needed
1. **Canvas Size**: Original arcade was 224x256 (vertical) - scale for modern displays
2. **Aspect Ratio**: Maintain vertical orientation or adapt for horizontal screens?
3. **Color Palette**: Match original limited arcade colors or expand?
4. **Animation Frames**: How many frames per sprite action?

### Technical Trade-offs
1. **Sprite vs Primitive Rendering**: Sprites look better, primitives are easier
2. **Fixed vs Variable Time Step**: Fixed is more deterministic, variable smoother
3. **Object Pooling**: Essential for barrels to avoid garbage collection
4. **Collision Detection Method**: Bounding box vs pixel-perfect

### Assumptions for Implementation
1. Desktop-first with keyboard controls
2. 2D side-view perspective (original arcade style)
3. Single-player only
4. No external assets initially (generate graphics programmatically)
5. Sound as optional enhancement

---

## Gotchas & Technical Risks

### Potential Pitfalls
1. **Jump Physics**: Original had specific arc and timing - must be precise
2. **Ladder Climbing**: Transition between walking and climbing states is tricky
3. **Barrel Physics**: Rolling, bouncing on edges, falling through gaps
4. **Collision Edge Cases**: Player landing on moving platform, barrel hitting player mid-jump
5. **State Management**: Multiple concurrent states (jumping, climbing, hammer, invincible)

### Hidden Complexity
1. **Elevator Stage**: Synchronized moving platforms with proper collision
2. **Conveyor Belt Stage**: Moving platforms that affect player and barrels
3. **Rivet Stage**: Removing rivets causes girders to fall with Donkey Kong
4. **Hammer Duration**: Timed power-up with visual countdown
5. **Fall Detection**: Differentiating safe falls from deadly falls

### Non-Functional Concerns
1. **Frame Rate Consistency**: Must maintain 60 FPS during intense moments
2. **Memory Management**: Barrel object pooling to prevent GC stutters
3. **Input Handling**: Prevent key repeat issues, handle simultaneous keys
4. **Browser Tab Visibility**: Pause game when tab loses focus

### Missing Features to Consider
1. **Demo Mode**: Attract screen with AI playing
2. **Pause Functionality**: Essential for user experience
3. **Level Select**: Debug/cheat feature for testing
4. **Sound Effects**: Jump, barrel smash, death, level complete
5. **High Score Table**: Arcade authenticity

---

## Detailed Architecture Document

### 1. System Overview

```
┌─────────────────────────────────────────────────────────────────┐
│                        DONKEY KONG GAME                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐         │
│  │   INDEX.    │    │   GAME.     │    │   STYLE.    │         │
│  │    HTML     │    │     JS      │    │    CSS      │         │
│  │  (Entry)    │    │  (Core)     │    │   (UI)      │         │
│  └──────┬──────┘    └──────┬──────┘    └─────────────┘         │
│         │                  │                                    │
│         ▼                  ▼                                    │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    GAME ENGINE                          │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │   │
│  │  │  Game   │ │  Input  │ │ Renderer│ │  Audio  │       │   │
│  │  │  Loop   │ │ Handler │ │         │ │ (Opt)   │       │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │   │
│  │  │ Physics │ │Collision│ │  State  │ │  Entity │       │   │
│  │  │ Engine  │ │ System  │ │ Manager │ │ Manager │       │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    GAME ENTITIES                        │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │   │
│  │  │ Player  │ │   DK    │ │ Barrels │ │  Fire   │       │   │
│  │  │ (Mario) │ │         │ │         │ │ Enemies │       │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │   │
│  │  │ Pauline │ │ Hammer  │ │ Ladders │ │Platforms│       │   │
│  │  │         │ │ Powerup │ │         │ │         │       │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    LEVEL DATA                           │   │
│  │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │   │
│  │  │ Stage 1 │ │ Stage 2 │ │ Stage 3 │ │ Stage 4 │       │   │
│  │  │ Barrels │ │Elevators│ │Conveyor │ │ Rivets  │       │   │
│  │  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### 2. File Structure

```
donkey-kong/
├── index.html          # Entry point, canvas setup, UI overlay
├── style.css           # UI styling, retro font, canvas centering
├── game.js             # Main game orchestration, state management
│
├── engine/
│   ├── gameLoop.js     # Fixed timestep loop, frame timing
│   ├── input.js        # Keyboard handling, key state tracking
│   ├── renderer.js     # Canvas drawing, camera, layers
│   ├── physics.js      # Gravity, velocity, movement
│   ├── collision.js    # AABB collision detection, resolution
│   └── audio.js        # Sound effects manager (optional)
│
├── entities/
│   ├── player.js       # Mario/Jumpman class, states, animations
│   ├── donkeyKong.js   # DK behavior, barrel throwing
│   ├── barrel.js       # Rolling barrel physics, bouncing
│   ├── fireEnemy.js    # Fire creature AI, movement
│   ├── pauline.js      # Goal character, distress animation
│   ├── hammer.js       # Power-up pickup, timer
│   ├── platform.js     # Girder/platform with collision
│   ├── ladder.js       # Climbable surface
│   └── elevator.js     # Moving platform (Stage 2)
│
├── levels/
│   ├── level.js        # Base level class, common functionality
│   ├── stage1Barrels.js    # 75m - Girder/barrel stage
│   ├── stage2Elevators.js  # 50m - Elevator stage
│   ├── stage3Conveyor.js   # 75m - Conveyor belt stage
│   ├── stage4Rivets.js     # 100m - Rivet removal stage
│   └── levelFactory.js     # Level instantiation
│
├── data/
│   ├── levelData.js    # Platform positions, ladder placements
│   └── constants.js    # Game constants, physics values
│
└── utils/
    ├── vector.js       # 2D vector math
    ├── objectPool.js   # Barrel pooling for performance
    └── spriteUtils.js  # Sprite drawing helpers
```

### 3. Core Systems Architecture

#### 3.1 Game Loop (Fixed Timestep)

```
┌──────────────────────────────────────────────────────────┐
│                    GAME LOOP FLOW                        │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  ┌─────────┐    ┌─────────┐    ┌─────────┐              │
│  │  Start  │───▶│ Process │───▶│  Update │              │
│  │  Frame  │    │  Input  │    │  Logic  │              │
│  └─────────┘    └─────────┘    └────┬────┘              │
│                                     │                    │
│                                     ▼                    │
│                              ┌─────────────┐            │
│                              │ Fixed Update│            │
│                              │  (Physics)  │            │
│                              │  Multiple   │            │
│                              │   Calls     │            │
│                              └──────┬──────┘            │
│                                     │                    │
│                                     ▼                    │
│                              ┌─────────────┐            │
│                              │   Render    │            │
│                              │   (Interp)  │            │
│                              └──────┬──────┘            │
│                                     │                    │
│                                     ▼                    │
│                              ┌─────────────┐            │
│                              │ Request     │            │
│                              │ Next Frame  │            │
│                              └─────────────┘            │
│                                                          │
│  Target: 60 FPS (16.67ms per frame)                     │
│  Fixed Physics Step: 16.67ms (or smaller for accuracy)  │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

**Key Implementation Notes:**
- Use `requestAnimationFrame` for smooth rendering
- Accumulate time for fixed physics updates
- Interpolate rendering positions for smooth visuals
- Handle tab visibility (pause when hidden)

#### 3.2 Player State Machine

```
┌──────────────────────────────────────────────────────────┐
│                  PLAYER STATE MACHINE                    │
├──────────────────────────────────────────────────────────┤
│                                                          │
│                     ┌──────────┐                         │
│                     │  IDLE    │                         │
│                     └────┬─────┘                         │
│                          │                               │
│           ┌──────────────┼──────────────┐               │
│           ▼              ▼              ▼               │
│    ┌──────────┐   ┌──────────┐   ┌──────────┐          │
│    │ WALKING  │   │ CLIMBING │   │ JUMPING  │          │
│    └────┬─────┘   └────┬─────┘   └────┬─────┘          │
│         │              │              │                 │
│         │              │              ▼                 │
│         │              │       ┌──────────┐            │
│         │              │       │  FALLING │            │
│         │              │       └────┬─────┘            │
│         │              │            │                   │
│         ▼              ▼            ▼                   │
│    ┌───────────────────────────────────────┐           │
│    │            HAMMER MODE                 │           │
│    │  (No jumping, no climbing)            │           │
│    │  States: HAMMER_IDLE, HAMMER_WALK     │           │
│    └───────────────────────────────────────┘           │
│                                                          │
│  State Transitions:                                      │
│  - IDLE → WALKING: Left/Right input + grounded          │
│  - IDLE → JUMPING: Jump input + grounded                │
│  - WALKING → CLIMBING: Up/Down input + touching ladder  │
│  - JUMPING → FALLING: Apex reached or walked off edge   │
│  - FALLING → IDLE: Ground collision                     │
│  - ANY → HAMMER_MODE: Hammer pickup collision           │
│  - HAMMER_MODE → IDLE: Timer expired                    │
│  - ANY → DEAD: Enemy collision OR high fall OR timeout  │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

#### 3.3 Collision Detection System

```
┌──────────────────────────────────────────────────────────┐
│               COLLISION DETECTION LAYERS                 │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  Layer 0: BACKGROUND (No collision)                      │
│  ├── Sky, decorative elements                            │
│  │                                                       │
│  Layer 1: SOLID GEOMETRY                                 │
│  ├── Platforms (girders)                                 │
│  ├── Ladders (special - can pass through sides)          │
│  ├── Elevators (moving platforms)                        │
│  └── Collision Type: AABB (Axis-Aligned Bounding Box)   │
│                                                          │
│  Layer 2: PLAYER                                         │
│  ├── Player hitbox                                       │
│  ├── Collision with: Layer 1, Layer 3, Layer 4          │
│  └── Special: Ladder overlap zone                        │
│                                                          │
│  Layer 3: ENEMIES                                        │
│  ├── Barrels (AABB)                                      │
│  ├── Fire enemies (AABB)                                 │
│  └── Collision with: Layer 1, Layer 2                   │
│                                                          │
│  Layer 4: COLLECTIBLES                                   │
│  ├── Hammer power-up                                     │
│  ├── Items (purse, umbrella)                             │
│  └── Collision with: Layer 2 only (player)              │
│                                                          │
│  Collision Response Priority:                            │
│  1. Platform collision (stop falling)                    │
│  2. Ladder overlap (enable climbing)                     │
│  3. Enemy collision (death or hammer smash)              │
│  4. Collectible collision (pickup)                       │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

### 4. Stage Designs

#### 4.1 Stage 1: 75m - Barrel Stage

```
Layout (ASCII Representation):
┌────────────────────────────────────────┐
│  PAULINE    ♥                           │  TOP
│  ──────────────────────────────────────│
│         ║         ║         ║           │  Ladders
│  ──────────────────────────────────────│  Platform 6
│     DONKEY KONG                        │
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Platform 5
│                                        │
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Platform 4
│                                        │
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Platform 3
│                                        │
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Platform 2
│                                        │
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Platform 1
│  MARIO    [OIL DRUM]                   │  BOTTOM
└────────────────────────────────────────┘

Mechanics:
- DK throws barrels at regular intervals
- Barrels roll down platforms, bounce on edges
- Barrels can fall through gaps
- Oil drum spawns fire enemy when barrel passes
- Hammer spawns on platforms 2 and 4
- Ladders connect all platforms
```

#### 4.2 Stage 2: 50m - Elevator Stage

```
Layout:
┌────────────────────────────────────────┐
│  PAULINE                               │
│  ──────────────────────────────────────│
│         ║                              │
│  ──────[ELEV]──────[ELEV]─────────────│  Moving platforms
│         ║         ║                    │
│  ──────────────────────────────────────│
│         ║         ║                    │
│  ──────[ELEV]──────────────────────────│
│         ║                              │
│  ──────────────────────────────────────│
│                                        │
└────────────────────────────────────────┘

Mechanics:
- Two elevators moving vertically
- Player must time jumps onto elevators
- Falling from elevator = death if too high
- Fewer barrels, more platforming challenge
```

#### 4.3 Stage 3: 75m - Conveyor Belt Stage

```
Layout:
┌────────────────────────────────────────┐
│  PAULINE                               │
│  ──────────────────────────────────────│
│         ║         ║         ║           │
│  ═════════════════════════════════════│  Conveyor (moving)
│         ║         ║         ║           │
│  ═════════════════════════════════════│  Conveyor (opposite)
│         ║         ║         ║           │
│  ──────────────────────────────────────│  Static platform
│                                        │
└────────────────────────────────────────┘

Mechanics:
- Conveyor belts move player and barrels
- Direction alternates between belts
- Requires timing and compensation
- Items placed on conveyor belts
```

#### 4.4 Stage 4: 100m - Rivet Stage

```
Layout:
┌────────────────────────────────────────┐
│        PAULINE                          │
│                                        │
│    ○────○────○────○────○               │  Rivets to remove
│    ║         ║         ║                │
│    ○────○────○────○────○               │
│    ║         ║         ║                │
│    ○────○────○────○────○               │
│    ║         ║         ║                │
│    ○────○────○────○────○               │
│                                        │
│    DONKEY KONG (center, on girders)    │
└────────────────────────────────────────┘

Mechanics:
- Remove all rivets (○) to make girders fall
- Player runs across rivets (they don't fall with player on them)
- When all rivets removed on a side, girder falls
- DK falls when all girders removed
- Fire enemies patrol the rivets
- No barrels in this stage
```

### 5. Physics System

#### 5.1 Movement Constants

| Parameter | Value | Notes |
|-----------|-------|-------|
| Gravity | 0.5 units/frame | Acceleration downward |
| Walk Speed | 2.0 units/frame | Left/right movement |
| Jump Velocity | -8.0 units/frame | Initial upward velocity |
| Climb Speed | 1.5 units/frame | Up/down on ladders |
| Max Fall Speed | 10.0 units/frame | Terminal velocity |
| Barrel Roll Speed | 2.5 units/frame | Horizontal movement |
| Barrel Bounce | -4.0 units/frame | Vertical on edge hit |

#### 5.2 Collision Resolution

```
Player-Platform Collision:
1. Check if player is moving downward (falling)
2. Check if player bottom overlaps platform top
3. Check horizontal overlap (player left/right vs platform)
4. If valid landing:
   - Set player Y to platform top
   - Set vertical velocity to 0
   - Set grounded state to true

Player-Ladder Collision:
1. Check overlap with ladder hitbox
2. If pressing UP or DOWN:
   - Transition to climbing state
   - Disable gravity
   - Align player X to ladder center
3. If at ladder top/bottom:
   - Allow transition to walking state

Player-Enemy Collision:
1. Check AABB overlap
2. If player has hammer:
   - Destroy enemy
   - Award points
3. If player jumping over barrel:
   - Award points
   - Barrel continues (no destruction)
4. Otherwise:
   - Player death
```

### 6. Scoring System

| Action | Points | Notes |
|--------|--------|-------|
| Jump over barrel | 100 | Per successful jump |
| Smash barrel (hammer) | 500 | Per barrel destroyed |
| Smash fire enemy (hammer) | 300 | Per enemy destroyed |
| Collect purse | 800 | Bonus item |
| Collect umbrella | 800 | Bonus item |
| Remove rivet | 100 | Stage 4 only |
| Complete Stage 1 | 5000 | Bonus based on time |
| Complete Stage 2 | 6000 | Bonus based on time |
| Complete Stage 3 | 7000 | Bonus based on time |
| Complete Stage 4 | 8000 | Bonus based on time |

### 7. Game State Management

```
┌──────────────────────────────────────────────────────────┐
│                    GAME STATES                           │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  ┌─────────────┐                                        │
│  │   TITLE     │ ◀────────────────────────┐            │
│  │   SCREEN    │                          │            │
│  └──────┬──────┘                          │            │
│         │ Start key pressed               │            │
│         ▼                                  │            │
│  ┌─────────────┐                          │            │
│  │ LEVEL INTRO │ ◀──┐                     │            │
│  │ (3 sec)     │    │                     │            │
│  └──────┬──────┘    │                     │            │
│         │           │                     │            │
│         ▼           │ Level complete      │            │
│  ┌─────────────┐    │ or player death     │            │
│  │  PLAYING    │────┘                     │            │
│  └──────┬──────┘                          │            │
│         │ All lives lost                  │            │
│         ▼                                  │            │
│  ┌─────────────┐                          │            │
│  │ GAME OVER   │──────────────────────────┘            │
│  │ (10 sec)    │                                        │
│  └──────┬──────┘                                        │
│         │ Game complete (all 4 stages)                  │
│         ▼                                                │
│  ┌─────────────┐                                        │
│  │  VICTORY    │                                        │
│  │  SCREEN     │                                        │
│  └─────────────┘                                        │
│                                                          │
│  State Data per State:                                   │
│  - TITLE: High scores, demo mode animation              │
│  - LEVEL INTRO: Stage number, lives remaining           │
│  - PLAYING: All game entities, timer, score             │
│  - GAME OVER: Final score, continue prompt              │
│  - VICTORY: Final score, play again prompt              │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

### 8. Entity Component Design

#### Player Entity

```javascript
// Player properties structure
{
  // Position & Movement
  x: number,           // World X position
  y: number,           // World Y position
  vx: number,          // Velocity X
  vy: number,          // Velocity Y
  
  // State
  state: enum,         // IDLE, WALKING, JUMPING, CLIMBING, FALLING, HAMMER_*
  facing: enum,        // LEFT, RIGHT
  grounded: boolean,   // On platform?
  onLadder: boolean,   // Touching ladder?
  
  // Power-up
  hasHammer: boolean,  // Hammer active?
  hammerTimer: number, // Duration remaining
  
  // Game State
  lives: number,       // Remaining lives (start with 3)
  invincible: boolean, // Post-death invincibility
  invincibleTimer: number,
  
  // Animation
  animFrame: number,
  animTimer: number,
  sprite: SpriteSheet
}
```

#### Barrel Entity

```javascript
// Barrel properties structure
{
  x: number,
  y: number,
  vx: number,          // Rolling direction
  vy: number,
  
  // Physics
  onGround: boolean,
  bouncing: boolean,   // Hit edge of platform?
  
  // Type
  isWild: boolean,     // Wild barrel (different color)
  
  // Animation
  animFrame: number,
  rotation: number,    // Visual rotation while rolling
  
  // Pool management
  active: boolean,
  id: number
}
```

### 9. Rendering Strategy

#### Canvas Setup

- **Size**: 480 x 640 pixels (scaled 2x from original arcade ratio)
- **Scaling**: Use CSS to scale for different screens
- **Layers**: Single canvas with draw order priority

#### Draw Order (Back to Front)

1. Background (solid color or gradient)
2. Platforms/Girders (with rivet decorations)
3. Ladders
4. Elevators/Conveyors
5. Collectibles (hammer, items)
6. Barrels and Fire Enemies
7. Donkey Kong
8. Pauline
9. Player (Mario)
10. UI Overlay (score, lives, timer)

#### Sprite System

- Generate sprites programmatically for MVP
- Use simple shapes with pixel-art styling
- Color palette matching original arcade:
  - Mario: Red (#FF0000), Blue (#0000FF)
  - DK: Brown (#8B4513)
  - Girders: Red (#FF4444)
  - Ladders: Blue (#4444FF)
  - Barrels: Blue/Brown

### 10. Input Handling

```
┌──────────────────────────────────────────────────────────┐
│                   INPUT MAPPING                          │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  Keyboard Controls:                                      │
│  ┌─────────────┬───────────────────────────────────┐    │
│  │    Key      │              Action               │    │
│  ├─────────────┼───────────────────────────────────┤    │
│  │ Arrow Left  │ Walk left                         │    │
│  │ Arrow Right │ Walk right                        │    │
│  │ Arrow Up    │ Climb up (on ladder)              │    │
│  │ Arrow Down  │ Climb down (on ladder)            │    │
│  │ Spacebar    │ Jump (when grounded)              │    │
│  │ P           │ Pause game                        │    │
│  │ Enter       │ Start game / Continue             │    │
│  │ M           │ Toggle mute (if audio)           │    │
│  └─────────────┴───────────────────────────────────┘    │
│                                                          │
│  Input State Tracking:                                   │
│  - currentKeys: Set of currently pressed keys           │
│  - previousKeys: Set of keys pressed last frame         │
│  - Just pressed: key in current, not in previous        │
│  - Just released: key in previous, not in current      │
│                                                          │
│  Simultaneous Key Support:                              │
│  - Allow left/right + jump simultaneously              │
│  - Handle ladder transition inputs correctly            │
│                                                          │
└──────────────────────────────────────────────────────────┘
```

### 11. Audio Design (Optional Enhancement)

If implementing audio, use Web Audio API:

| Sound Effect | Trigger | Duration |
|--------------|---------|----------|
| Jump | Spacebar pressed | 0.2s |
| Land | Ground collision after fall | 0.1s |
| Barrel Roll | Continuous loop (low volume) | Loop |
| Barrel Smash | Hammer hits barrel | 0.3s |
| Hammer Pickup | Player collects hammer | 0.5s |
| Death | Player loses life | 1.0s |
| Level Complete | Reach Pauline | 2.0s |
| DK Throw | Barrel thrown | 0.3s |

### 12. Implementation Phases

#### Phase 1: Core Framework (Foundation)
- [ ] Create index.html with canvas
- [ ] Set up game loop with fixed timestep
- [ ] Implement input handler
- [ ] Create basic renderer
- [ ] Add physics engine (gravity, velocity)

#### Phase 2: Player Mechanics
- [ ] Create player entity
- [ ] Implement walking left/right
- [ ] Add jump mechanic with proper arc
- [ ] Implement gravity and falling
- [ ] Add player state machine
- [ ] Create collision detection
- [ ] Implement ladder climbing

#### Phase 3: Stage 1 - Barrels
- [ ] Create platform/girder entities
- [ ] Create ladder entities
- [ ] Design Stage 1 layout
- [ ] Implement platform collision
- [ ] Create Donkey Kong entity
- [ ] Implement barrel throwing AI
- [ ] Create barrel entity with rolling physics
- [ ] Add barrel collision and player death
- [ ] Implement jumping over barrels (scoring)

#### Phase 4: Game Systems
- [ ] Add lives system (3 lives)
- [ ] Implement scoring system
- [ ] Add timer and time limit
- [ ] Create UI overlay (score, lives, timer)
- [ ] Implement game states (title, playing, game over)
- [ ] Add level intro screens

#### Phase 5: Hammer Power-up
- [ ] Create hammer entity
- [ ] Implement hammer pickup
- [ ] Add hammer timer (7 seconds)
- [ ] Implement smashing barrels/fire
- [ ] Restrict movement while holding hammer
- [ ] Add visual feedback for hammer mode

#### Phase 6: Stage 2 - Elevators
- [ ] Create elevator entity
- [ ] Implement vertical movement
- [ ] Add elevator collision (riding)
- [ ] Design Stage 2 layout
- [ ] Handle falling from elevator

#### Phase 7: Stage 3 - Conveyor Belts
- [ ] Create conveyor belt entity
- [ ] Implement horizontal movement
- [ ] Affect player and barrel movement
- [ ] Design Stage 3 layout

#### Phase 8: Stage 4 - Rivets
- [ ] Create rivet entity
- [ ] Implement rivet removal mechanic
- [ ] Add girder falling animation
- [ ] Make DK fall when all rivets removed
- [ ] Design Stage 4 layout
- [ ] Remove barrels from this stage

#### Phase 9: Polish
- [ ] Add fire enemy AI
- [ ] Implement bonus items (purse, umbrella)
- [ ] Add death animations
- [ ] Implement post-death invincibility
- [ ] Add level transition animations
- [ ] Create title screen
- [ ] Add game over screen
- [ ] Add victory screen

#### Phase 10: Optional Enhancements
- [ ] Add sound effects
- [ ] Implement high score with local storage
- [ ] Add mobile touch controls
- [ ] Create demo/attract mode
- [ ] Add pause functionality

### 13. Testing Strategy

#### Unit Tests (Manual Verification)

1. **Player Movement**
   - Walk left/right at correct speed
   - Jump height and arc matches expected
   - Gravity pulls player down correctly
   - Ladder climbing works in both directions

2. **Collision Detection**
   - Player lands on platforms correctly
   - Player can climb ladders when overlapping
   - Player dies on enemy collision (no hammer)
   - Player smashes enemies (with hammer)

3. **Barrel Physics**
   - Barrels roll in correct direction
   - Barrels bounce at platform edges
   - Barrels fall through gaps
   - Wild barrels behave differently

4. **Game State**
   - Lives decrement on death
   - Score updates correctly
   - Timer counts down
   - Level advances on completion

#### Integration Tests

1. Complete Stage 1 without dying
2. Complete all 4 stages in sequence
3. Lose all lives and reach game over
4. Collect hammer and verify behavior
5. Jump over barrel and verify scoring

#### Performance Tests

1. Maintain 60 FPS with 10+ barrels on screen
2. No frame drops during barrel spawning
3. Smooth collision detection with multiple entities

---

## Summary

This architecture provides a comprehensive blueprint for implementing a faithful Donkey Kong arcade clone. The modular design allows for:

1. **Incremental Development**: Build core systems first, add complexity later
2. **Authentic Gameplay**: Physics and mechanics match original arcade feel
3. **Maintainable Code**: Clear separation of concerns across modules
4. **Extensibility**: Easy to add features like audio, mobile controls, or additional levels

The implementation should proceed in phases, with each phase delivering playable functionality. This allows for testing and iteration throughout development.

**Recommended First Implementation**: Phase 1-3 (Core Framework + Player + Stage 1)
This delivers a playable first level that captures the essence of Donkey Kong gameplay.