Business Rules - Nokia Snake Game

Game rules

Business Rules - Nokia Snake Game

Game Rules

Collision Rules

Rule G-001: Snake Self-Collision

Description: Snake collides with its own body
Condition: Snake head position equals any body segment position (excluding head)
Action: Game over
Priority: High
Validation: Check on every game update

// Implementation
function checkSelfCollision(snake) {
  const head = snake.body[0];
  for (let i = 1; i < snake.body.length; i++) {
    if (head.x === snake.body[i].x && head.y === snake.body[i].y) {
      return true; // Collision detected
    }
  }
  return false; // No collision
}

Rule G-002: Snake Wall Collision

Description: Snake moves outside game boundaries
Condition: Snake head position < 0 OR ≥ grid width/height
Action: Game over
Priority: High
Validation: Check on every game update

// Implementation
function checkWallCollision(snake, gridWidth, gridHeight) {
  const head = snake.body[0];
  return head.x < 0 || head.x >= gridWidth || 
         head.y < 0 || head.y >= gridHeight;
}

Rule G-003: Snake Food Collision

Description: Snake head collides with food
Condition: Snake head position equals food position
Action:

  1. Increase snake length by 1
  2. Increase score based on food type and consecutive food bonus
  3. Generate new food
  4. Update consecutive food counter
  5. Deactivate active power-up (if any)

Priority: High
Validation: Check on every game update

// Implementation
function checkFoodCollision(snake, food) {
  const head = snake.body[0];
  return head.x === food.position.x && head.y === food.position.y;
}

Movement Rules

Rule M-001: Direction Change Validation

Description: Prevent 180-degree turns
Condition: New direction is opposite of current direction
Action: Ignore input, maintain current direction
Priority: High
Validation: Check on every input event

// Implementation
function isValidDirectionChange(currentDirection, newDirection) {
  const oppositeDirections = {
    'UP': 'DOWN',
    'DOWN': 'UP',
    'LEFT': 'RIGHT',
    'RIGHT': 'LEFT'
  };
  return newDirection !== oppositeDirections[currentDirection];
}

Rule M-002: Movement Speed

Description: Snake moves at consistent speed based on game state
Condition: Game is in PLAYING state
Action: Move snake one grid cell per game update based on gameSpeed
Priority: High
Formula: movementInterval = 1000 / gameSpeed (ms between moves)

Rule M-003: Boundary Wrap (Optional)

Description: Snake wraps around screen edges (disabled by default)
Condition: Snake head reaches boundary
Action: Teleport to opposite side
Priority: Low (feature flag)

Scoring Rules

Rule S-001: Base Scoring

Description: Points awarded for food collection
Base Value: 10 points per regular food
Power-up Food: 20 points (double base value)
Priority: High

Rule S-002: Progressive Scoring Bonus

Description: Bonus for consecutive food collection without dying
Formula: bonusMultiplier = 1 + (consecutiveFoods * 0.1)
Maximum Bonus: 2.0x (after 10 consecutive foods)
Reset Condition: Game over or missed food (no collection for 5 seconds)
Priority: Medium

// Implementation
function calculateProgressiveScore(baseScore, consecutiveFoods) {
  const bonusMultiplier = Math.min(1 + (consecutiveFoods * 0.1), 2.0);
  return Math.floor(baseScore * bonusMultiplier);
}

Rule S-003: High Score Tracking

Description: Track top 10 scores
Storage: localStorage
Update Condition: Game over with score > 0
Display: Sorted descending, show date and snake length
Priority: Medium

Game Over Rules

Rule GO-001: Game Over Conditions

Conditions:

  1. Snake self-collision (Rule G-001)
  2. Snake wall collision (Rule G-002)
  3. Manual quit (user action)

Actions:

  1. Stop game loop
  2. Calculate final score
  3. Update high scores if applicable
  4. Show game over screen
  5. Offer restart option

Priority: High

Rule GO-002: Restart Rules

Description: Reset game to initial state
Actions:

  1. Reset snake to starting position and length
  2. Reset score to 0
  3. Reset consecutive food counter
  4. Generate new food
  5. Reset game speed to base value
  6. Clear active power-ups

Priority: High

Validation Rules

Input Validation Rules

Rule IV-001: Keyboard Input Validation

