Frontend Components - Nokia Snake Game

UI components

Frontend Components - Nokia Snake Game

Overview

Architecture: Component-based with Redux-like state management
Granularity: Moderate (logical grouping per game entity/feature)
Rendering: WebGL 2D context with modern minimalist design
State Management: Centralized store with unidirectional data flow

Component Hierarchy

graph TB
    App[App Component] --> GameContainer[GameContainer]
    App --> MainMenu[MainMenu]
    App --> GameOverScreen[GameOverScreen]
    
    GameContainer --> GameCanvas[GameCanvas]
    GameContainer --> GameHUD[GameHUD]
    GameContainer --> PauseMenu[PauseMenu]
    
    GameCanvas --> SnakeRenderer[SnakeRenderer]
    GameCanvas --> FoodRenderer[FoodRenderer]
    GameCanvas --> PowerUpRenderer[PowerUpRenderer]
    GameCanvas --> GridRenderer[GridRenderer]
    
    GameHUD --> ScoreDisplay[ScoreDisplay]
    GameHUD --> HighScoreDisplay[HighScoreDisplay]
    GameHUD --> TimerDisplay[TimerDisplay]
    GameHUD --> LevelDisplay[LevelDisplay]
    
    MainMenu --> StartButton[StartButton]
    MainMenu --> SettingsButton[SettingsButton]
    MainMenu --> HighScoresButton[HighScoresButton]
    
    GameOverScreen --> RestartButton[RestartButton]
    GameOverScreen --> MenuButton[MenuButton]
    GameOverScreen --> FinalScoreDisplay[FinalScoreDisplay]

Core Components

1. App Component

Purpose: Root component, application entry point
Responsibilities:

  • Application initialization and setup
  • Routing between main screens
  • Global error boundary
  • Theme provider

Props: None (root component)
State:

  • currentScreen: 'MAIN_MENU' | 'GAME' | 'GAME_OVER' | 'SETTINGS'
  • theme: Current visual theme
  • error: Global error state

Methods:

  • initializeApp(): Set up application
  • handleScreenChange(screen): Navigate between screens
  • handleGlobalError(error): Global error handler
  • applyTheme(theme): Change visual theme

Lifecycle:

  1. Mount: Initialize app, set up event listeners
  2. Update: Handle screen changes, theme updates
  3. Unmount: Clean up resources, save state

2. GameContainer Component

Purpose: Main game screen container
Responsibilities:

  • Game state management
  • Component coordination
  • Input handling delegation
  • Game loop management

Props:

  • initialState: Initial game state (optional)
  • onGameOver: Callback when game ends
  • onPause: Callback when game paused

State:

  • gameState: Current game state object
  • isPaused: Boolean indicating pause state
  • inputState: Current keyboard input state
  • renderStats: Performance statistics

Methods:

  • startGame(): Initialize and start game
  • pauseGame(): Pause game loop
  • resumeGame(): Resume game loop
  • restartGame(): Reset and restart game
  • handleInput(event): Process keyboard input
  • updateGameState(deltaTime): Update game logic

Lifecycle:

  1. Mount: Initialize game engine, set up input handlers
  2. Game Loop: Continuous state updates and rendering
  3. Pause/Resume: Manage game loop suspension
  4. Unmount: Stop game loop, clean up resources

3. GameCanvas Component

Purpose: WebGL rendering canvas
Responsibilities:

  • WebGL context management
  • Game element rendering
  • Canvas sizing and scaling
  • Performance optimization

Props:

  • gameState: Current game state to render
  • width: Canvas width
  • height: Canvas height
  • theme: Visual theme configuration

State:

  • glContext: WebGL rendering context
  • renderQueue: Queue of rendering operations
  • lastRenderTime: Timestamp of last render
  • fps: Current frames per second

Methods:

  • initializeWebGL(): Set up WebGL context
  • renderFrame(): Render single frame
  • resizeCanvas(width, height): Handle canvas resize
  • clearCanvas(): Clear rendering canvas
  • renderGameObject(object, style): Render game object

Lifecycle:

  1. Mount: Create canvas, initialize WebGL
  2. Render Loop: Continuous rendering at target FPS
  3. Resize: Handle window resize events
  4. Unmount: Clean up WebGL resources

4. SnakeRenderer Component

Purpose: Render snake entity
Responsibilities:

  • Snake segment rendering
  • Movement animations
  • Color and style application
  • Special effects (power-ups, etc.)

