Domain Entities - Nokia Snake Game

Game entities

Domain Entities - Nokia Snake Game

Overview

Domain: Classic arcade game with modern enhancements
Core Entities: Snake, Food, Game, Player, Power-up
Value Objects: Position, Direction, Score, GameSettings
Relationships: Aggregation, Composition, Association

Core Entities

1. Snake Entity

Purpose: Represents the player-controlled snake
Properties:

  • id: Unique identifier (UUID)
  • body: Array of Position objects representing segments
  • direction: Current movement direction (Direction enum)
  • length: Current length (derived from body length)
  • color: Visual representation color
  • speed: Current movement speed (grid cells per second)
  • isAlive: Boolean indicating if snake is alive

Behaviors:

  • move(direction): Move snake in specified direction
  • grow(): Add new segment to snake body
  • checkSelfCollision(): Check if snake collides with itself
  • getHead(): Get head position
  • getTail(): Get tail position
  • changeDirection(newDirection): Change movement direction

Lifecycle:

  1. Creation: Initialized with starting position and length
  2. Growth: Increases length when food is collected
  3. Movement: Continuously moves in current direction
  4. Death: When collision occurs (self or wall)
  5. Reset: Returns to initial state on game restart

2. Food Entity

Purpose: Represents consumable items that make snake grow
Properties:

  • id: Unique identifier (UUID)
  • position: Position on game grid
  • type: Food type (REGULAR, POWER_UP)
  • value: Point value when collected
  • color: Visual representation based on type
  • spawnTime: Timestamp when food was spawned
  • lifetime: Maximum time before despawning (optional)

Behaviors:

  • getPosition(): Return current position
  • isPowerUp(): Check if food is power-up type
  • shouldDespawn(currentTime): Check if food should despawn
  • collect(): Mark as collected and return value

Lifecycle:

  1. Generation: Created at random valid position
  2. Display: Rendered on game board
  3. Collection: When snake head collides with food
  4. Removal: After collection or despawn timeout

3. Game Entity

Purpose: Represents the overall game session
Properties:

  • id: Unique identifier (UUID)
  • status: Current game status (MAIN_MENU, PLAYING, PAUSED, GAME_OVER)
  • score: Current score
  • highScore: Best score achieved
  • level: Current difficulty level
  • gameTime: Total time played in current session
  • gridSize: Game board dimensions (width, height)
  • gameSpeed: Base game speed
  • consecutiveFoods: Count of consecutive food collections
  • activePowerUp: Currently active power-up (if any)

Behaviors:

  • start(): Begin new game session
  • pause(): Pause current game
  • resume(): Resume paused game
  • gameOver(): End current game session
  • restart(): Start new game with same settings
  • updateScore(points): Add points to current score
  • checkHighScore(): Update high score if beaten
  • increaseLevel(): Advance to next difficulty level

Lifecycle:

  1. Initialization: Set up game with default settings
  2. Active Play: Player controls snake, collects food
  3. Paused State: Game temporarily halted
  4. Game Over: Session ends (collision or quit)
  5. Restart: New session begins

4. Player Entity

Purpose: Represents the human player
Properties:

  • id: Unique identifier (UUID or username)
  • name: Player display name
  • totalScore: Lifetime total score across all games
  • gamesPlayed: Number of games played
  • gamesWon: Number of games completed (high score achieved)
  • bestSnakeLength: Longest snake achieved
  • playTime: Total time spent playing
  • achievements: Collection of unlocked achievements

Behaviors:

  • updateStats(gameResult): Update player statistics
  • unlockAchievement(achievement): Mark achievement as unlocked
  • getRank(): Calculate player rank based on statistics
  • resetStats(): Clear all statistics (optional)

Lifecycle:

  1. Registration: Player identified (anonymous or named)
  2. Gameplay: Accumulates statistics across sessions
  3. Achievement: Unlocks achievements based on performance
  4. Persistent: Statistics saved across browser sessions

5. Power-up Entity

Purpose: Represents temporary game enhancements
Properties:

  • id: Unique identifier (UUID)
  • type: Power-up type (SPEED_BOOST)
  • effect: Effect description and parameters
  • duration: How long effect lasts (seconds or "UNTIL_NEXT_FOOD")
  • activationTime: When power-up was activated
  • isActive: Boolean indicating if power-up is currently active
  • visualEffect: Visual representation parameters

