Please use Laptop/Desktop or any other large screen for the Mock Interview Session.

Design Snake Game



YouTube Video Thumbnail
Link

Watch above sample mock interview video to see how it works.
Login and Buy Premium to Start the Interview



Snake Game Design

Snake Game Design

Problem Statement

Create a simple Snake game played on a grid of size cols by rows. The snake starts at the top-left corner (0,0) with length 1.

You receive a sequence of food locations specified as row-column pairs. Each time the snake eats food, it grows by one unit and your score increases by one.

Food appears sequentially; the next food only shows up after the current one is eaten.

Food will never spawn on any part of the snake's body.

Examples

Given rows = 3, cols = 3, and foodPositions = [[2,2],[1,0]].

SnakeGame game = new SnakeGame(rows, cols, foodPositions);

The snake starts at position (0,0), and the first food is at (2,2).

|S| | |
| | | |
| | |F|

game.moveSnake("R"); -> Returns 0

| |S| |
| | | |
| | |F|

game.moveSnake("D"); -> Returns 0

| | | |
| |S| |
| | |F|

game.moveSnake("D"); -> Returns 1 (Snake eats first food; next food appears at (1,0))

| | | |
|F|S| |
| |S| |

game.moveSnake("L"); -> Returns 1

| | | |
|F| |S|
| |S| |

game.moveSnake("U"); -> Returns 2 (Snake eats second food)

| | | |
|S| |S|
| |S| |

game.moveSnake("U"); -> Returns -1 (Game over: snake hits the top border)

Constraints

  • 1 ≤ rows, cols ≤ 50
  • 1 ≤ Number of food items ≤ 20
  • Food positions are distinct and valid within the grid