Props:

  • snake: Snake entity object
  • gridSize: Game grid dimensions
  • cellSize: Size of each grid cell in pixels
  • style: Visual style configuration

State:

  • animationState: Current animation state
  • segmentCache: Cached segment positions
  • colorGradient: Color gradient for snake

Methods:

  • renderSnake(): Render complete snake
  • animateMovement(oldPositions, newPositions): Animate movement
  • applyPowerUpEffects(powerUpType): Apply visual effects
  • updateSegmentCache(positions): Update position cache

Rendering Details:

  • Head: Distinct shape/color
  • Body: Segments with gradient
  • Tail: Special rendering
  • Movement: Smooth animation between positions
  • Effects: Visual feedback for power-ups

5. FoodRenderer Component

Purpose: Render food items
Responsibilities:

  • Food item rendering
  • Collection animations
  • Type-specific visuals
  • Spawn/despawn effects

Props:

  • foodItems: Array of food objects
  • gridSize: Game grid dimensions
  • cellSize: Size of each grid cell in pixels
  • style: Visual style configuration

State:

  • animationState: Food animation state
  • particleEffects: Collection animation particles
  • pulseState: Pulsing animation state

Methods:

  • renderFood(): Render all food items
  • animateCollection(food): Animate food collection
  • applyTypeStyle(foodType): Apply type-specific styling
  • updatePulseAnimation(): Update pulsing animation

Rendering Details:

  • Regular Food: Simple circle with color
  • Power-up Food: Special shape with glow effect
  • Animation: Pulsing, rotating, or other effects
  • Collection: Particle explosion effect

6. GameHUD Component

Purpose: Heads-Up Display overlay
Responsibilities:

  • Game information display
  • Score and statistics
  • Control hints
  • Performance metrics

Props:

  • gameState: Current game state
  • position: HUD position on screen
  • theme: Visual theme configuration
  • showPerformance: Whether to show performance stats

State:

  • hudElements: Array of HUD elements to display
  • updateQueue: Queue of HUD updates
  • animationState: HUD animation state

Methods:

  • updateHUD(gameState): Update HUD with current state
  • animateScoreChange(oldScore, newScore): Animate score changes
  • showNotification(message, type): Show temporary notification
  • togglePerformanceStats(): Toggle performance display

HUD Elements:

  1. Score Display: Current score with animation
  2. High Score: Best score achieved
  3. Timer: Game duration
  4. Level: Current difficulty level
  5. Snake Length: Current snake size
  6. Consecutive Foods: Streak counter
  7. Power-up Timer: Active power-up duration

7. MainMenu Component

Purpose: Main menu screen
Responsibilities:

  • Game start initiation
  • Navigation to other screens
  • Settings access
  • High scores display

Props:

  • onStartGame: Callback to start game
  • onShowSettings: Callback to show settings
  • onShowHighScores: Callback to show high scores
  • highScores: Array of high scores

State:

  • menuState: Current menu state
  • selectedOption: Currently selected menu option
  • animationState: Menu animation state

Methods:

  • handleStartGame(): Trigger game start
  • handleSettings(): Open settings screen
  • handleHighScores(): Show high scores
  • handleKeyNavigation(event): Handle keyboard navigation

Menu Options:

  1. Start Game: Begin new game session
  2. Continue: Resume saved game (if available)
  3. Settings: Game configuration
  4. High Scores: View best scores
  5. Help: Game instructions
  6. Exit: Close application (web: reload)

8. GameOverScreen Component

Purpose: Game over screen
Responsibilities:

  • Final score display
  • Restart option
  • High score celebration
  • Statistics summary

Props:

  • finalScore: Game ending score
  • highScore: Current high score
  • gameStats: Game statistics
  • onRestart: Callback to restart game
  • onMenu: Callback to return to menu

State:

  • screenState: Screen animation state
  • scoreAnimation: Score display animation
  • particleEffects: Celebration effects

Methods:

  • animateScoreReveal(): Animate score display
  • checkHighScore(): Check if high score beaten
  • showCelebration(): Show celebration effects
  • handleRestart(): Trigger game restart

Screen Elements:

  1. Game Over Title: Large text display
  2. Final Score: Animated score reveal
  3. High Score Indicator: If new record achieved
  4. Statistics: Game duration, snake length, etc.
  5. Restart Button: Immediate restart
  6. Menu Button: Return to main menu