Behaviors:

  • activate(): Apply power-up effect to game
  • deactivate(): Remove power-up effect
  • isExpired(currentTime): Check if power-up duration has expired
  • getRemainingTime(currentTime): Calculate remaining effect time

Lifecycle:

  1. Creation: Generated as special food type
  2. Collection: When snake collects power-up food
  3. Activation: Effect applied to game
  4. Active: Effect modifies game behavior
  5. Expiration: Effect removed after duration

Value Objects

1. Position Value Object

Purpose: Represents coordinates on game grid
Properties:

  • x: Horizontal coordinate (0 to gridWidth-1)
  • y: Vertical coordinate (0 to gridHeight-1)

Behaviors:

  • equals(otherPosition): Check if positions are equal
  • distanceTo(otherPosition): Calculate Manhattan distance
  • translate(dx, dy): Create new position with offset
  • isWithinBounds(gridWidth, gridHeight): Check if position is valid

Immutable: Once created, cannot be modified

2. Direction Value Object

Purpose: Represents movement direction
Values: UP, DOWN, LEFT, RIGHT

Behaviors:

  • opposite(): Get opposite direction
  • isHorizontal(): Check if direction is LEFT or RIGHT
  • isVertical(): Check if direction is UP or DOWN
  • toVector(): Convert to (dx, dy) vector

Immutable: Enum-like value object

3. Score Value Object

Purpose: Represents game score with metadata
Properties:

  • value: Numeric score value
  • timestamp: When score was achieved
  • snakeLength: Snake length when score achieved
  • gameTime: Game duration when score achieved
  • consecutiveFoods: Consecutive food count when score achieved

Behaviors:

  • compareTo(otherScore): Compare scores for ranking
  • format(): Format score for display
  • add(points): Create new score with added points

Immutable: Score objects represent specific achievements

4. GameSettings Value Object

Purpose: Represents game configuration
Properties:

  • gridWidth: Game board width in cells
  • gridHeight: Game board height in cells
  • initialSpeed: Starting game speed
  • speedIncreasePerSegment: Speed increase per snake segment
  • maxSpeed: Maximum allowed game speed
  • powerUpChance: Probability of power-up food (0.0 to 1.0)
  • consecutiveFoodBonus: Bonus multiplier per consecutive food
  • controls: Keyboard control mappings

Behaviors:

  • validate(): Check if settings are valid
  • getGridSize(): Return grid dimensions object
  • cloneWithUpdates(updates): Create new settings with modifications

Immutable: Settings define game behavior

Entity Relationships

1. Game-Snake Relationship (Composition)

Type: Composition (Game owns Snake)
Cardinality: 1:1 (One game has one snake)
Description: Game creates and manages the snake entity. Snake cannot exist without a game.

classDiagram
    Game "1" -- "1" Snake : contains
    class Game {
        +Snake snake
        +createSnake()
        +destroySnake()
    }
    class Snake {
        +Game game
        +move()
        +grow()
    }

2. Game-Food Relationship (Aggregation)

Type: Aggregation (Game contains Food)
Cardinality: 1:0..* (One game can have zero or more food items)
Description: Game generates and manages food items. Food can exist independently but is managed by the game.

classDiagram
    Game "1" -- "0..*" Food : contains
    class Game {
        +List~Food~ foodItems
        +generateFood()
        +removeFood(Food)
    }
    class Food {
        +Game game
        +getPosition()
        +collect()
    }

3. Game-Power-up Relationship (Aggregation)

Type: Aggregation (Game contains Power-up)
Cardinality: 1:0..1 (One game can have zero or one active power-up)
Description: Game manages active power-ups. Power-ups are created when special food is collected.

classDiagram
    Game "1" -- "0..1" PowerUp : has active
    class Game {
        +PowerUp activePowerUp
        +activatePowerUp(PowerUp)
        +deactivatePowerUp()
    }
    class PowerUp {
        +Game game
        +activate()
        +deactivate()
    }

4. Player-Game Relationship (Association)

Type: Association (Player plays Games)
Cardinality: 1:0..* (One player can play zero or more games)
Description: Player participates in game sessions. Games record player achievements.

classDiagram
    Player "1" -- "0..*" Game : plays
    class Player {
        +List~Game~ gameHistory
        +updateStats(Game)
    }
    class Game {
        +Player player
        +recordResult()
    }

5. Snake-Food Relationship (Interaction)

Type: Interaction (Snake collects Food)
Cardinality: 0..:0.. (Snake can collect multiple food items, food can be collected by snake)
Description: Snake head position equals food position triggers collection.

