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 segmentsdirection: Current movement direction (Direction enum)length: Current length (derived from body length)color: Visual representation colorspeed: Current movement speed (grid cells per second)isAlive: Boolean indicating if snake is alive
Behaviors:
move(direction): Move snake in specified directiongrow(): Add new segment to snake bodycheckSelfCollision(): Check if snake collides with itselfgetHead(): Get head positiongetTail(): Get tail positionchangeDirection(newDirection): Change movement direction
Lifecycle:
- Creation: Initialized with starting position and length
- Growth: Increases length when food is collected
- Movement: Continuously moves in current direction
- Death: When collision occurs (self or wall)
- 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 gridtype: Food type (REGULAR, POWER_UP)value: Point value when collectedcolor: Visual representation based on typespawnTime: Timestamp when food was spawnedlifetime: Maximum time before despawning (optional)
Behaviors:
getPosition(): Return current positionisPowerUp(): Check if food is power-up typeshouldDespawn(currentTime): Check if food should despawncollect(): Mark as collected and return value
Lifecycle:
- Generation: Created at random valid position
- Display: Rendered on game board
- Collection: When snake head collides with food
- 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 scorehighScore: Best score achievedlevel: Current difficulty levelgameTime: Total time played in current sessiongridSize: Game board dimensions (width, height)gameSpeed: Base game speedconsecutiveFoods: Count of consecutive food collectionsactivePowerUp: Currently active power-up (if any)
Behaviors:
start(): Begin new game sessionpause(): Pause current gameresume(): Resume paused gamegameOver(): End current game sessionrestart(): Start new game with same settingsupdateScore(points): Add points to current scorecheckHighScore(): Update high score if beatenincreaseLevel(): Advance to next difficulty level
Lifecycle:
- Initialization: Set up game with default settings
- Active Play: Player controls snake, collects food
- Paused State: Game temporarily halted
- Game Over: Session ends (collision or quit)
- Restart: New session begins
4. Player Entity
Purpose: Represents the human player
Properties:
id: Unique identifier (UUID or username)name: Player display nametotalScore: Lifetime total score across all gamesgamesPlayed: Number of games playedgamesWon: Number of games completed (high score achieved)bestSnakeLength: Longest snake achievedplayTime: Total time spent playingachievements: Collection of unlocked achievements
Behaviors:
updateStats(gameResult): Update player statisticsunlockAchievement(achievement): Mark achievement as unlockedgetRank(): Calculate player rank based on statisticsresetStats(): Clear all statistics (optional)
Lifecycle:
- Registration: Player identified (anonymous or named)
- Gameplay: Accumulates statistics across sessions
- Achievement: Unlocks achievements based on performance
- 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 parametersduration: How long effect lasts (seconds or "UNTIL_NEXT_FOOD")activationTime: When power-up was activatedisActive: Boolean indicating if power-up is currently activevisualEffect: Visual representation parameters
Behaviors:
activate(): Apply power-up effect to gamedeactivate(): Remove power-up effectisExpired(currentTime): Check if power-up duration has expiredgetRemainingTime(currentTime): Calculate remaining effect time
Lifecycle:
- Creation: Generated as special food type
- Collection: When snake collects power-up food
- Activation: Effect applied to game
- Active: Effect modifies game behavior
- 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 equaldistanceTo(otherPosition): Calculate Manhattan distancetranslate(dx, dy): Create new position with offsetisWithinBounds(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 directionisHorizontal(): Check if direction is LEFT or RIGHTisVertical(): Check if direction is UP or DOWNtoVector(): Convert to (dx, dy) vector
Immutable: Enum-like value object
3. Score Value Object
Purpose: Represents game score with metadata
Properties:
value: Numeric score valuetimestamp: When score was achievedsnakeLength: Snake length when score achievedgameTime: Game duration when score achievedconsecutiveFoods: Consecutive food count when score achieved
Behaviors:
compareTo(otherScore): Compare scores for rankingformat(): Format score for displayadd(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 cellsgridHeight: Game board height in cellsinitialSpeed: Starting game speedspeedIncreasePerSegment: Speed increase per snake segmentmaxSpeed: Maximum allowed game speedpowerUpChance: Probability of power-up food (0.0 to 1.0)consecutiveFoodBonus: Bonus multiplier per consecutive foodcontrols: Keyboard control mappings
Behaviors:
validate(): Check if settings are validgetGridSize(): Return grid dimensions objectcloneWithUpdates(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
- Created → Alive: Initial rendering complete
- Alive → Growing: Food collection triggers growth
- Growing → Alive: New segment added to body
- Alive → Dead: Collision detection
- Dead → Created: Game restart
Game State Transitions
- MainMenu → Playing: User starts new game
- Playing → Paused: User pauses game
- Paused → Playing: User resumes game
- Playing → GameOver: Snake collision
- GameOver → MainMenu: Return to menu
- GameOver → Playing: Restart game
Validation Rules
- Position Validation: x ≥ 0 && x < gridWidth && y ≥ 0 && y < gridHeight
- Direction Validation: Must be UP, DOWN, LEFT, or RIGHT
- Score Validation: value ≥ 0, timestamp valid
- Game Settings Validation: All values within reasonable ranges
- Entity ID Validation: UUID format, unique within context
Security Considerations
Entity Validation (SECURITY-05 Compliance)
- Input Validation: All entity properties validated on creation
- State Validation: Entity state validated before state transitions
- Boundary Validation: Position values within game bounds
- Type Validation: Entity types match expected values
Data Integrity (SECURITY-15 Compliance)
- Immutable Value Objects: Position, Direction, Score cannot be modified
- State Consistency: Entity relationships maintained consistently
- Lifecycle Integrity: State transitions follow defined rules
- Error Recovery: Invalid entities trigger safe fallback
Performance Considerations
Entity Management
- Object Pooling: Reuse entity objects where possible
- Lazy Loading: Load entity data only when needed
- Caching: Cache frequently accessed entity properties
- Cleanup: Proper disposal of unused entities
Memory Optimization
- Value Object Sharing: Share immutable value objects
- Entity Compression: Minimize entity memory footprint
- Garbage Collection: Minimize object creation in game loop
- Resource Management: Proper cleanup of entity resources
Testing Considerations
Entity Unit Tests
- Creation Tests: Verify entities created with valid state
- Behavior Tests: Test entity methods and behaviors
- State Transition Tests: Verify lifecycle transitions
- Validation Tests: Test entity validation rules
Integration Tests
- Relationship Tests: Test entity interactions
- Lifecycle Tests: Test complete entity lifecycles
- Persistence Tests: Test entity save/load functionality
- Performance Tests: Test entity management performance