Component Props and State

Common Props Interface

interface GameComponentProps {
  // Required props
  gameState?: GameState;
  theme?: ThemeConfig;
  
  // Optional props
  width?: number;
  height?: number;
  className?: string;
  style?: React.CSSProperties;
  
  // Callbacks
  onStateChange?: (newState: Partial<GameState>) => void;
  onError?: (error: Error) => void;
  onRenderComplete?: () => void;
}

interface GameState {
  status: 'MAIN_MENU' | 'PLAYING' | 'PAUSED' | 'GAME_OVER';
  score: number;
  highScore: number;
  snake: Snake;
  food: Food[];
  gameTime: number;
  // ... other state properties
}

Component State Management

// Centralized state store
class GameStore {
  private state: GameState;
  private subscribers: Array<(state: GameState) => void>;
  
  getState(): GameState;
  dispatch(action: GameAction): void;
  subscribe(callback: (state: GameState) => void): Unsubscribe;
}

// Component local state
interface ComponentLocalState {
  // UI-specific state
  isAnimating: boolean;
  localValues: Record<string, any>;
  errorState: Error | null;
  
  // Performance state
  renderCount: number;
  lastRenderTime: number;
  performanceMetrics: PerformanceMetrics;
}

Component Interactions

1. Input Flow

Keyboard Event → InputHandler → GameContainer → GameState Update → Component Re-render

2. Rendering Flow

GameState Change → GameContainer → GameCanvas → Individual Renderers → WebGL Draw Calls

3. State Update Flow

User Action → Component Handler → Store Dispatch → State Update → Subscriber Notification → Component Update

4. Error Handling Flow

Component Error → Error Boundary → Error Handler → Fallback UI → Error Logging

User Interaction Flows

Game Start Flow

sequenceDiagram
    User->>MainMenu: Click "Start Game"
    MainMenu->>App: navigateTo('GAME')
    App->>GameContainer: mount with initialState
    GameContainer->>GameContainer: initializeGame()
    GameContainer->>GameCanvas: render with gameState
    GameContainer->>InputHandler: start listening
    GameContainer->>GameLoop: start()

Game Pause/Resume Flow

sequenceDiagram
    User->>GameContainer: Press "P" key
    GameContainer->>GameContainer: togglePause()
    GameContainer->>GameLoop: pause() / resume()
    GameContainer->>GameHUD: update with isPaused
    GameContainer->>PauseMenu: show() / hide()

Game Over Flow

sequenceDiagram
    GameEngine->>GameContainer: collision detected
    GameContainer->>GameContainer: handleGameOver()
    GameContainer->>GameLoop: stop()
    GameContainer->>App: onGameOver(finalScore)
    App->>GameOverScreen: mount with finalScore
    GameOverScreen->>GameOverScreen: animateScoreReveal()
    GameOverScreen->>HighScoreManager: checkHighScore()

Settings Change Flow

sequenceDiagram
    User->>SettingsScreen: Change control mapping
    SettingsScreen->>GameStore: dispatch(SETTINGS_UPDATE)
    GameStore->>InputHandler: updateControlMapping()
    GameStore->>All Components: notify state change
    SettingsScreen->>LocalStorage: saveSettings()

Form Validation Rules

Settings Form Validation

const settingsValidationRules = {
  // Control mapping validation
  controls: {
    up: { required: true, type: 'string', maxLength: 20 },
    down: { required: true, type: 'string', maxLength: 20 },
    left: { required: true, type: 'string', maxLength: 20 },
    right: { required: true, type: 'string', maxLength: 20 },
    pause: { required: true, type: 'string', maxLength: 20 }
  },
  
  // Game settings validation
  gameSettings: {
    gridWidth: { required: true, type: 'number', min: 10, max: 50 },
    gridHeight: { required: true, type: 'number', min: 10, max: 50 },
    initialSpeed: { required: true, type: 'number', min: 1, max: 20 },
    powerUpChance: { required: true, type: 'number', min: 0, max: 1 }
  },
  
  // Visual settings validation
  visualSettings: {
    theme: { required: true, type: 'string', enum: ['MINIMAL', 'CLASSIC', 'MODERN'] },
    animationSpeed: { required: true, type: 'number', min: 0.5, max: 2.0 }
  }
};

Input Validation Rules (SECURITY-05 Compliance)