Description: Validate all keyboard input
Allowed Keys: ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Space, Escape
Allowed Actions: KEY_DOWN, KEY_UP
Validation: Type checking, value range checking, game state validation
Priority: High (SECURITY-05 Compliance)

// Implementation
function validateKeyboardInput(event, gameState) {
  // Type checking
  if (!event || typeof event !== 'object') return false;
  
  // Property validation
  const requiredProps = ['key', 'type', 'timeStamp'];
  for (const prop of requiredProps) {
    if (!event.hasOwnProperty(prop)) return false;
  }
  
  // Key validation
  const allowedKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' ', 'Escape'];
  if (!allowedKeys.includes(event.key)) return false;
  
  // Action validation
  const allowedActions = ['keydown', 'keyup'];
  if (!allowedActions.includes(event.type)) return false;
  
  // Game state validation
  if (event.type === 'keydown') {
    return validateGameMove(event.key, gameState);
  }
  
  return true;
}

Rule IV-002: Game Move Validation

Description: Validate moves against game state
Prevention: Opposite direction moves (180-degree turns)
Condition: Game must be in PLAYING state
Priority: High

State Validation Rules

Rule SV-001: Game State Integrity

Description: Validate game state on load and save
Checks:

  1. Required properties exist
  2. Property types are correct
  3. Value ranges are valid
  4. Relationships are consistent

Priority: High

// Implementation
function validateGameState(state) {
  const requiredProps = ['status', 'snake', 'food', 'score', 'gameSpeed'];
  
  // Check required properties
  for (const prop of requiredProps) {
    if (!state.hasOwnProperty(prop)) return false;
  }
  
  // Validate status
  const validStatuses = ['MAIN_MENU', 'PLAYING', 'PAUSED', 'GAME_OVER'];
  if (!validStatuses.includes(state.status)) return false;
  
  // Validate snake
  if (!Array.isArray(state.snake.body) || state.snake.body.length < 1) return false;
  
  // Validate score (non-negative integer)
  if (!Number.isInteger(state.score) || state.score < 0) return false;
  
  // Validate game speed (positive number)
  if (typeof state.gameSpeed !== 'number' || state.gameSpeed <= 0) return false;
  
  return true;
}

Rule SV-002: Boundary Condition Validation

Description: Validate positions within grid boundaries
Condition: All game objects must be within grid bounds
Priority: High

Business Logic Rules

Rule BL-001: Power-up Activation Rules

Description: Rules for power-up activation
Types: Speed boost only (user selection)
Activation: Collect power-up food
Duration: Until next food collection
Effect: 25% speed increase
Stacking: Not allowed (only one active at a time)
Priority: Medium

Rule BL-002: Difficulty Adjustment Rules

Description: Gradual speed increase as snake grows
Base Speed: 10 grid cells per second
Increase: +0.5 speed per snake segment
Maximum Speed: 20 grid cells per second
Priority: Medium

// Implementation
function calculateGameSpeed(snakeLength, hasPowerUp) {
  const baseSpeed = 10;
  const maxSpeed = 20;
  const speedPerSegment = 0.5;
  
  let speed = baseSpeed + (snakeLength * speedPerSegment);
  speed = Math.min(speed, maxSpeed);
  
  if (hasPowerUp) {
    speed *= 1.25; // 25% speed boost
  }
  
  return speed;
}

Rule BL-003: Food Generation Rules

Description: Rules for food placement
Constraints:

  1. Must be within grid boundaries
  2. Must not overlap with snake body
  3. Regular food: 90% chance
  4. Power-up food: 10% chance
  5. Minimum distance from snake: 3 grid cells (optional)

Priority: Medium

Rule BL-004: Game Progression Rules

Description: Rules for game advancement
Speed Increase: Based on snake length (Rule BL-002)
Scoring: Progressive (Rule S-002)
Difficulty: Gradual, no sudden jumps
Priority: Medium

Error Handling Rules

Rule EH-001: Silent Fail Strategy

Description: Log errors but continue game if possible
Implementation:

  1. Catch all exceptions
  2. Log to console with context
  3. Attempt fallback to safe state
  4. Continue game if possible
  5. Restart only if unrecoverable

Priority: High (SECURITY-15 Compliance)

Rule EH-002: Safe State Fallback

