Design Snake Game

Move a snake around a board, let it grow when it eats, and report the score or the end of the game.

Write a class for the Snake game on a board of height rows and width columns. The snake starts at row 0, col 0 with a length of one square. The pieces of food, each given as [row, col], appear one at a time in the given order. Each call to move(direction), with "U", "D", "L" or "R" for up, down, left or right, moves the snake one square. When the head reaches the current piece of food, the snake grows by one square and the next piece appears. The method returns the score, which is the number of pieces eaten, or -1 when the snake runs off the board or into its own body.

Example 1
Input: SnakeGame(width = 3, height = 2, food = [[1,2],[0,1]]), move R, D, R, U, L, U
Output: 0, 0, 1, 1, 2, -1
Solution

The Idea

You may know the old phone game: a snake made of squares slides across the screen, one square per step. Each time it reaches a piece of food it gets one square longer. The game ends when it runs off the screen or bites its own body.

Follow Example 1 on a board 3 columns wide and 2 rows high. The snake starts as a single square at row 0, col 0, and that square is also its head, the square at the front. R takes it to row 0, col 1, and D down to row 1, col 1. The first piece of food sits at row 1, col 2, so the next R eats it. The score becomes 1, and the snake now covers row 1, col 2 and row 1, col 1.

U then moves it up to row 0, col 2, where there is no food. L reaches the second piece, at row 0, col 1, and the score becomes 2. The last U would take the head above row 0, off the board, so it returns -1.

To catch a crash, the class must know after every move which squares the snake covers. Does every square of the snake have to move along with the head?

The drawing shows moves 4 and 5 of Example 1, one board for each.

Example 1, moves 4 and 5. On move 4, U, the head moves to row 0, col 2, there is no food, and the tail leaves row 1, col 1. On move 5, L, the head moves onto the food at row 0, col 1 and nothing leaves the back, so the snake grows to three squares.

On the left, move 4 is U. The head steps up from row 1, col 2 to row 0, col 2. The square marked body, at row 1, col 2, is where the head was a moment ago. The dashed square marked tail left, at row 1, col 1, held the last square of the snake, its tail, and is empty again. On the right, move 5 is L onto the food at row 0, col 1. The new head is there, and nothing leaves the back, so the snake grows to three squares.

So a move never shifts the middle of the snake. A new head appears at the front, and, unless the snake ate, the last square disappears from the back. Under each board, the row labelled body, head first lists the snake's squares in that order, each written as (row,col). Move 4 added (0,2) at the front and dropped (1,1) from the back, and move 5 only added (0,1) at the front.

A list like this, which grows at the front and shrinks at the back, is called a double-ended queue, or deque for short. Adding at the front and removing at the back each take one step, however long the snake is.

Solution Approach

Four choices remain: how to keep the squares in order, how to spot quickly that a square belongs to the snake, when to move the tail, and how to store a square.

Keeping the snake in order

Which Java class holds the list labelled body, head first? Here it is an ArrayDeque<Integer> named body, which holds each square as one whole number worked out from its row and column. Its method peekFirst() reads the head, addFirst puts a new head in front, and pollLast() removes the tail. None of the three walks through the snake.

Checking for a crash

How does a move know whether the new head lands on the snake? The simple way is to walk through body and compare each square, but that costs one step per square, so a long snake makes every move slow. Instead, the same squares are also kept in a HashSet<Integer> named occupied. Its method contains answers "is this square part of the snake?" in about one step, whatever the snake's length. Every change to body is made to occupied as well.

Moving the tail before the check

When should the tail leave? In a move without food, the tail leaves in the same step as the head arrives. So the head may move into the square the tail is leaving, and that is not a crash.

Take a board 2 wide and 2 high with food at [0,1], [1,1] and [1,0]. The moves R, D and L eat all three pieces, and the snake of four squares fills the whole board. The next move, U, takes the head to row 0, col 0, the square where the tail is. Because the tail moves away in that step, the move is fine. So move removes the tail from occupied first, and only then checks the new head. When the snake eats, the tail stays, and the check runs against the whole snake.

The wall check comes before the tail moves, since a head off the board ends the game at once.

One number per square

How is a square stored? A pair of row and column would need its own class with equals and hashCode for the set. Instead, the square at row r, col c becomes the single number r * width + c. In Example 1, with a width of 3, row 1, col 2 becomes 1 * 3 + 2 = 5. Going back, whole-number division 5 / 3 = 1 gives the row, and the remainder 5 % 3 = 2 gives the column.

Java Solution

The class has these parts:

  • The fields width and height: the board size, for the wall check.
  • The fields food and foodIndex: the pieces of food in order, and the position of the next one to eat. Since one piece is eaten at a time, foodIndex is also the score.
  • The deque body: the snake's squares head first, each stored as one number.
  • The set occupied: the same squares, for the crash check.
  • The method move: it finds the new head from the direction, returns -1 at a wall, eats or drops the tail, returns -1 if the head hits the body, and finally adds the new head to both.
  • The helpers cells and play, which only serve main: the first lists the snake's squares as (row,col), head first, and the second plays a list of moves and stops at the first -1.