classDiagram
    Snake "0..*" -- "0..*" Food : collects
    class Snake {
        +collectFood(Food) Score
    }
    class Food {
        +isCollectedBy(Snake) boolean
    }

6. Food-Power-up Relationship (Specialization)

Type: Specialization (Power-up Food is a type of Food)
Description: Power-up food inherits from food with additional effects.

classDiagram
    Food <|-- PowerUpFood : extends
    class Food {
        +Position position
        +int value
        +collect()
    }
    class PowerUpFood {
        +PowerUpType type
        +PowerUp createPowerUp()
    }

Entity Lifecycles

Snake Lifecycle

stateDiagram-v2
    [*] --> Created : Game starts
    Created --> Alive : Initial rendering
    Alive --> Growing : Food collected
    Growing --> Alive : Growth complete
    Alive --> Dead : Collision detected
    Dead --> [*] : Game over
    Dead --> Created : Game restart

Food Lifecycle

stateDiagram-v2
    [*] --> Generated : Random position
    Generated --> Displayed : Rendered on board
    Displayed --> Collected : Snake collision
    Displayed --> Expired : Timeout reached
    Collected --> [*] : Score awarded
    Expired --> [*] : Removed from board

Game Lifecycle

stateDiagram-v2
    [*] --> MainMenu : Application start
    MainMenu --> Playing : Start game
    Playing --> Paused : Pause button
    Paused --> Playing : Resume button
    Playing --> GameOver : Collision
    GameOver --> MainMenu : Return to menu
    GameOver --> Playing : Restart game
    MainMenu --> [*] : Application exit

Power-up Lifecycle

stateDiagram-v2
    [*] --> Inactive : As food item
    Inactive --> Active : Collected by snake
    Active --> Expiring : Duration counting
    Expiring --> [*] : Effect ends
    Active --> [*] : Manual deactivation

Entity State Transitions

Snake State Transitions

  1. Created → Alive: Initial rendering complete
  2. Alive → Growing: Food collection triggers growth
  3. Growing → Alive: New segment added to body
  4. Alive → Dead: Collision detection
  5. Dead → Created: Game restart

Game State Transitions

  1. MainMenu → Playing: User starts new game
  2. Playing → Paused: User pauses game
  3. Paused → Playing: User resumes game
  4. Playing → GameOver: Snake collision
  5. GameOver → MainMenu: Return to menu
  6. GameOver → Playing: Restart game

Validation Rules

  1. Position Validation: x ≥ 0 && x < gridWidth && y ≥ 0 && y < gridHeight
  2. Direction Validation: Must be UP, DOWN, LEFT, or RIGHT
  3. Score Validation: value ≥ 0, timestamp valid
  4. Game Settings Validation: All values within reasonable ranges
  5. Entity ID Validation: UUID format, unique within context

Security Considerations

Entity Validation (SECURITY-05 Compliance)

  1. Input Validation: All entity properties validated on creation
  2. State Validation: Entity state validated before state transitions
  3. Boundary Validation: Position values within game bounds
  4. Type Validation: Entity types match expected values

Data Integrity (SECURITY-15 Compliance)

  1. Immutable Value Objects: Position, Direction, Score cannot be modified
  2. State Consistency: Entity relationships maintained consistently
  3. Lifecycle Integrity: State transitions follow defined rules
  4. Error Recovery: Invalid entities trigger safe fallback

Performance Considerations

Entity Management

  1. Object Pooling: Reuse entity objects where possible
  2. Lazy Loading: Load entity data only when needed
  3. Caching: Cache frequently accessed entity properties
  4. Cleanup: Proper disposal of unused entities

Memory Optimization

  1. Value Object Sharing: Share immutable value objects
  2. Entity Compression: Minimize entity memory footprint
  3. Garbage Collection: Minimize object creation in game loop
  4. Resource Management: Proper cleanup of entity resources

Testing Considerations

Entity Unit Tests

  1. Creation Tests: Verify entities created with valid state
  2. Behavior Tests: Test entity methods and behaviors
  3. State Transition Tests: Verify lifecycle transitions
  4. Validation Tests: Test entity validation rules

Integration Tests

  1. Relationship Tests: Test entity interactions
  2. Lifecycle Tests: Test complete entity lifecycles
  3. Persistence Tests: Test entity save/load functionality
  4. Performance Tests: Test entity management performance