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 heightwidthmove(direction)
Example 1
Output: 0, 0, 1, 1, 2, -1
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.
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>bodypeekFirst()addFirstpollLast()
Checking for a crash
How does a move know whether the new head lands on the snake? The simple way is to walk through bodyHashSet<Integer>occupiedcontainsbodyoccupied
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 moveoccupied
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 equalshashCoder * width + c
Java Solution
The class has these parts:
- The fields
andwidth : the board size, for the wall check.height - The fields
andfood : 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.foodIndex - The deque
: the snake's squares head first, each stored as one number.body - The set
: the same squares, for the crash check.occupied - The method
: 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.move - The helpers
andcells , which only serveplay : 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.main
The main
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:
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)][(0,1), (0,2), (1,2)]
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 moveoccupied
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
does a few arithmetic steps, at most one removal at the back and one addition at the front ofmove , andbody operations that take constant time on average.HashSet - Space: O(n) for a snake that grows to n squares, because
andbody each hold one number per square, while theoccupied array is kept as given, not copied.food
Another design built on a deque is