const inputValidationRules = {
  // Keyboard input validation
  keyboardInput: {
    key: { required: true, type: 'string', pattern: /^[A-Za-z0-9ArrowUpArrowDownArrowLeftArrowRightEscapeSpace]$/ },
    type: { required: true, type: 'string', enum: ['keydown', 'keyup'] },
    timestamp: { required: true, type: 'number', min: 0 }
  },
  
  // Game state validation
  gameState: {
    score: { required: true, type: 'number', min: 0 },
    snakeLength: { required: true, type: 'number', min: 1, max: 1000 },
    gameTime: { required: true, type: 'number', min: 0 }
  },
  
  // Component props validation
  componentProps: {
    gameState: { required: false, type: 'object' },
    theme: { required: false, type: 'object' },
    callbacks: { required: false, type: 'object' }
  }
};

Component Lifecycle

Mounting Phase

  1. Constructor: Initialize state, bind methods
  2. ComponentDidMount: DOM setup, event listeners, resource loading
  3. Initial Render: First render with initial state

Updating Phase

  1. ShouldComponentUpdate: Performance optimization check
  2. ComponentDidUpdate: Handle prop/state changes, side effects
  3. Render: Re-render with updated state

Unmounting Phase

  1. ComponentWillUnmount: Clean up resources, event listeners
  2. State Persistence: Save component state if needed
  3. Resource Cleanup: Release WebGL resources, timers, etc.

Error Handling

  1. Error Boundary: Catch component errors
  2. Fallback UI: Show error state component
  3. Error Recovery: Attempt automatic recovery
  4. Error Logging: Log errors for debugging

Performance Optimization

Rendering Optimization

  1. ShouldComponentUpdate: Prevent unnecessary re-renders
  2. Memoization: Cache expensive computations
  3. Virtualization: Only render visible elements
  4. Batching: Batch state updates and renders

Memory Optimization

  1. Object Pooling: Reuse component instances
  2. Event Delegation: Use event delegation instead of individual listeners
  3. Resource Management: Proper cleanup of WebGL resources
  4. Garbage Collection: Minimize object creation in render methods

WebGL Optimization

  1. Texture Atlases: Combine textures into atlases
  2. Batch Rendering: Batch similar draw calls
  3. Shader Optimization: Use efficient shaders
  4. Buffer Management: Proper buffer usage and cleanup

Security Considerations

Input Validation (SECURITY-05 Compliance)

  1. Prop Validation: Validate all component props
  2. Event Validation: Validate event data before processing
  3. State Validation: Validate component state changes
  4. DOM Sanitization: Sanitize any dynamic content

Error Handling (SECURITY-15 Compliance)

  1. Error Boundaries: Isolate component errors
  2. Graceful Degradation: Fallback when features unavailable
  3. Safe Defaults: Default to safe states on error
  4. Error Logging: Log errors without exposing sensitive data

XSS Prevention

  1. Content Sanitization: Sanitize dynamic content
  2. Event Handler Security: Secure event handler binding
  3. DOM Manipulation Safety: Safe DOM manipulation practices
  4. CSP Compliance: Content Security Policy adherence

Testing Strategy

Unit Tests

  1. Component Rendering: Test component renders correctly
  2. Props Validation: Test prop validation logic
  3. State Management: Test component state changes
  4. Event Handling: Test event handlers

Integration Tests

  1. Component Interaction: Test component communication
  2. User Flows: Test complete user interaction flows
  3. State Management: Test Redux store integration
  4. Rendering Pipeline: Test complete rendering pipeline

Performance Tests

  1. Render Performance: Test component render speed
  2. Memory Usage: Test component memory footprint
  3. Animation Performance: Test animation smoothness
  4. Load Time: Test component initialization time

Accessibility Tests

  1. Keyboard Navigation: Test keyboard accessibility
  2. Screen Reader: Test screen reader compatibility
  3. Color Contrast: Test visual accessibility
  4. Focus Management: Test focus handling

Compliance Summary

SECURITY Baseline Compliance

  • SECURITY-05 (Input Validation): Component props validation, event validation, form validation
  • SECURITY-15 (Exception Handling): Error boundaries, graceful degradation, safe defaults

Frontend Best Practices

  • Component Design: Single responsibility, loose coupling, high cohesion
  • Performance: Optimized rendering, memory management, WebGL best practices
  • Accessibility: Keyboard navigation, screen reader support, color contrast
  • Maintainability: Clean code, documentation, test coverage