The main method plays Example 1, then a 2 × 2 board where the snake fills the board and follows its tail. Last comes a board 3 wide and 1 high, where a snake of three squares turns back into itself.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;

public class DesignSnakeGame {

    private final int width, height;
    private final int[][] food;
    private int foodIndex = 0;                                // the next piece to eat
    // Snake cells, head first. A cell (r, c) is stored as r * width + c.
    private final Deque<Integer> body = new ArrayDeque<>();
    private final Set<Integer> occupied = new HashSet<>();

    public DesignSnakeGame(int width, int height, int[][] food) {
        this.width = width;
        this.height = height;
        this.food = food;
        body.addFirst(0);                                     // the snake starts at (0, 0)
        occupied.add(0);
    }

    // Returns the score after the move, or -1 if the game is over.
    public int move(String direction) {
        int head = body.peekFirst();
        int r = head / width, c = head % width;
        switch (direction) {
            case "U": r--; break;
            case "D": r++; break;
            case "L": c--; break;
            default:  c++; break;                             // "R"
        }
        if (r < 0 || r >= height || c < 0 || c >= width) {
            return -1;                                        // hit a wall
        }
        int next = r * width + c;
        boolean eats = foodIndex < food.length
                && food[foodIndex][0] == r && food[foodIndex][1] == c;
        if (eats) {
            foodIndex++;                                      // grow: the tail stays
        } else {
            occupied.remove(body.pollLast());                 // the tail leaves first
        }
        if (occupied.contains(next)) {
            return -1;                                        // ran into its own body
        }
        body.addFirst(next);
        occupied.add(next);
        return foodIndex;                                     // one point per piece eaten
    }

    // The snake's cells as (row, col), head first.
    String cells() {
        StringBuilder sb = new StringBuilder("[");
        for (int cell : body) {
            if (sb.length() > 1) sb.append(", ");
            sb.append("(").append(cell / width).append(",").append(cell % width).append(")");
        }
        return sb.append("]").toString();
    }

    static void play(String name, DesignSnakeGame game, String... moves) {
        System.out.println(name);
        for (String m : moves) {
            int score = game.move(m);
            if (score == -1) {
                System.out.println("  " + m + " -> -1   game over");
                break;
            }
            System.out.println("  " + m + " -> " + score + "    snake " + game.cells());
        }
    }

    public static void main(String[] args) {
        play("Example 1, 3 wide and 2 high:",
             new DesignSnakeGame(3, 2, new int[][] {{1, 2}, {0, 1}}),
             "R", "D", "R", "U", "L", "U");
        play("2 x 2 board, the snake fills it and follows its tail:",
             new DesignSnakeGame(2, 2, new int[][] {{0, 1}, {1, 1}, {1, 0}}),
             "R", "D", "L", "U");
        play("3 wide and 1 high, the snake turns back into itself:",
             new DesignSnakeGame(3, 1, new int[][] {{0, 1}, {0, 2}}),
             "R", "R", "L");
    }
}

Running it prints:

Output
Example 1, 3 wide and 2 high:
  R -> 0    snake [(0,1)]
  D -> 0    snake [(1,1)]
  R -> 1    snake [(1,2), (1,1)]
  U -> 1    snake [(0,2), (1,2)]
  L -> 2    snake [(0,1), (0,2), (1,2)]
  U -> -1   game over
2 x 2 board, the snake fills it and follows its tail:
  R -> 1    snake [(0,1), (0,0)]
  D -> 2    snake [(1,1), (0,1), (0,0)]
  L -> 3    snake [(1,0), (1,1), (0,1), (0,0)]
  U -> 3    snake [(0,0), (1,0), (1,1), (0,1)]
3 wide and 1 high, the snake turns back into itself:
  R -> 1    snake [(0,1), (0,0)]
  R -> 2    snake [(0,2), (0,1), (0,0)]
  L -> -1   game over

In the Example 1 block, the scores 0, 0, 1, 1 and 2, then game over, match the expected output. After U the snake is [(0,2), (1,2)], and after L it is [(0,1), (0,2), (1,2)], the two lists from the drawing.

On the 2 × 2 board, L fills all four squares with a score of 3. The next U still returns 3: the head moved into (0,0), the square the tail left in the same step, and now the head is at (0,0) and the tail at (0,1). In the last block, L sends the head from (0,2) back to (0,1). Only the tail at (0,0) leaves, so (0,1) is still body, and the move returns -1.

The order inside move matters. We also ran a version that checks occupied before removing the tail. It printed the same for Example 1 and the last game, but on the 2 × 2 board the fourth move, U, printed game over instead of a score of 3.

Complexity

A move works only on the two ends of the snake and checks one square in the set, so its cost does not grow with the snake.

  • Time: O(1) per move on average, because move does a few arithmetic steps, at most one removal at the back and one addition at the front of body, and HashSet operations that take constant time on average.
  • Space: O(n) for a snake that grows to n squares, because body and occupied each hold one number per square, while the food array is kept as given, not copied.

Another design built on a deque is Number of Recent Calls.