Description: Fallback state for error recovery
State: Initial game state with error recovery flag
Condition: Unhandled exception or validation failure
Priority: High

Rule EH-003: User Notification Rules

Description: When to notify users of errors
Notification: Only for critical, game-breaking errors
Non-critical: Log only, continue silently
Critical Examples:

  • WebGL context loss
  • Storage failure preventing game save
  • Fatal rendering errors

Priority: Medium

Security Rules

Rule SEC-001: Input Sanitization

Description: Sanitize all user input
Requirements:

  1. Validate before processing
  2. Escape special characters
  3. Limit input length
  4. Type coercion prevention

Priority: High (SECURITY-05 Compliance)

Rule SEC-002: Data Validation

Description: Validate all data before use
Scope: Game state, saved data, user input
Validation: Type, range, format, consistency
Priority: High

Rule SEC-003: Exception Safety

Description: Ensure exceptions don't expose sensitive information
Implementation:

  1. Generic error messages
  2. No stack traces in production
  3. No internal state exposure
  4. Safe defaults

Priority: High (SECURITY-15 Compliance)

Frontend Component Rules

Rule FC-001: Component Structure Rules

Description: Rules for component organization
Granularity: Moderate (logical grouping)
Grouping: By game entity/feature
Examples: SnakeComponent, FoodComponent, GameBoard, ScoreDisplay
Priority: Medium

Rule FC-002: State Management Rules

Description: Rules for component state
Centralized: Single source of truth (Redux-like)
Props: Pass data down, events up
Local State: Only for UI-specific state (animations, transitions)
Priority: High

Rule FC-003: User Interaction Rules

Description: Rules for user interactions
Feedback: Visual feedback for all interactions
Responsiveness: Immediate response to input
Accessibility: Keyboard navigation, screen reader support
Priority: Medium

Persistence Rules

Rule P-001: Game State Save Rules

Description: What to save in game state
Save: Basic game state (snake, food, score, consecutiveFoods, gameTime)
Don't Save: Active power-ups, temporary state, UI state
Format: JSON with versioning
Priority: Medium

Rule P-002: High Score Persistence Rules

Description: Rules for high score storage
Storage: localStorage
Limit: Top 10 scores only
Data: Score, date, snake length
Validation: Score must be positive integer
Priority: Medium

Rule P-003: Settings Persistence Rules

Description: Rules for settings storage
Storage: localStorage
Settings: Controls mapping, sound volume, visual preferences
Default: Provide sensible defaults
Priority: Low

Performance Rules

Rule PER-001: Game Loop Performance

Description: Rules for game loop efficiency
Target: 60 FPS
Optimization: Fixed time step, frame skipping if needed
Monitoring: Frame rate monitoring, performance warnings
Priority: High

Rule PER-002: Rendering Performance

Description: Rules for efficient rendering
WebGL: Use best practices, batch rendering calls
Updates: Only render when state changes
Optimization: Texture atlasing, sprite batching
Priority: High

Rule PER-003: Memory Management Rules

Description: Rules for memory efficiency
Object Pooling: Reuse game objects
Garbage Collection: Minimize allocations in game loop
Cleanup: Proper resource disposal
Priority: Medium

Compliance Summary

SECURITY Baseline Compliance

  • SECURITY-05 (Input Validation): Rules IV-001, IV-002, SEC-001, SEC-002
  • SECURITY-15 (Exception Handling): Rules EH-001, EH-002, EH-003, SEC-003

Game Quality Compliance

  • Consistency: All rules ensure consistent gameplay
  • Fairness: Rules prevent exploits and ensure fair play
  • User Experience: Rules prioritize smooth, responsive gameplay
  • Maintainability: Rules are documented and testable

Rule Enforcement

Validation Points

  1. Input Processing: Validate all user input
  2. State Updates: Validate state transitions
  3. Persistence: Validate saved data
  4. Rendering: Validate rendering parameters

Error Handling Points

  1. Input Errors: Log and ignore invalid input
  2. State Errors: Fallback to safe state
  3. Rendering Errors: Attempt recovery, restart if needed
  4. Persistence Errors: Continue without persistence

Testing Points

  1. Unit Tests: Test individual rules
  2. Integration Tests: Test rule interactions
  3. End-to-End Tests: Test complete rule application
  4. Edge Cases: Test boundary conditions and error scenarios