Loading...
Learn Design Snake & Ladder — a key concept for LLD interviews.
You're building the classic Snake game. The board is a 20x20 grid where the snake moves, food appears randomly, and walls kill the snake. How should you represent the game board so that collision checks are fast?
class Position {
constructor(public row: number, public col: number) {}
equals(other: Position): boolean {
return this.row === other.row && this.col === other.col
}
toString(): string { return `${this.row},${this.col}` }
}
class Board {
private width: number
private height: number
private snakePositions: Set<string> // O(1) collision check
private foodPosition: Position | null
isValidPosition(pos: Position): boolean {
return pos.row >= 0 && pos.row < this.height
&& pos.col >= 0 && pos.col < this.width
}
hasSnakeAt(pos: Position): boolean {
return this.snakePositions.has(pos.toString())
}
}What's the best way to represent the game board?